【Java Web学习笔记】04-添加一个SpringMVC拦截器

ScarletLina 2016-05-03

Spring MVC提供拦截器Interceptor可以将特别的功能应用到指定的请求,例如:鉴权、日志等。拦截器的功能和应用场景与过滤器Filter有点像,但更强大,包含了AOP的思想。过滤器在请求的逻辑前执行,而拦截器在请求前后都可以执行。

 

拦截器需要实现HandlerInterceptor接口,三个方法。分别是:在处理器执行前的方法preHandle(..);在处理器执行后的方法postHandle(..);在请求结束后的方法afterCompletion(..)。SpringMVC提供了一个适配器类HandlerInterceptorAdapter。拦截器直接继承适配器,则只需要实现自己需要的方法,不用完全实现三个方法。参考跟开涛学SpringMVC写的一个简单的性能监控拦截器,代码如下:

 

package com.lz.quick.web.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.core.NamedThreadLocal;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class DefaultInterceptor implements HandlerInterceptor {

	private static final Logger log = LogManager
			.getLogger(DefaultInterceptor.class);

	private NamedThreadLocal<Long> startTimeThreadLocal = new NamedThreadLocal<Long>(
			"StopWatch-StartTime");

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler, ModelAndView mv)
			throws Exception {
		long endTime = System.currentTimeMillis();
		long beginTime = startTimeThreadLocal.get();
		long consumeTime = endTime - beginTime;
		if (consumeTime > 500) {
			log.warn("performance suffer: {} cost {}.",
					request.getRequestURI(), consumeTime);
		}
		else {
			log.debug("performance suffer: {} cost {}.",
					request.getRequestURI(), consumeTime);
		}
		log.exit(request.getRequestURI());
	}

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		log.entry(request.getRequestURI());
		long beginTime = System.currentTimeMillis();
		startTimeThreadLocal.set(beginTime);
		return log.exit(true);
	}

}

 

注册拦截器使用<mvc:interceptors>元素。拦截器配置:

 

<mvc:interceptors>
	<mvc:interceptor>
		<mvc:mapping path="/**"/>
		<bean class="com.lz.quick.web.interceptor.DefaultInterceptor"></bean>
	</mvc:interceptor>
</mvc:interceptors>

更多代码参见【Java Web学习笔记】03-练习的web工程

相关推荐