springmvc拦截器
HandlerInterceptorAdapter
1,定义拦截器类
package testweb; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; public class LoginInterceptor extends HandlerInterceptorAdapter { private static final Logger log = LoggerFactory.getLogger(LoginInterceptor.class); @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { //do return true; } }
2,配置xml
<mvc:interceptors> <mvc:interceptor> <mvc:exclude-mapping path="/js/**" /> <!--******--> <mvc:exclude-mapping path="/logout" /> <bean class="testweb.LoginInterceptor" /> </mvc:interceptor> <mvc:interceptor> <mvc:exclude-mapping path="/js/**" /> <!--******--> <mvc:exclude-mapping path="/logout" /> <bean class="com.github.miemiedev.mybatis.paginator.springmvc.PageListAttrHandlerInterceptor" /> </mvc:interceptor> </mvc:interceptors>
3.拓展
spring为我们提供了org.springframework.web.servlet.handler.HandlerInterceptorAdapter这个适配器,继承此类,可以非常方便的实现自己的拦截器。他有三个方法: public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { return true; } public void postHandle( HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } public void afterCompletion( HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } 分别实现预处理、后处理(调用了Service并返回ModelAndView,但未进行页面渲染)、返回处理(已经渲染了页面) 在preHandle中,可以进行编码、安全控制等处理; 在postHandle中,有机会修改ModelAndView; 在afterCompletion中,可以根据ex是否为null判断是否发生了异常,进行日志记录。
本文来自博客园,作者:每天都要学一点,欢迎讨论和转载,转载请注明原文链接:https://www.cnblogs.com/yanan7890/p/6641689.html