Spring Boot,SpringMVC 跨域问题解决

服务端跨域问题很常见,一下两个方法经本人实测有效

方法一、单独对某个接口增加跨域配置,只对当前接口有效

在Controller层增加注解

@CrossOrigin(origins = "*", maxAge = 3600)
Spring Boot,SpringMVC 跨域问题解决_第1张图片

方法二、全局配置

  1.配置文件继承 WebMvcConfigurerAdapter
  2.拦截器继承 HandlerInterceptorAdapter

@Configuration
public class ApiConfig extends WebMvcConfigurerAdapter {

@Override
public void configureMessageConverters(List> list) {
FastJsonHttpMessageConverter fastJsonConverter = new FastJsonHttpMessageConverter();
FastJsonConfig fastConf = new FastJsonConfig();
fastConf.setSerializerFeatures(SerializerFeature.PrettyFormat);
fastJsonConverter.setFastJsonConfig(fastConf);
list.add(fastJsonConverter);
super.configureMessageConverters(list);
}

@Bean
public HandlerInterceptor getAuthorizationInterceptor() {
return new AuthorizationInterceptor();
}

/**
* 添加拦截器
*
* @param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(getAuthorizationInterceptor());
super.addInterceptors(registry);
}

/**
* 解决跨域问题
*
* @param registry
*/
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedHeaders("*")
.allowCredentials(true)
.allowedMethods("*")
.allowedOrigins("*");
}

拦截器适配器HandlerInterceptorAdapter

/**
 * 访问token验证
 *
 * @author jackspeed
 */
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {
    /**
     * 缓存操作
     */
    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            String url = request.getHeader("Origin");
            if (!StringUtils.isEmpty(url)) {
                String val = response.getHeader("Access-Control-Allow-Origin");
                if (StringUtils.isEmpty(val)) {
                    response.addHeader("Access-Control-Allow-Origin", url);
                } else {
                    response.setHeader("Access-Control-Allow-Origin", "*");
                }
            }
            response.setContentType("application/json;charset=UTF-8");
            response.addHeader("Access-Control-Allow-Credentials", "true");

            response.setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.addHeader("Access-Control-Allow-Headers",
                    "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With");


            AccessSecret access = ((HandlerMethod) handler).getMethodAnnotation(AccessSecret.class);
             //TODO:
        return super.preHandle(request, response, handler);
    }

    

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}

你可能感兴趣的:(Spring Boot,SpringMVC 跨域问题解决)