拦截器的使用

2018-09-11 12:21 更新

拦截器是在执行Action类方法前或后执行的类方法,可以注解方式指定,也可以在配置文件myhibernate.xml中配置。

分为全局拦截器:所有的控制层的Action类方法都会被拦截执行

类拦截器:只拦截指定的Action类里面的所有方法

方法拦截器 : 只拦截指定的Action类里面的特定的方法


拦截器的编写

package demo.interceptor;
import org.myhibernate.mvc.intercept.ActionInvocation;
import org.myhibernate.mvc.intercept.Interceptor;

public class DemoInterceptor implements Interceptor
{
	public void doIntercept(HttpServletRequest request, HttpServletResponse response,ActionInvocation invocation) 
	{
		System.out.println("DemoInterceptor doIntercept before");
		invocation.invoke();
		System.out.println("DemoInterceptor doIntercept after");
	}
}


1、全局拦截器

 在web.xml的过滤器中配置全局拦截器如下

	<filter>
		<filter-name>/filter</filter-name>
		<filter-class>org.myhibernate.mvc.filter.DispatchFilter</filter-class>
		<init-param>
			<param-name>global.interceptor</param-name>
			<param-value>demo.interceptor.DemoInterceptor</param-value>
		</init-param>
	</filter>

修改之前的h1()方法,如下


@ActionAnnotation(interceptors={DemoInterceptor.class})
public void h1()
	{
		System.out.println("h1 hello word");
		out.print("h1 hello word");
	}
	

在浏览器中访问h1方法,控制台输出如下

h1



2、类拦截器

类拦截器配置方法如下

@ActionAnnotation(interceptors={DemoInterceptor.class})
public class HelloWord extends Action
{

}

则该拦截器对该类里面的所有方法都会进行拦截执行


3、方法拦截器

方法拦截器配置方法如下

@ActionAnnotation(interceptors={DemoInterceptor.class})
	public void h1()
	{
		System.out.println("h1 hello word");
		out.print("h1 hello word");
	}

方法拦截器只拦截指定的方法


也可以在配置文件myhibernate.xml中配置拦截器,如下

<?xml version="1.0" encoding="UTF-8" ?>
<mappings>
	<interceptors>
		<action name="helloword" interceptor="demo.action.Interceptor2">
			<method name="h1" interceptor="demo.action.Interceptor2"  ></method>
			<method name="h2" interceptor="demo.action.Interceptor2,demo.action.TestInterceptor"  ></method>
		</action>
	</interceptors>
	 
</mappings>

多个拦截器以英文模式的逗号,分隔开



以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号