無非也就是那麼幾個步驟:
1、編寫頁面jsp
2、配置Action
3、編寫攔截器Interceptor
4、在配置文件中配置攔截器及要攔截的對象。
一、攔截器的簡單應用
1、Login.jsp
<form action="LoginAction.action"> username:<input type="text" name="username"><br> password:<input type="text" name="password"><br> age:<input type="text" name="age"><br> date:<input type="text" name="date"><br> <input type="submit" value="submit"> </form>
2、LoginAction
public class LoginAction extends ActionSupport implements ModelDriven<Person> { private Person person=new Person(); @Override public Person getModel() { return person; } @Override public String execute() throws Exception { return SUCCESS; } }
3、Interceptor
public class TheInterceptor implements Interceptor { private String testString; //get、set方法省略... @Override public void destroy() { // TODO Auto-generated method stub } @Override public void init() { System.out.println("init invoked!"); System.out.println(testString); } @Override public String intercept(ActionInvocation invocation) throws Exception { System.out.println("before!"); String result= invocation.invoke(); System.out.println("after!"); return null; } }
4、配置struts.xml
<struts> <package name="struts2" extends="struts-default"> <!-- 配置interceptor --> <interceptors> <interceptor name="theInterceptor" class="com.tgb.interceptor.TheInterceptor"> <param name="testString">tgb</param> </interceptor> </interceptors> <action name="LoginAction" class="com.tgb.struts2.LoginAction"> <result name="success">/success.jsp</result> <result name="input">/index.jsp</result> <!-- 引用攔截器 --> <interceptor-ref name="theInterceptor"></interceptor-ref> <interceptor-ref name="defaultStack"></interceptor-ref> </action> </package> </struts>
<package name="struts2" extends="struts-default"> <interceptors> <!-- 繼承抽象類AbstractInterceptor --> <interceptor name="theInterceptor2" class="com.tgb.interceptor.TheInterceptor2"> </interceptor> <!-- 繼承抽象類 MethodFilterInterceptor --> <interceptor name="theInterceptor3" class="com.tgb.interceptor.TheInterceptor3"> </interceptor> </interceptors> <action name="LoginAction" class="com.tgb.struts2.LoginAction"> <result name="success">/success.jsp</result> <result name="input">/index.jsp</result> <interceptor-ref name="theInterceptor2"></interceptor-ref> <interceptor-ref name="theInterceptor3"> <!-- 配置參數是否攔截該方法 --> <param name="includeMethods">execute</param> </interceptor-ref> <interceptor-ref name="defaultStack"></interceptor-ref> </action> </package>