1. 程式人生 > 其它 >spring boot 新增攔截器

spring boot 新增攔截器

構建一個spring boot專案。

新增攔截器需要新增一個configuration

@Configuration
@ComponentScan(basePackageClasses = Application.class, useDefaultFilters = true)
public class ServletContextConfig extends WebMvcConfigurationSupport {

為了方便掃描位置,我們可以寫一個介面或者入口類Application放置於最外一層的包內,這樣就會掃描該類以及子包的類。

1 resources配置

在沒有配置這個類的時候,我們可以在application.ym中修改靜態檔案位置和匹配方式:

#指定環境配置檔案
spring:
  profiles:
    active: dev
  # 修改預設靜態路徑,預設為/**,當配置hello.config.ServletContextConfig後此處配置失效
  mvc:
    static-path-pattern: /static/**

但當我們繼承了WebMvcConfigurationSupport 並配置掃描後,上述resources的配置失效,還原預設配置。那麼我們需要在這個類中再次指定靜態資源位置:

@Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/").addResourceLocations("/**");
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
    }

這樣訪問classpath下的static包下的靜態資源的url匹配為/static/xxx.js。預設匹配static下的靜態檔案url為/xxx.js,雖然清潔,但我感覺idea不會識別這種路徑,還是改成完整的路徑比較好。

2.Interceptor配置

配置登入攔截或者別的。需要建立一個攔截器類來繼承HandlerInterceptorAdapter,然後只需要覆蓋你想要攔截的位置就可以了。比如,我只是攔截訪問方法之前:

package hello.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by miaorf on 2016/8/3.
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {
    private Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String authorization = request.getHeader("Authorization");
        logger.info("The authorization is: {}",authorization);
        return super.preHandle(request, response, handler);
    }
}

寫好interceptor之後需要在開始建立的ServletContextConfig中新增這個攔截器:

@Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns(FAVICON_URL)
        ;
    }

完整的ServletContextConfig為:

/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2014-2016 [email protected]
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

package hello.config;

import hello.Application;
import hello.interceptor.LoginInterceptor;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
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
@ComponentScan(basePackageClasses = Application.class, useDefaultFilters = true)
public class ServletContextConfig extends WebMvcConfigurationSupport {

    static final private String FAVICON_URL = "/favicon.ico";
    static final private String PROPERTY_APP_ENV = "application.environment";
    static final private String PROPERTY_DEFAULT_ENV = "dev";



    /**
     * 發現如果繼承了WebMvcConfigurationSupport,則在yml中配置的相關內容會失效。
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/").addResourceLocations("/**");
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
    }


    /**
     * 配置servlet處理
     */
    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns(FAVICON_URL)
        ;
    }

}

3.AOP攔截方法

相關測試程式碼http://www.cnblogs.com/woshimrf/p/5677337.html

本demo原始碼:

https://github.com/Ryan-Miao/spring-boot-demo