zoukankan      html  css  js  c++  java
  • SpringBoot(三)HandlerInterceptor

    HandlerInterceptor

    拦截器用的机会不多,在这里做数据签名校验不错,不过更多的人喜欢写Filter,

    这个切面神奇的地方是:可以在页面渲染的不同阶段使用Writer。

    (因为替代方案太多,基本得不到应用)

    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");
        }
    }
  • 相关阅读:
    Problem: 八中上厕所
    Problem: 最短路上的统计
    股票买卖问题
    Redis(十二)——Redis为什么是单线程的?
    链表题汇总
    Redis(十一)——集群模式
    Redis(十)——哨兵模式
    Redis(九)——主从复制
    Redis(八)——客户端与服务器
    Redis(七)——事件
  • 原文地址:https://www.cnblogs.com/chenss15060100790/p/9095394.html
Copyright © 2011-2022 走看看