过滤器filter和拦截器interceptor的使用区别

过滤器filter和拦截器interceptor的使用区别:

 1 <!-- 通过过滤器Filter解决spring mvc中乱码问题 -->
 2 <filter>
 3     <filter-name>dsfasf</filter-name>
 4     <filter-class>org.springframework.web.filter.ChracterEncoding</filter-class>
 5 </filter>
 6 
 7 <filter-mapping>
 8     <filter-name>sadfdsaf</filter-name>
 9     <url-pattern>*</url-partern>
10 </filter-mapping>

通过拦截器实现:

只有一个拦截器的执行顺序:preHandler -> controller -> postHandle -> afterCompletion
多个拦截器的执行顺序:(场景记忆法:高速上的两个路口的收费站)
preHandle1 (收费站1)
preHandler2 (收费站2)
controller (目的地)
postHandler2 (收费站2)
postHandler1 (收费站1)
afterCompletion2 (收费站2)
afterCompletion1 (收费站1)

1、创建拦截器类并且实现HandlerInterceptor:

public class TestInterceptor implements HandlerInterceptor{
    
    /**
     * 表示是否要把当前请求拦截下来,
     * false,表示请求将被终止,不再进入controller方法中,
     * true,表示继续往下进行。
     * @param  表示拦截器目标对象(这里就是TestInterceptor实例化对象)
     * @return [description]
     */
    @Override
    public boolean preHandle(request, response, object){}

    /**
     * 这里可以对controller返回的结果进行修改等操作
     * @param  request      [description]
     * @param  response     [description]
     * @param  object       [description]
     * @param  modelAndView [description]
     * @return              [description]
     */
    @Override
    public postHandle(request,response, object, modelAndView){}

    /**
     * 通常应用于Controller执行结束后,资源等销毁操作。(这个不是经常用)
     * @param  request   [description]
     * @param  response  [description]
     * @param  ojbect    [description]
     * @param  Exception [description]
     * @return           [description]
     * @throws Exception [description]
     */
    @Override
    public afterCompletion(request,response, ojbect, Exception) throw Exception{}
}

2、将拦截器注册到springmvc容器中

<mvc:interceptors>
    <mvc:interceptor>
        <bean class="TestInterceptor"/>
    </mvc:interceptor>
</mvc:interceptors>

3、配置拦截器的拦截规则

<mvc:interceptors>
    <mvc:interceptor>
        <mvc:mapping path="/"></mvc:mapping>
        <bean class="TestInterceptor"/>
    </mvc:interceptor>
</mvc:interceptors>

了解内容。拦截器其它的实现方式:

实现WebRequestInterceptor(org.springframework.web.context.request.拦截器其它的实现方式:实现WebRequestInterceptor)

与HandlerInterceptor区别:
1、preHandle()方法没有返回值,意味着请求将不能终止。
2、接口的方法中参数类型不一样。只有WebRequest

拦截器的使用场景:
场景1:处理乱码问题. 

/**
 * 在拦截器中设置请求参数的编码
 * @param  args [description]
 * @return      [description]
 */
boolean preHandle(HttpServerletRequest args){
    args.setCharacterEncoding("utf-8");
    return true;
}

场景2:权限验证。比如:对用户登录进行判断。

扫描二维码关注公众号,回复: 6250399 查看本文章
/**
 * 在拦截器中设置请求参数的编码
 * @param  args [description]
 * @return      [description]
 */
boolean preHandle(HttpServerletRequest args){
    args.setCharacterEncoding("utf-8");

    //因为用户登录信息存储在session中
    if(ags.getSession().getAttribute("user") == null){
        //用户没有登录,终止请求,返回到登录页面
        args.getRequestDispatcher().forward(request,response);
        return false;
    }
    return true;
}

猜你喜欢

转载自www.cnblogs.com/yangcw/p/10878757.html