Spring MVC 之拦截器(八)

 在springMVC中实现拦截器有两种方式

1、实现HandlerInterceptor接口

2、继承HandlerInterceptorAdaptor类

编写拦截器:

 1 package com.cy.springannotation.interceptor;
 2 
 3 import javax.servlet.http.HttpServletRequest;
 4 import javax.servlet.http.HttpServletResponse;
 5 
 6 import org.apache.log4j.Logger;
 7 import org.springframework.web.servlet.HandlerInterceptor;
 8 import org.springframework.web.servlet.ModelAndView;
 9 /**
10  * 拦截器
11  * @author acer
12  *
13  */
14 public class MyIntercetor implements HandlerInterceptor{
15     private Logger log=Logger.getLogger(this.getClass());
16 
17     @Override
18     public void afterCompletion(HttpServletRequest arg0,
19             HttpServletResponse arg1, Object arg2, Exception arg3)
20             throws Exception {
21         log.info("1---afterCompletion方法-----DispatcherServlet完全处理完请求后被调用,往往执行一些资源清理动作");
22     }
23 
24     @Override
25     public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
26             Object arg2, ModelAndView arg3) throws Exception {
27         log.info("1---postHandle方法----------Controller方法后");
28     }
29 
30     @Override
31     public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1,
32             Object arg2) throws Exception {
33         log.info("1---preHandle方法-----------Controller方法前");
34         //如返回为false的时候,拦截器可阻止方法的调用 ,默认返回false
35 //        return false;
36         return true;
37     }
38 
39 }

在springAnnotation-servlet.xml里配置:

 

1  <!-- 配置拦截器 -->
2       <mvc:interceptors>
3         <mvc:interceptor>
4           <mvc:mapping path="/login.do"/>
5           <bean class="com.cy.springannotation.interceptor.MyIntercetor"></bean>
6         </mvc:interceptor>
7      </mvc:interceptors> 

 配置多个拦截器的时候:

 1 <!-- 配置拦截器 -->
 2       <mvc:interceptors>
 3         <mvc:interceptor>
 4           <mvc:mapping path="/login.do"/>  <!-- 如果不配置mapping则默认所有请求均被该拦截器拦截 -->
 5           <bean class="com.cy.springannotation.interceptor.MyIntercetor"></bean>
 6         </mvc:interceptor>
 7         <mvc:interceptor>
 8           <mvc:mapping path="/*"/>
 9           <bean class="com.cy.springannotation.interceptor.SecondIntercetor"></bean>
10         </mvc:interceptor>
11      </mvc:interceptors> 

 

 

登录拦截:

Spring MVC 之拦截器(八)

 

控制台显示:

Spring MVC 之拦截器(八)

 

上一篇:AndroidStudio 编译异常java.lang.OutOfMemoryError: GC overhead limit exceeded


下一篇:Swift 绘图板功能完善以及终极优化