SpringBoot配置攔截器實現(xiàn)過程詳解
如何配置攔截器
step1: 自定義攔截器
/**
* 自定義攔截器
*/
public class MyInterceptor implements HandlerInterceptor {
private static final Logger logger = LoggerFactory.getLogger(MyInterceptor.class);
/**
* 在請求匹配controller之前執(zhí)行,返回true才行進行下一步
* @param request
* @param response
* @param handler
* @return
* @throws Exception
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
return false;
}
/**
* 已經執(zhí)行完controller了,但是還沒有進入視圖渲染
* @param request
* @param response
* @param handler
* @param modelAndView
* @throws Exception
*/
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
/**
* 視圖也渲染完了,此時我可以做一些清理工作了
* @param request
* @param response
* @param handler
* @param ex
* @throws Exception
*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}step2:配置攔截器
@Configuration
public class MyInterceptorConfig extends WebMvcConfigurationSupport {
@Override
protected void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**"); // 攔截所有內容:/** 攔截部分內容:/admin/**
super.addInterceptors(registry);
}
}攔截器設置容易出現(xiàn)的問題
靜態(tài)資源被攔截
MyInterceptorConfig 繼承 WebMvcConfigurationSupport類時,會導致resources/static下的靜態(tài)資源也被攔截,如果我們不想靜態(tài)資源被攔截,可以嘗試以下兩種方法。
/**
* 在MyInterceptorConfig中重寫addResourceHandlers方法,重新指定靜態(tài)資源
* 推薦在前后端分離時使用,后臺不需要訪問靜態(tài)資源
*
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations(
"classpath:/static/");
super.addResourceHandlers(registry);
}
/**
* 將MyInterceptorConfig類由繼承WebMvcConfigurationSupport改為實現(xiàn)WebMvcConfigurer
* 推薦在非前后端分離時使用,后臺需要訪問靜態(tài)資源
*
*/
@Configuration
public class MyInterceptorConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**"); // 攔截所有內容:/** 攔截部分內容:/admin/**
}
}如何取消攔截操作
step1:自定義注解
/**
* 自定義注解用來指定某個方法不用攔截
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface UnInterception {
}step2:修改攔截器MyInterceptor中的preHandle方法
/**
* 在請求匹配controller之前執(zhí)行
* @param request
* @param response
* @param handler
* @return
* @throws Exception
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
UnInterception unInterception = method.getAnnotation(UnInterception.class);
if(null != unInterception) {
logger.info("不需要攔截,可以執(zhí)行");
return true;
}
// 返回true才會執(zhí)行方法,返回false不會執(zhí)行
return false;
}step3:在不需要攔截的controller上加上UnInterception注解
@Controller
@RequestMapping("/interceptor")
public class InterceptorController {
@UnInterception
@RequestMapping("/test")
public String test() {
return "hello";
}
}實例-登錄驗證
用攔截器實現(xiàn)一個登錄驗證功能
step1:自定義攔截器
import com.kimmel.course13.annotation.UnInterception;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
/**
* 自定義攔截器
*/
public class MyInterceptor implements HandlerInterceptor {
private static final Logger logger = LoggerFactory.getLogger(MyInterceptor.class);
/**
* 在請求匹配controller之前執(zhí)行
* @param request
* @param response
* @param handler
* @return
* @throws Exception
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
HandlerMethod handlerMethod = (HandlerMethod) handler;
Method method = handlerMethod.getMethod();
String methodName = method.getName();
// 判斷用戶有沒有登錄,一般登錄之后的用戶都有一個對應的token
UnInterception unInterception = method.getAnnotation(UnInterception.class);
String token = request.getParameter("token");
if (null == token || "".equals(token)) {
logger.info("用戶未登錄,沒有權限執(zhí)行{}請登錄", methodName);
return false;
}
// 返回true才會執(zhí)行方法,返回false不會執(zhí)行
return true;
}
/**
* 已經執(zhí)行完controller了,但是還沒有進入視圖渲染
* @param request
* @param response
* @param handler
* @param modelAndView
* @throws Exception
*/
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
HandlerMethod handlerMethod = (HandlerMethod) handler;
Method method = handlerMethod.getMethod();
String methodName = method.getName();
logger.info("已經執(zhí)行完{}了,但是還沒有進入視圖渲染", methodName);
}
/**
* 視圖也渲染完了,此時我可以做一些清理工作了
* @param request
* @param response
* @param handler
* @param ex
* @throws Exception
*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
logger.info("視圖也渲染完了,此時我可以做一些清理工作了");
}
}step2:配置攔截器
import com.kimmel.course13.Interceptor.MyInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
@Configuration
public class MyInterceptorConfig extends WebMvcConfigurationSupport {
@Override
protected void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**"); // 攔截所有內容:/** 攔截部分內容:/admin/**
super.addInterceptors(registry);
}
/**
* 發(fā)現(xiàn)如果繼承了WebMvcConfigurationSupport,則在yml中配置的相關內容會失效。 需要重新指定靜態(tài)資源
*
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations(
"classpath:/static/");
registry.addResourceHandler("swagger-ui.html").addResourceLocations(
"classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations(
"classpath:/META-INF/resources/webjars/");
super.addResourceHandlers(registry);
}
}
step3:自定義測試controller
@Controller
@RequestMapping("/interceptor")
public class InterceptorController {
@RequestMapping("/test")
public String test() {
return "hello";
}
}step4:測試
進入瀏覽器,輸入http://localhost:8080/interceptor/test
結果:無法進入,日志:用戶未登錄,沒有權限執(zhí)行 test 請登錄
進入瀏覽器,輸入http://localhost:8080/interceptor/test?token=1
結果:成功進入hello.html
到此這篇關于SpringBoot配置攔截器實現(xiàn)過程詳解的文章就介紹到這了,更多相關SpringBoot配置攔截器內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
SpringBoot后端接收參數(shù)優(yōu)化代碼示例(統(tǒng)一處理前端參數(shù))
使用Spring Boot開發(fā)API的時候,讀取請求參數(shù)是服務端編碼中最基本的一項操作,下面這篇文章主要給大家介紹了關于SpringBoot后端接收參數(shù)優(yōu)化(統(tǒng)一處理前端參數(shù))的相關資料,需要的朋友可以參考下2024-07-07
如何解決EasyExcel導出文件LocalDateTime報錯問題
這篇文章主要介紹了如何解決EasyExcel導出文件LocalDateTime報錯問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-06-06
SpringBoot?@DS注解實現(xiàn)多數(shù)據(jù)源配置以及問題解決辦法
這篇文章主要給大家介紹了關于SpringBoot?@DS注解實現(xiàn)多數(shù)據(jù)源配置以及問題解決辦法,所謂多數(shù)據(jù)源就是一個Java EE項目中采用了不同數(shù)據(jù)庫實例中的多個庫,或者是同一個數(shù)據(jù)庫實例中的多個不同庫,需要的朋友可以參考下2023-11-11
SpringMVC?RESTFul實戰(zhàn)案例訪問首頁
這篇文章主要為大家介紹了SpringMVC?RESTFul實戰(zhàn)案例訪問首頁,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-05-05

