Spring Boot攔截器實(shí)現(xiàn)步驟及測(cè)試實(shí)例
第一步,定義攔截器:
package com.zl.interceptor; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class myInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("preHandle"); return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("preHandle"); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("preHandle"); } }
控制臺(tái)打印三個(gè)輸出語(yǔ)句,作為測(cè)試。
第二步:配置攔截器
package com.zl.interceptor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebMVCConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(myInterceptor()).addPathPatterns("/**"); } @Bean myInterceptor myInterceptor(){ return new myInterceptor(); } }
將定義的攔截器注入到這個(gè)配置方法中,并攔截所有路徑。
第三步:寫(xiě)個(gè)接口測(cè)試
package com.zl.interceptor; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class helloController { @GetMapping("/hello") public String hello(){ return "hello"; } }
測(cè)試結(jié)果
定義的攔截器三個(gè)方法都執(zhí)行了。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
JAVA設(shè)計(jì)模式之建造者模式原理與用法詳解
這篇文章主要介紹了JAVA設(shè)計(jì)模式之建造者模式,簡(jiǎn)單說(shuō)明了建造者模式的原理、組成,并結(jié)合實(shí)例形式分析了java建造者模式的定義與用法,需要的朋友可以參考下2017-08-08SpringBoot實(shí)現(xiàn)動(dòng)態(tài)數(shù)據(jù)源切換的方法總結(jié)
項(xiàng)目開(kāi)發(fā)中經(jīng)常會(huì)遇到多數(shù)據(jù)源同時(shí)使用的場(chǎng)景,比如冷熱數(shù)據(jù)的查詢(xún)等情況,所以接下來(lái)本文就來(lái)介紹一下如何使用實(shí)現(xiàn)自定義注解的形式來(lái)實(shí)現(xiàn)動(dòng)態(tài)數(shù)據(jù)源切換吧2023-12-12Java中HttpServletResponse響應(yīng)中文出現(xiàn)亂碼問(wèn)題
這篇文章主要介紹了Java中HttpServletResponse響應(yīng)中文出現(xiàn)亂碼問(wèn)題的相關(guān)資料,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2016-06-06詳解MyBatis-Plus Wrapper條件構(gòu)造器查詢(xún)大全
這篇文章主要介紹了詳解MyBatis-Plus Wrapper條件構(gòu)造器查詢(xún)大全,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-08-08MyBatis-Plus如何使用枚舉自動(dòng)關(guān)聯(lián)注入詳解
這篇文章主要給大家介紹了關(guān)于MyBatis-Plus如何使用枚舉自動(dòng)關(guān)聯(lián)注入的相關(guān)資料,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用MyBatis-Plus具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2022-03-03