Struts2核心拦截器学习笔记_struts2核心拦截器
Struts2核心拦截器学习笔记由刀豆文库小编整理,希望给你工作、学习、生活带来方便,猜你可能喜欢“struts2核心拦截器”。
Struts2的核心——拦截器
在struts2中,拦截器(Interceptor)是其核心的组件,当我们访问一个action时,我们可以通过拦截器的配置,做一些需要的操作。
我们可以写我们自己的拦截器,但是要实现或继承struts2给我们提供的接口或类。
①.我们实现Interceptor接口,该接口是struts2提供的拦截器接口,位于com.opensymphony.xwork2.interceptor包下,其提供了类似与filter的一些方法,我们必须实现它的方法:destroy()、init()、intercept(ActionInvocation)。
public cla MyInterceptor implements Interceptor {
public void destroy(){
System.out.println(“destroy”);} public void init(){ } public String intercept(ActionInvocation invocation)throws System.out.println(“init”);Exception {
System.out.println(“intercept”);
String resultString= invocation.invoke();System.out.println(“finish”);return resultString;}
②.我们可以继承AbstractInterceptor类,该类是一个抽象类,它位于com.opensymphony.xwork2.interceptor包下,它实现了Interceptor接口,并完成了对destroy()方法和init()方法的实现,但保留了抽象方法interceptor(),以供自定义的拦截器来重写其方法,完成特定的需求。
public cla MyInterceptor1 extends AbstractInterceptor {
} @Override
public String intercept(ActionInvocation invocation)throws
System.out.println(“intercept1”);
String result=invocation.invoke();
System.out.println(“finish1”);Exception { return result;}
③.上面两个是对action进行的拦截,粒度比较粗,当然struts2也给我们提供了对action中方法的拦截。这时,我们自己写的类就要继承struts
2给我们提供的方法过滤类,该
类
同
样
位
于MethodFilterInterceptor com.opensymphony.xwork2.interceptor包下,但该类已经完成了对interceptor()方法的简单实现,而提供了一个doIntercept()方法。
public cla MyInterceptor2 extends MethodFilterInterceptor { @Override
protected String doIntercept(ActionInvocation invocation)throws Exception {
System.out.println(“methodFilterInterceptor2”);String result=invocation.invoke();System.out.println(“finish2”);
return result;} }
写好了我们自己的拦截器类,还需要在struts.xml文件进行配置来告诉struts2框架,我们的拦截器要拦截的action、方法。
首先,我们要在package包下增加一个新的元素标签 ,在该标签下,我们就可以定义我们自己写的拦截器,如:
cla=“com.test.interceptor.MyInterceptor”>
定义了一个name是myInterceptor的拦截器(即实现了Interceptor接口的那个拦截器),类似的,我们定义了上面我们已写的3个拦截器。
name=“myInterceptor”
cla=“com.test.interceptor.MyInterceptor”>
请注意下面代码,我们定义了(拦截器栈),在struts2中还有拦截器栈,一个拦截器栈中可以包含多个拦截器,当我们要在某一个action上进行多个拦截时,我们可以将其放入一个拦截器栈中,这样在action中配置的时候,只需配置拦截器栈就可以了。
name=“myInterceptor”>
name=“myInterceptor1”>
defaultStack这个拦截器栈是struts2,提供的一个默认拦截器栈,其中实现了一些常用功能,如:struts2的检验框架,当我们在声明package时候会有extends属性,其值为struts-default,而defaultStack就定义在struts-default包类,进而就被我们的package所继承。
name=“defaultStack”>
在拦截器的配置中,我们可以为package配置一个默认的拦截器或拦截器栈,如果我们不指定,其值就为父包继承下来的defaultStack。
name=“myStack”>
/result.jsp
/login2.jsp /login2.jsp
/output.jsp
/succe.jsp
/register4.jsp
/succe.jsp /register2.jsp 我们在action中,对我们写的拦截器进行配置,这里要注意,我们在配置自己写的拦截器后,默认的拦截器,就不起作用了,如果还需要struts2默认的拦截器提供的功能,我们就要手动配置下了。另外,在拦截器中有
标签,可以对拦截器类中定义的属性赋值,这里是告诉拦截器,只拦截abc()方法。
abc