在上一篇文章中说了拦截器的原理,但是没有实践是永远不行的,所以下面就来看看拦截器是如何工作的:
无非也就是那么几个步骤:
1、编写页面jsp
2、配置Action
3、编写拦截器Interceptor
4、在配置文件中配置拦截器及要拦截的对象。
一、拦截器的简单应用
无非也就是那么几个步骤:
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>
二、其余的拦截器
在上面的应用中我们直接实现的的
Interceptor接口,在这个接口中我们要实现三个方法:
destroy,
init,
intercept。除此之外还有另外两个拦截器,如下:
1)
AbstractInterceptor,其实现接口Interceptor。如果没有特别需求的话,我们只需要继承
AbstractInterceptor类,然后在其中编写
intercept方法即可。
2)
MethodFilterInterceptor,期继承抽象类
AbstractInterceptor。其主要是针对方法的,其中封装了两个参数
excludeMethods和
includeMethods。
其含义:不包含方法和包含方法。意思是如果配置了这两个参数,当拦截时根据配置的不同而对方法处理时采取不拦截和拦截策略。
3)上面两种在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>