springboot mvc 配置WebMvcConfigurerAdapter 過時使用WebMvcConfigurer 或者WebMvcConfigurationSupport
阿新 • • 發佈:2018-11-07
配置攔截器:
package top.mschen.blog.common.config; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import org.springframework.web.servlet.HandlerInterceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @Component public class LogInterceptor implements HandlerInterceptor{ private static Logger LOGGER= LoggerFactory.getLogger(LogInterceptor.class); public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { LOGGER.info("請求路徑:{}", request.getRequestURI()); return true; } }
新增攔截器:也可以直接實現WebMvcConfigurer介面
package top.mschen.blog.common.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; /** * WebMvcConfigurationSupport * WebMvcConfigurerAdapter * WebMvcConfigurer */ @Configuration public class WebMvcConfig { @Autowired private LogInterceptor logInterceptor; @Bean public WebMvcConfigurer webMvcConfigurer(){ return new WebMvcConfigurer(){ @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(logInterceptor).addPathPatterns("/**"); } }; } // /** // * addPathPatterns 新增攔截規則 // * excludePathPatterns 排除攔截規則 // * // * @param registry // */ // @Override // public void addInterceptors(InterceptorRegistry registry) { // registry.addInterceptor(logInterceptor).addPathPatterns("/**"); // super.addInterceptors(registry); // } }