spring mvc拦截器的使用记录

来源:互联网 发布:淘宝网和易趣网的区别 编辑:程序博客网 时间:2024/04/28 22:01

今天项目中需要使用到spring mvc的拦截器,将使用心得记录一下:

导包的哪些啥就不说了,下面说下具体的使用步骤:

1:其实spring mvc中有两个拦截器,一种是实现HandlerInceptor,另一种是实现WebRequestInterceptor

其中有三个方法:

preHandle():在请求到达controller之前调用,filter执行之后调用,根据返回的boolean值决定是否要往下执行,如果要在当中跳转页面,那么就需要用到response重定向

postHandle():在controller方法执行完毕之后,在DispatcherServlet进行视图返回渲染之前被调用,所以我们可以在这个方法中对Controller处理之后的ModelAndView对象   进行操作。postHandle方法被调用的方向跟preHandle是相反的,也就是说先声明的Inceptor的postHandle方法反而会后执行。

afterCompletion():该方法是在整个请求结束之后,也就是说在DispatcherServlet渲染了对应的视图 之后执行,主要作用是用于进行资源的清理。

2:自定义的拦截器类如:

public class PermissionInterceptor implements HandlerInterceptor{
public void afterCompletion(HttpServletRequest arg0,
HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
}
public void postHandle(HttpServletRequest req, HttpServletResponse res,
Object arg2, ModelAndView arg3) throws Exception {
}
public boolean preHandle(HttpServletRequest req, HttpServletResponse res,
Object arg2) throws Exception {
System.out.println("preHandle");
Integer userCount = (Integer) req.getSession().getServletContext().getAttribute("userCount");
String username = (String) req.getSession().getAttribute("username"+userCount);
System.out.println("拦截器中的username "+username);
if(username == null){
res.sendRedirect("toLogin");
return false;
}
return true;
}


3:在spring配置文件中进行配置:如

<!-- 配置spring mvc拦截器 -->
<mvc:interceptors>
<mvc:interceptor>
<!-- 配置拦截所有请求 -->
<mvc:mapping path="/**"/>
<!-- 配置放开哪些请求 -->
<mvc:exclude-mapping path="/user/toLogin"/>
<mvc:exclude-mapping path="/user/login"/>
<mvc:exclude-mapping path="/user/findByNfcId"/>
<mvc:exclude-mapping path="/user/saves"/>
<!-- 自定义的拦截器类,继承自HandlerInterceptor -->
<bean class="com.henghao.nfc.interceptor.PermissionInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>

0 0