zoukankan      html  css  js  c++  java
  • java struts学习-拦截器

    引言:

    Struts2拦截器,每个拦截器类只有一个对象实例,即采用单例模式,所有引用这个拦截器的Action都共享这一拦截器类的实例,因此,在拦截器中如果使用类变量,要注意同步问题。

    •       拦截器是在访问某个方法,字段之前或之后实施拦截。

    •       拦截器是AOP的一种实现

    •       拦截器栈(Interceptor Stack)

    –      拦截器栈就是将拦截器按一定的顺序联结成一条链。

    –      在访问被拦截的方法或字段时,拦截器链中的拦截器就会按其之前定义的顺序被调用。

    •       实现原理

    –      Struts2拦截器的实现原理相对简单,当请求struts2的action时,Struts 2会查找配置文件,并根据其配置实例化相对应拦截器对象,然后串成一个列表,最后一个一个地调用列表中的拦截器。

    代码详解

     1 //要实现自定义拦截器需要继承一个MethodFilterceptor类
     2 public class LoginInterceptor extends MethodFilterInterceptor{
     3    private Map<String,Object> session=null;
     4    protected String doIntercept(ActionInvocation actionInvocation) throws          Exception{
     5       session = ActionContext.getContext().getSession();
     6       Object use=session.get("user");
     7       if(user!=null){
     8           return actionInvocation.invoke();//允许通过
     9       }else{
    10           return "login";
    11       }
    12     }
    13 }
    //在struts.xml配置文件中使用自定义的拦截器
    <interceptors>
         //自定义拦截器栈
         <interceptor name="loginInterceptor" class="com.nf.action.LoginInterceptor"></interceptor>
         <interceptor-stack name="myStack">
             <interceptor-ref name="loginInterceptor">
                      <param name="excludeMethods">loginView,login</param> //excludeMethods表示排除指定的方法,即不对标记为excludeMethods的方法进行拦截,
             </interceptor-ref>
         </interceptor-stack>
    </interceptors>
    //配置一个默认拦截器,也就是所有的Action都会被拦截,除了param-->
    <default-interceptor-ref name="myStack">
  • 相关阅读:
    03_ if 练习 _ little2big
    uva 11275 3D Triangles
    uva 12296 Pieces and Discs
    uvalive 3218 Find the Border
    uvalive 2797 Monster Trap
    uvalive 4992 Jungle Outpost
    uva 2218 Triathlon
    uvalive 3890 Most Distant Point from the Sea
    uvalive 4728 Squares
    uva 10256 The Great Divide
  • 原文地址:https://www.cnblogs.com/Crezy/p/7645678.html
Copyright © 2011-2022 走看看