Spring Boot 優雅的配置攔截器方式

其實spring boot攔截器的配置方式和springMVC差很少,只有一些小的改變須要注意下就ok了。下面主要介紹兩種經常使用的攔截器:css

1、基於URL實現的攔截器:

public class LoginInterceptor extends HandlerInterceptorAdapter{
	/**
     * 在請求處理以前進行調用(Controller方法調用以前)
     * 基於URL實現的攔截器
     * @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)) {
        	//不須要的攔截直接過
            return true;
        } else {
        	// 這寫你攔截須要乾的事兒,好比取緩存,SESSION,權限判斷等
            System.out.println("====================================");
            return true;
        }
    }
}

關鍵代碼:path.matches(Const.NO_INTERCEPTOR_PATH 就是基於正則匹配的url。web

/**
 * @author 	BianP
 * @explain 常量類
 */
public class Const {

    public static final String SUCCESS = "SUCCESS";
    public static final String ERROR = "ERROR";
    public static final String FIALL = "FIALL";
    /**********************對象和個體****************************/
    public static final String SESSION_USER = "loginedAgent"; // 用戶對象
    public static final String SESSION_LOGINID = "sessionLoginID"; // 登陸ID
    public static final String SESSION_USERID = "sessionUserID"; // 當前用戶對象ID編號

    public static final String SESSION_USERNAME = "sessionUserName"; // 當前用戶對象ID編號
    public static final Integer PAGE = 10; // 默認分頁數
    public static final String SESSION_URL = "sessionUrl"; // 被記錄的url
    public static final String SESSION_SECURITY_CODE = "sessionVerifyCode"; // 登陸頁驗證碼
    // 時間 緩存時間
    public static final int TIMEOUT = 1800;// 秒
	public static final String ON_LOGIN = "/logout.htm";
	public static final String LOGIN_OUT = "/toLogout";
    // 不驗證URL anon:不驗證/authc:受控制的
    public static final String NO_INTERCEPTOR_PATH =".*/((.css)|(.js)|(images)|(login)|(anon)).*";
}

2、基於註解的攔截器

①建立註解:spring

/**
 * 在須要登陸驗證的Controller的方法上使用此註解
 */
@Target({ElementType.METHOD})// 可用在方法名上
@Retention(RetentionPolicy.RUNTIME)// 運行時有效
public @interface LoginRequired {
	
}

②建立攔截器:緩存

public class AuthorityInterceptor extends HandlerInterceptorAdapter{
	
	 @Override
	 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
	 	// 若是不是映射到方法直接經過
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        // ①:START 方法註解級攔截器
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        // 判斷接口是否須要登陸
        LoginRequired methodAnnotation = method.getAnnotation(LoginRequired.class);
        // 有 @LoginRequired 註解,須要認證
        if (methodAnnotation != null) {
            // 這寫你攔截須要乾的事兒,好比取緩存,SESSION,權限判斷等
            System.out.println("====================================");
            return true;
        }
        return true;
	}
}

3、把攔截器添加到配置中,至關於SpringMVC時的配置文件乾的事兒:springboot

/**
 * 和springmvc的webmvc攔截配置同樣
 * @author BIANP
 */
@Configuration
public class WebConfigurer implements WebMvcConfigurer {
	 @Override
	 public void addInterceptors(InterceptorRegistry registry) {
        // 攔截全部請求,經過判斷是否有 @LoginRequired 註解 決定是否須要登陸
        registry.addInterceptor(LoginInterceptor()).addPathPatterns("/**");
        registry.addInterceptor(AuthorityInterceptor()).addPathPatterns("/**");
	 }
	 
	 @Bean
	 public LoginInterceptor LoginInterceptor() {
		 return new LoginInterceptor();
	 }
	 
	 @Bean
	 public AuthorityInterceptor AuthorityInterceptor() {
		 return new AuthorityInterceptor();
	 }
}

一、必定要加@Configuration  這個註解,在啓動的時候在會被加載。session

二、有一些教程是用的「WebMvcConfigurerAdapter」,不過在spring5.0版本後這個類被丟棄了 WebMvcConfigurerAdapter  ,雖然還能夠用,可是看起來很差。mvc

三、也有一些教程使用的WebMvcConfigurationSupport,我使用後發現,classpath:/META/resources/,classpath:/resources/,classpath:/static/,classpath:/public/)不生效。具體能夠緣由,你們能夠看下源碼由於:WebMvcAutoConfiguration上有個條件註解:ide

@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)

因此仍是建議使用WebMvcConfigurer, 其實springMVC不少東西,均可以搬到springboot中來使用,只須要把配置文件的模式,改爲 對應@Configuration 類就行了。ui

歡迎加入技術討論羣:340697945      url

相關文章
相關標籤/搜索