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;
}
/**
* 已經(jīng)執(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("/**"); // 攔截所有內(nèi)容:/** 攔截部分內(nèi)容:/admin/**
super.addInterceptors(registry);
}
}攔截器設(shè)置容易出現(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("/**"); // 攔截所有內(nèi)容:/** 攔截部分內(nèi)容:/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();
// 判斷用戶有沒有登錄,一般登錄之后的用戶都有一個對應(yīng)的token
UnInterception unInterception = method.getAnnotation(UnInterception.class);
String token = request.getParameter("token");
if (null == token || "".equals(token)) {
logger.info("用戶未登錄,沒有權(quán)限執(zhí)行{}請登錄", methodName);
return false;
}
// 返回true才會執(zhí)行方法,返回false不會執(zhí)行
return true;
}
/**
* 已經(jīng)執(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("已經(jīng)執(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("/**"); // 攔截所有內(nèi)容:/** 攔截部分內(nèi)容:/admin/**
super.addInterceptors(registry);
}
/**
* 發(fā)現(xiàn)如果繼承了WebMvcConfigurationSupport,則在yml中配置的相關(guān)內(nèi)容會失效。 需要重新指定靜態(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
結(jié)果:無法進入,日志:用戶未登錄,沒有權(quán)限執(zhí)行 test 請登錄
進入瀏覽器,輸入http://localhost:8080/interceptor/test?token=1
結(jié)果:成功進入hello.html
到此這篇關(guān)于SpringBoot配置攔截器實現(xiàn)過程詳解的文章就介紹到這了,更多相關(guān)SpringBoot配置攔截器內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java連接mysql數(shù)據(jù)庫以及mysql驅(qū)動jar包下載和使用方法
這篇文章主要給大家介紹了關(guān)于Java連接mysql數(shù)據(jù)庫以及mysql驅(qū)動jar包下載和使用方法,MySQL是一款常用的關(guān)系型數(shù)據(jù)庫,它的JDBC驅(qū)動程序使得我們可以通過Java程序連接MySQL數(shù)據(jù)庫進行數(shù)據(jù)操作,需要的朋友可以參考下2023-11-11
Java實戰(zhàn)項目 醫(yī)院預(yù)約掛號系統(tǒng)
本文是一個Java語言編寫的實戰(zhàn)項目,是一個醫(yī)院預(yù)約掛號系統(tǒng),主要用到了jdbc+jsp+mysql+ajax等技術(shù),技術(shù)含量比較高,感興趣的童鞋跟著小編往下看吧2021-09-09
將SpringBoot項目無縫部署到Tomcat服務(wù)器的操作流程
SpringBoot 是一個用來簡化 Spring 應(yīng)用初始搭建以及開發(fā)過程的框架,我們可以通過內(nèi)置的 Tomcat 容器來輕松地運行我們的應(yīng)用,本文給大家介紹 SpringBoot 項目部署到獨立 Tomcat 服務(wù)器的操作流程,需要的朋友可以參考下2024-05-05
java數(shù)據(jù)結(jié)構(gòu)基礎(chǔ):緒論
這篇文章主要介紹了Java的數(shù)據(jù)解構(gòu)基礎(chǔ),希望對廣大的程序愛好者有所幫助,同時祝大家有一個好成績,需要的朋友可以參考下,希望能給你帶來幫助2021-07-07
Mybatis實現(xiàn)ResultMap結(jié)果集
本文主要介紹了Mybatis實現(xiàn)ResultMap結(jié)果集,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-04-04

