`

010 - Interceptor

阅读更多

1. 自定义Interceptor

//MyInterceptor.java

public class MyInterceptor extends AbstractInterceptor {

 

 public String intercept(ActionInvocation invocation) throws Exception {


  long start = System.currentTimeMillis();       //Action前做点事


  String r = invocation.invoke();                     //调用Action中的某个方法


  long end = System.currentTimeMillis();        //Action 执行后再做点事


  System.out.println("action time = " + (end - start));
  return r;


 }

}

 

 

 

//struts.xml

<struts>


 <constant name="struts.devMode" value="true"></constant>
 <package name="test" namespace="/" extends="struts-default">
          <interceptors>
                   <interceptor name="my" class="MyInterceptor"/>  //向struts2注册自己的Interceptor
          </interceptors>


          <action name="test" class="TestAction">
                    <result>/test.jsp</result>

                    <!-- 注意两个interceptor-ref的顺序, 顺序不同, 执行效果也不同: 先配置的先执行/后配置的先退出(先进后出) --> 
                     <interceptor-ref name="my"></interceptor-ref>                    //应用到这个Action上
                     <interceptor-ref name="defaultStack"></interceptor-ref>


           </action>

 </package>


</struts>

 

 

2. 使用token拦截器防止重复提交

 //struts.xml

<struts>

     <constant name="struts.devMode" value="true"></constant>
     <package name="test" namespace="/" extends="struts-default">
  
     <action name="input" class="InputAction">
              <result>/input.jsp</result>
     </action>

 

     <action name="user" class="UserAction">
             <result>/addOK.jsp</result>
      
            <interceptor-ref name="defaultStack"></interceptor-ref>


            <interceptor-ref name="token"></interceptor-ref>
            <result name="invalid.token">/error.jsp</result>


     </action>

 </package>

</struts>

 

 

//表单的写法

    <form action="user" method="post">
            name:<input name="name">
            age:<input name="age">
            <input type="submit" value="add">

            <s:token></s:token>
    </form>

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics