package com.osvue.win.app.config;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
//@Component
//public class InterceptorConfig extends WebMvcConfigurerAdapter {
// @Override
// public void addInterceptors(InterceptorRegistry registry) {
//  // 添加拦截器
//  registry.addInterceptor(new UserLoginInterceptor()).addPathPatterns("/**")// 定义拦截路径
//    .excludePathPatterns("/hello/**"); // 排除拦截路径
// }
//}

@Component
public class InterceptorConfig extends WebMvcConfigurationSupport {
 @Override
 public void addInterceptors(InterceptorRegistry registry) {
  registry.addInterceptor(new UserLoginInterceptor())// 添加拦截器
    .addPathPatterns("/hello/**")// 添 加拦截的请求路径
    .excludePathPatterns("/js/**", "/css/**", "/files/**") // 放⾏静态资源 静态资源被认为是 ⼀个控制器请求
    .excludePathPatterns("/hello/world");// 添加排除那些 请求路径不经过拦截器
 }

 // 注意:在springboot2.x版本中⾃定义拦截器之后出现项⽬中静态资 源 404情况,需要在⾃定义拦截器的配置中加⼊如下配置即可:

 // springboot2.x 静态资源在⾃定义拦截器之后⽆法访问的 解决⽅案
 @Override
 protected void addResourceHandlers(ResourceHandlerRegistry registry) {
  registry.addResourceHandler("/**") // 代表以 什么样的请求路径访问静态资源
    .addResourceLocations("classpath:/static/")
    .addResourceLocations("classpath:/templates/");
 }

}

interceptor

package com.osvue.win.app.config;

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

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class UserLoginInterceptor  implements HandlerInterceptor{

 @Override
 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
   throws Exception {
  // TODO Auto-generated method stub
  return HandlerInterceptor.super.preHandle(request, response, handler);
 }

 @Override
 public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
   ModelAndView modelAndView) throws Exception {
  // TODO Auto-generated method stub
  HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
 }

 @Override
 public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
   throws Exception {
  // TODO Auto-generated method stub
  HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
 }

 
}