springmvc 拦截器(springmvc教程六)

工程代码

github: https://github.com/dengjili/springmvc

拦截器的使用

定义一个拦截器

public class MyInterceptor implements HandlerInterceptor {

	private static final Logger logger = LoggerFactory.getLogger(MyController.class);

	// 前置方法  若返回false,则直接结束
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		logger.debug("=>{}", "preHandle");
		return true;
	}

	// 后置方法
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		logger.debug("=>{}", "postHandle");
	}

	// 视图结束后方法
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		logger.debug("=>{}", "afterCompletion");
	}

}

配置拦截器

<!-- 拦截器配置 -->
	<mvc:interceptors>
		<mvc:interceptor>
			<mvc:mapping path="/attribute/*" />
			<bean class="priv.dengjl.interceptor.MyInterceptor" />
		</mvc:interceptor>
	</mvc:interceptors>

多个拦截器的顺序

定义一个新拦截器

public class MyInterceptor2 implements HandlerInterceptor {

	private static final Logger logger = LoggerFactory.getLogger(MyController.class);

	// 前置方法  若返回false,则直接结束
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		logger.debug("=>{}", "preHandle2");
		return true;
	}

	// 后置方法
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		logger.debug("=>{}", "postHandle2");
	}

	// 视图结束后方法
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		logger.debug("=>{}", "afterCompletion2");
	}

}

配置拦截器

<!-- 拦截器配置 -->
	<mvc:interceptors>
		<mvc:interceptor>
			<mvc:mapping path="/attribute/*" />
			<bean class="priv.dengjl.interceptor.MyInterceptor" />
		</mvc:interceptor>
		<mvc:interceptor>
			<mvc:mapping path="/attribute/*" />
			<bean class="priv.dengjl.interceptor.MyInterceptor2" />
		</mvc:interceptor>
	</mvc:interceptors>

输出结果

=>preHandle
=>preHandle2
=>postHandle2
=>postHandle
=>afterCompletion2
=>afterCompletion

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值