Loading

自定义拦截器

一.什么是自定义拦截器?

顾名思义,就是用户自己定义的并实现的拦截器。虽然Sturts2中已经有了一些拦截器,但并不能完全满足我们的开发需求,有时,我们需要自己来开发拦截器以满足需求。

二.如何开发自定义拦截器?
再Struts2中,所有拦截器都要实现com.opensymphony.xwork2.interceptor.Interceptor接口:

public interface Interceptor extends Serializable
{

     //用于释放资源
     public abstract void destroy();
     
    //用于初始化一些相关资源
    public abstract void init();
    
      //此方法就是拦截器执行的处理方法,用户要实现的功能就写着这里面
    public abstract String intercept(ActionInvocation actioninvocation)  throws Exception;
}

1.如果我们在intercept方法中写了 invocation.invoke();
意味着继续运行拦截器后续的处理,如果这个拦截器后面还有拦截器,接着拦截,一直运行到Action,然后执行Result。

如果没有,意味着对请求的运行处理到此为止,不再继续向后运行了,直接处理去Result了。

2.在 invocation.invoke(); 这句话之前写的功能会在Action运行之前执行。

3.在 invocation.invoke(); 这句话之后写的功能会在Result运行之后执行。

4.intercept方法返回的值就是最终要返回的Result字符串。

三.例子
首先,创建一个java类实现此接口:

package interceptor;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

public class MyInterceptor implements Interceptor{
	
	public void destroy()
	{
		System.out.println("MyInterceptor销毁");
	}
	public void init()
	{
		System.out.println("MyInterceptor初始化");
	}
	
	public String intercept(ActionInvocation invocation) throws Exception
	{
		System.out.println("在action执行之前");
		String result=invocation.invoke();
		System.out.println("在Result运行之后");
		
		return result;
	}

}

然后再Struts.xml里面配置拦截器的声明和引用:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
        "http://struts.apache.org/dtds/struts-2.5.dtd">
 <struts>
 
 <constant name="struts.devMode" value="true"/>
 <constant name="struts.locale" value="zh_CN"/>
 <constant name="struts.i18n.encoding" value="UTF-8"/>
 
 <package name="struts2" extends="struts-default">
 <interceptors>
  <interceptor name="myInterceptor" class="interceptor.MyInterceptor"/>
 </interceptors>
 
 
   <action name="helloworldAction" class="cn.javass.hello.struts2impl.action.HelloWorldAction">
     <result name="success">/Text01/welcome.jsp</result> 
     <interceptor-ref name="myInterceptor"/>
   </action>
 
 </package>

最后,执行相应的操作后有可以看到:
在这里插入图片描述

posted @ 2020-04-21 21:15  文牧之  阅读(30)  评论(0)    收藏  举报  来源