您的位置:首页 > 编程语言 > Java开发

struts2--拦截器

2016-07-26 16:02 267 查看

struts的拦截器:
1、流程:
  访问action,首先到过滤器里面,分发到不同的action里面.在过滤器中执行一系列的拦截器;
2、过滤器与拦截器的区别:
 过滤器:到目标资源之前进行过滤,可以过滤所有内容(action,jsp,html);拦截器:到目标资源之前进行拦截,只能拦截action;
3、拦截器的使用原理:
 aop:面向方面编程,底层采用动态代理的方式
 责任链模式:有一组操作,栓在一条线上,当一个操作执行完成之后,到下一个操作
4、拦截器的执行过程:
 访问action时候,首先到StrutsPrepareAndExecuteFilter过滤器里面
 [此类中有init方法:用来加载配置文件;doFilter方法:执行默认的拦截器],
 在过滤器里面doFilter方法里面执行[executeAction方法执行拦截器]多个拦截器,
 并生成当前action的代理的对象[
  ActionProxy proxy = config.getContainer().getInstance(ActionProxyFactory.class).createActionProxy(
                    namespace, name, method, extraContext, true, false);
 ],当拦截器执行完成之后,执行invoke方法,执行下一个拦截器
5、拦截器的结构:
  拦截器继承AbstractInterceptor类,这个类实现 Interceptor接口
  在类中有三个生命周期的方法
  init  intercept  destroy
  拦截的逻辑写在 intercept方法里面

自定义拦截器:
1)、创建一个类继承AbstractInterceptor类
2)、重写intercept方法,在此方法中写拦截逻辑
3)、注册自定义的拦截器
/*
  * 判断是否是登录?
  *  = 判断session里面是否有user对象,如果有登录,不存在没有登录
 */
 public String intercept(ActionInvocation invocation) throws Exception {
  //推荐使用得到 actionContext方式进行操作
  ActionContext context = invocation.getInvocationContext();
  //得到session里面的值
  Object object = context.getSession().get("user");
  //判断是否为空
  if(object != null) { //已经登录
   //执行下一个操作
   return invocation.invoke();
  } else {//没有登录
   return Action.LOGIN;
  }
 }
 
注册拦截器:
声明拦截器:
 (1)在action所在的package里面声明自定义的拦截器
  <interceptors>
   <interceptor name="loginInterceptor"  class="cn.xxx.demo4.MyInterceptor"></interceptor>
  </interceptors>
使用拦截器:
 (2)在action里面使用声明的拦截器
  <interceptor-ref name="loginInterceptor"></interceptor-ref>
 (3)使用自定义拦截器,默认继承的拦截器会失效,需要显示的声明出来
  <interceptor-ref name="defaultStack"></interceptor-ref>
第二种注册方式:
声明拦截器:
 (1)在action所在包里面声明拦截器,定义stack,把拦截器的引入写在stack里面
  <interceptors>
   <interceptor name="loginInterceptor" class="cn.xxx.demo4.MyInterceptor"></interceptor>
   <interceptor-stack name="myStackLogin">
    <interceptor-ref name="defaultStack"></interceptor-ref>[***]
    <interceptor-ref name="loginInterceptor"></interceptor-ref>
   </interceptor-stack>
  </interceptors>
使用拦截器:
  (2)在action直接使用定义的stack就可以了
  <interceptor-ref name="myStackLogin"></interceptor-ref>  

addFieldError和addActionError区别
 (1)addFieldError指表单输入数据有误
 (2)addActionError指业务问题

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: