日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

玩转springboot:实现springboot自定义拦截器

發布時間:2025/3/20 50 豆豆
生活随笔 收集整理的這篇文章主要介紹了 玩转springboot:实现springboot自定义拦截器 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

一、前言

在javaee中,我們經常使用filter來做攔截器,后來有了springmvc,我們使用HandlerInterceptor進行攔截,springmvc的攔截器查看這篇文章,現在有了springboot,我們使用HandlerInterceptor進行攔截,但是我們不用xml的配置,省了很多的事情。

二、springboot攔截器使用

1、設置攔截器
/*** @author 歐陽思海* @date 2018/7/26 10:08* 攔截器測試*/ public class TestInterceptor implements HandlerInterceptor {//目標方法執行之前@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler) throws Exception {if(true){System.out.println("已經進行攔截了。。。。。。。。");return false;}return true;}@Overridepublic void postHandle(HttpServletRequest request, HttpServletResponse response, Objecthandler, ModelAndView modelAndView) throws Exception {}@Overridepublic void afterCompletion(HttpServletRequest request, HttpServletResponse response,Object handler, Exception ex) throws Exception {}}

這里如果攔截成功,會輸出:

已經進行攔截了。。。。。。。。
2、攔截器注冊

在springmvc的時候,我們這里使用的是xml進行配置的,但是,在springboot中,我們使用java配置,具體用法如下:

//使用WebMvcConfigurerAdapter可以來擴展SpringMVC的功能 //@EnableWebMvc 不要接管SpringMVC @Configuration public class MyMvcConfig extends WebMvcConfigurerAdapter {//注冊攔截器2@Overridepublic void addInterceptors(InterceptorRegistry registry) {/*addPathPatterns 用于添加攔截規則excludePathPatterns 用戶排除攔截*/registry.addInterceptor(new TestInterceptor()).addPathPatterns("/**").excludePathPatterns("/index.html", "/", "/user/login");} }

解釋:

上面攔截器的注冊,首先,我們使用addPathPatterns("/**")添加了所有的都攔截。

然后,在使用excludePathPatterns("/index.html", "/", "/user/login")將index.html和/user/login兩個url設置不攔截。

注意注冊時的區別

registry.addInterceptor(getInterfaceAuthCheckInterceptor()).addPathPatterns("/api/**"):這種方式無論什么情況都可以

registry.addInterceptor(new InterfaceAuthCheckInterceptor()).addPathPatterns("/api/**"):這種情況時,自定義的interceptor中不能注入其他內容,比如redis或者其他service,如果要注入,必須使用上面這種方法

下面我們寫個controller進行測試。

3、controller測試
/*** @author 歐陽思海* @date 2018/7/25 9:57*/ @Controller public class HelloworldController {@ResponseBody@RequestMapping("/hello")public String hello(){return "Hello World!";} }

這里我們在瀏覽器輸入:http://localhost:8080/test

后臺輸出結果:

已經進行攔截了。。。。。。。。

攔截器使用完畢!

總結

以上是生活随笔為你收集整理的玩转springboot:实现springboot自定义拦截器的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。