码迷,mamicode.com
首页 > 编程语言 > 详细

SpringBoot(三)HandlerInterceptor

时间:2018-05-27 13:39:37      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:system   pat   extend   nbsp   inter   creat   created   mvc   beans   

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");
    }
}

 

SpringBoot(三)HandlerInterceptor

标签:system   pat   extend   nbsp   inter   creat   created   mvc   beans   

原文地址:https://www.cnblogs.com/chenss15060100790/p/9095394.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!