1:实现 HandlerInterceptor 接口
public class LoginInterceptor implements HandlerInterceptor {
static Log logger = LogFactory.getLog(LoginInterceptor.class);
//登录之前的校验
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
logger.debug("登录之前的校验");
//todo 拦截的功能
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
2:实现 WebMvcConfigurationSupport 接口,重写 addInterceptors 方法, Configuration 注解标记为配置类
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport { //WebMvcConfigurerAdapter
//拦截器注册
@Override
public void addInterceptors(InterceptorRegistry registry) {
// registry.addInterceptor(new TestInterceptor()).addPathPatterns("/**"); // /**下的每一个接口都要有"登录"的校验
registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/mes");//mes下的接口都要被拦截
super.addInterceptors(registry);
}
//全局跨域
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**") // 允许跨域访问的路径
// .allowedOrigins("http://domain2.com") //允许跨域访问的源
// .allowedMethods("PUT", "DELETE") //允许请求方法
// .allowedHeaders("header1", "header2", "header3") //允许头部设置
// .exposedHeaders("header1", "header2")
// .allowCredentials(false).maxAge(3600); //是否发送cookie,预检间隔时间
;
}
//如果有安全框架,需要在框架中启用CORS;还有一种基于"过滤器"的跨域设置
}