5.1 回顧SpringMVC使用攔截器步驟
- 自定義攔截器類,實現HandlerInterceptor接口
- 注冊攔截器類
5.2 Spring Boot使用攔截器步驟
5.2.1 按照Spring MVC的方式編寫一個攔截器類,實現HandlerInterceptor接口
在03-springboot-web中創建interceptor包,並創建一個LoginInterceptor攔截器
代碼示例:
package com.bjpowernode.springboot.interceptor; import org.springframework.web.servlet.HandlerInterceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class LoginInterceptor implements HandlerInterceptor { @Override //進入Controller之前執行該方法 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { //登錄攔截的業務邏輯 System.out.println("-------登錄請求攔截器--------------"); System.out.println(request.getRequestURI().toString()); Object object = request.getSession().getAttribute("user"); if (object == null) { System.out.println("用戶沒有登錄"); return false; } //繼續提交請求,false 請求不提交了 return true; } }
5.2.2 通過配置類注冊攔截器
在03-springboot-web中創建一個config包,創建一個配置類InterceptorConfig,並實現WebMvcConfigurer接口, 覆蓋接口中的addInterceptors方法,並為該配置類添加@Configuration注解,標注此類為一個配置類,讓Spring Boot 掃描到,這里的操作就相當於SpringMVC的注冊攔截器 ,@Configuration就相當於一個applicationContext-mvc.xml
代碼示例:
package com.bjpowernode.springboot.config; import com.bjpowernode.springboot.interceptor.LoginInterceptor; 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 InterceptorConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { //需要攔截的路徑,/**表示需要攔截所有請求 String[]addPathPatterns={"/**"}; //不需要攔截的路徑 String [] excludePathPaterns={ "/boot/get", "/boot/post", "/boot/put", "/myservlet" }; //注冊一個登錄攔截器 registry.addInterceptor(new LoginInterceptor()) .addPathPatterns(addPathPatterns) .excludePathPatterns(excludePathPaterns); //注冊一個權限攔截器 如果有多個攔截器 ,只需要添加以下一行代碼 //registry.addInterceptor(new LoginInterceptor()) // .addPathPatterns(addPathPatterns) // .excludePathPatterns(excludePathPatterns); } }
5.2.3 瀏覽器訪問測試是否攔截成功
訪問http://localhost:8080/boot/get 控制台不會輸出信息
訪問http://localhost:8080/boot/stu 控制台輸出信息