CorsInterceptor.java
package net.ybclass.online_ybclass.interceptor;
import org.springframework.http.HttpMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CorsInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//表示接受任意域名的请求,也可以指定域名
response.setHeader("Access-Control-Allow-Origin", request.getHeader("origin"));
//该字段可选,是个布尔值,表示是否可以携带cookie
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS");
response.setHeader("Access-Control-Allow-Headers", "*");
//这里可以不加,但是其他语言开发的话记得处理options请求
/**
* 非简单请求是对那种对服务器有特殊要求的请求,
* 比如请求方式是PUT或者DELETE,或者Content-Type字段类型是application/json。
* 都会在正式通信之前,增加一次HTTP请求,称之为预检。浏览器会先询问服务器,当前网页所在域名是否在服务器的许可名单之中,
* 服务器允许之后,浏览器会发出正式的XMLHttpRequest请求
*/
if(HttpMethod.OPTIONS.toString().equals(request.getMethod())){
return true;
}
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 {
}
}
InterceptorConfig.java
package net.ybclass.online_ybclass.config;
import net.ybclass.online_ybclass.interceptor.CorsInterceptor;
import net.ybclass.online_ybclass.interceptor.LoginInterceptor;
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;
/**
* 拦截器配置
* 不用权限可以访问url /api/v1/pub/
* 要登陆可以访问url /api/v1/pri/
*/
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
@Bean
LoginInterceptor loginInterceptor(){
return new LoginInterceptor();
}
@Bean
CorsInterceptor corsInterceptor(){return new CorsInterceptor();}
@Override
public void addInterceptors(InterceptorRegistry registry) {
//拦截全部路径,这个跨域了,需要放在最上面
registry.addInterceptor(corsInterceptor()).addPathPatterns("/**");
registry.addInterceptor(loginInterceptor())
.addPathPatterns("/api/v1/pri/*/*/**")//配置拦截的路径
.excludePathPatterns("/api/v1/pri/user/login","/api/v1/pri/user/register"); //不拦截那些路径
WebMvcConfigurer.super.addInterceptors(registry);
}
}