SpringBoot優(yōu)雅的配置攔截器方式
其實(shí)spring boot攔截器的配置方式和springMVC差不多,只有一些小的改變需要注意下就ok了。
下面主要介紹兩種常用的攔截器:
一、基于URL實(shí)現(xiàn)的攔截器:
- public class LoginInterceptor extends HandlerInterceptorAdapter{
- /**
- * 在請(qǐng)求處理之前進(jìn)行調(diào)用(Controller方法調(diào)用之前)
- * 基于URL實(shí)現(xiàn)的攔截器
- * @param request
- * @param response
- * @param handler
- * @return
- * @throws Exception
- */
- @Override
- public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
- String path = request.getServletPath();
- if (path.matches(Const.NO_INTERCEPTOR_PATH)) {
- //不需要的攔截直接過(guò)
- return true;
- } else {
- // 這寫你攔截需要干的事兒,比如取緩存,SESSION,權(quán)限判斷等
- System.out.println("====================================");
- return true;
- }
- }
- }
關(guān)鍵代碼:path.matches(Const.NO_INTERCEPTOR_PATH 就是基于正則匹配的url。
- /**
- * @author BianP
- * @explain 常量類
- */
- public class Const {
- public static final String SUCCESS = "SUCCESS";
- public static final String ERROR = "ERROR";
- public static final String FIALL = "FIALL";
- /**********************對(duì)象和個(gè)體****************************/
- public static final String SESSION_USER = "loginedAgent"; // 用戶對(duì)象
- public static final String SESSION_LOGINID = "sessionLoginID"; // 登錄ID
- public static final String SESSION_USERID = "sessionUserID"; // 當(dāng)前用戶對(duì)象ID編號(hào)
- public static final String SESSION_USERNAME = "sessionUserName"; // 當(dāng)前用戶對(duì)象ID編號(hào)
- public static final Integer PAGE = 10; // 默認(rèn)分頁(yè)數(shù)
- public static final String SESSION_URL = "sessionUrl"; // 被記錄的url
- public static final String SESSION_SECURITY_CODE = "sessionVerifyCode"; // 登錄頁(yè)驗(yàn)證碼
- // 時(shí)間 緩存時(shí)間
- public static final int TIMEOUT = 1800;// 秒
- public static final String ON_LOGIN = "/logout.htm";
- public static final String LOGIN_OUT = "/toLogout";
- // 不驗(yàn)證URL anon:不驗(yàn)證/authc:受控制的
- public static final String NO_INTERCEPTOR_PATH =".*/((.css)|(.js)|(images)|(login)|(anon)).*";
- }
二、基于注解的攔截器
①創(chuàng)建注解:
- /**
- * 在需要登錄驗(yàn)證的Controller的方法上使用此注解
- */
- @Target({ElementType.METHOD})// 可用在方法名上
- @Retention(RetentionPolicy.RUNTIME)// 運(yùn)行時(shí)有效
- public @interface LoginRequired {
- }
②創(chuàng)建攔截器:
- public class AuthorityInterceptor extends HandlerInterceptorAdapter{
- @Override
- public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
- // 如果不是映射到方法直接通過(guò)
- if (!(handler instanceof HandlerMethod)) {
- return true;
- }
- // ①:START 方法注解級(jí)攔截器
- HandlerMethod handlerMethod = (HandlerMethod) handler;
- Method method = handlerMethod.getMethod();
- // 判斷接口是否需要登錄
- LoginRequired methodmethodAnnotation = method.getAnnotation(LoginRequired.class);
- // 有 @LoginRequired 注解,需要認(rèn)證
- if (methodAnnotation != null) {
- // 這寫你攔截需要干的事兒,比如取緩存,SESSION,權(quán)限判斷等
- System.out.println("====================================");
- return true;
- }
- return true;
- }
- }
三、把攔截器添加到配置中,相當(dāng)于SpringMVC時(shí)的配置文件干的事兒:
- /**
- * 和springmvc的webmvc攔截配置一樣
- * @author BIANP
- */
- @Configuration
- public class WebConfigurer implements WebMvcConfigurer {
- @Override
- public void addInterceptors(InterceptorRegistry registry) {
- // 攔截所有請(qǐng)求,通過(guò)判斷是否有 @LoginRequired 注解 決定是否需要登錄
- registry.addInterceptor(LoginInterceptor()).addPathPatterns("/**");
- registry.addInterceptor(AuthorityInterceptor()).addPathPatterns("/**");
- }
- @Bean
- public LoginInterceptor LoginInterceptor() {
- return new LoginInterceptor();
- }
- @Bean
- public AuthorityInterceptor AuthorityInterceptor() {
- return new AuthorityInterceptor();
- }
- }
1、一定要加@Configuration 這個(gè)注解,在啟動(dòng)的時(shí)候在會(huì)被加載。
2、有一些教程是用的“WebMvcConfigurerAdapter”,不過(guò)在spring5.0版本后這個(gè)類被丟棄了 WebMvcConfigurerAdapter ,雖然還可以用,但是看起來(lái)不好。
3、也有一些教程使用的WebMvcConfigurationSupport,我使用后發(fā)現(xiàn),classpath:/META/resources/,classpath:/resources/,classpath:/static/,classpath:/public/不生效。具體可以原因,大家可以看下源碼因?yàn)椋篧ebMvcAutoConfiguration上有個(gè)條件注解:
- @ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
所以還是建議使用WebMvcConfigurer, 其實(shí)springMVC很多東西,都可以搬到springboot中來(lái)使用,只需要把配置文件的模式,改成 對(duì)應(yīng)@Configuration 類就好了。