【Spring专题-④】拦截器浅析

来源:互联网 发布:windows用airplay 编辑:程序博客网 时间:2024/05/22 03:45

【声明】

文章内容根据网络资料整理而成,复习用!

1.前言

SpringMVC 中的Interceptor 拦截器也是相当重要和相当有用的,它的主要作用是拦截用户的请求并进行相应的处理。比如通过它来进行权限验证,或者是来判断用户是否登陆,或者是像12306 那样子判断当前时间是否是购票时间。

2.定义&配置

①applicationContext.xml配置文件中添加 <mvc:interceptors>

<mvc:interceptors><mvc:interceptor><mvc:mapping path="/**"/><!-- 过滤掉resources静态资源目录 --><mvc:exclude-mapping path="/resources/**"/><bean class="cn.demo.springIntercept.filter.MyInterceptor"/></mvc:interceptor></mvc:interceptors>

②自定义拦截器

public class MyInterceptor extends HandlerInterceptorAdapter {public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {System.out.println("pre Interceptor..............................."); String name = request.getParameter("name");if(null == name || "".equals(name)){response.setCharacterEncoding("utf-8");response.setContentType("text/html");response.getWriter().println("msg: name is null,please check you name!");return false;}else{super.preHandle(request, response, handler);}return super.preHandle(request, response, handler);}}

注意:

HandlerInterceptorAdapter
实现AsyncHandlerInterceptor接口的抽象类,一般我们使用拦截器的话都会继承这个类。然后复写相应的方法。


3.源码分析

Web请求被DispatcherServlet截获后,会调用DispatcherServlet的doDispatcher方法。


核心处理请求的代码片段:


【参考】

http://www.cnblogs.com/Leo_wl/p/3779547.html
SpringMVC拦截器详解

http://haohaoxuexi.iteye.com/blog/1750680
SpringMVC中使用Interceptor拦截器

0 0