springboot2 - HandlerInterceptor

这个接口功能强劲,因为可以直接调用 request、response,能想到的切面代码基本都能写到这里。

但是它的地位很尴尬,人人都认识,但是没人用它:

  • 如果想做拦截器,一般会用 Filter;
  • 做数据校验、签名等,使用特定的接口,而不会直接用它;
  • 个人也不推荐使用,因为功能太大了,应当预留给更有必要的的业务。

一下子想到的场景:应付面试,因为面试经常问,Interceptor 和 Filter 的区别。

区别如下:

  • 只用 servlet 就可以开发 web 项目,而 spring 并不是必要的;
  • Filter 是 servlet 原生的,引入 spring 之后,才多了 Interceptor 选项;
  • JavaWeb执行流程:filter -> servlet
  • springMVC执行流程:filter -> servlet -> interceptor -> controller。
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 请求拦截器,
 *
 * Created by 12614 on 2018/5/11.
 */
public class TestInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        System.out.println("TestInterceptor: preHandle");
        //TODO 请求拦截处理逻辑
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        System.out.println("TestInterceptor: postHandle");

        //TODO 页面渲染前置逻辑
        //E.G.
        httpServletResponse.getWriter().write("-----------------------");
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        System.out.println("TestInterceptor: afterCompletion");

        //TODO 页面渲染后置逻辑
        //E.G.
        httpServletResponse.getWriter().write("========================");
    }
}

spring 配置

<mvc:interceptors>
   <mvc:interceptor>
        <!--进行拦截的路径-->
        <mvc:mapping path="/**"/> 
        <!--不进行拦截的路径-->   
        <mvc:exclude-mapping path="/lib/**" /> 
        <beans:bean class="xxxxx全类名"/>
    </mvc:interceptor>
</mvc:interceptors>

springboot 配置

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * Created by 12614 on 2018/5/11.
 */
@Configuration
public class ApplicationConfigurer extends WebMvcConfigurerAdapter {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        super.addInterceptors(registry);
        registry.addInterceptor(new TestInterceptor())
                .addPathPatterns("/**.ftl","/**.json");
    }
}

posted on 2018-05-27 11:00  疯狂的妞妞  阅读(706)  评论(0编辑  收藏  举报

导航