SpringBoot(三)HandlerInterceptor

來源:互聯網
上載者:User

標籤: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. */@Configurationpublic class ApplicationConfigurer extends WebMvcConfigurerAdapter {    @Override    public void addInterceptors(InterceptorRegistry registry) {        super.addInterceptors(registry);        registry.addInterceptor(new TestInterceptor())                .addPathPatterns("/**.ftl","/**.json");    }}

 

SpringBoot(三)HandlerInterceptor

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.