spring解决服务端跨域问题

1、使用注解 @CrossOrigin

  • 在Controller层加上**@CrossOrigin**注解即可
@RestController
@CrossOrigin(origins = "*",maxAge = 1800L)
public class HelloController {
	
	
}

2、过滤器

package com.ivan.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Configuration
@WebFilter(urlPatterns = "/*")
public class CorsFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
    		throws ServletException, IOException {
    	String access_control = response.getHeader("Access-Control-Allow-Origin");
    	if(access_control == null) {
            // Access-Control-Allow-Origin: 指定授权访问的域
            response.addHeader("Access-Control-Allow-Origin", "*");  //此优先级高于@CrossOrigin配置

            // Access-Control-Allow-Methods: 授权请求的方法(GET, POST, PUT, DELETE,OPTIONS等)
            response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE,OPTIONS");

            response.addHeader("Access-Control-Allow-Headers", "Content-Type");

            response.addHeader("Access-Control-Allow-Headers", "token");
            response.addHeader("Access-Control-Allow-Headers", "device");
            response.addHeader("Access-Control-Allow-Headers", "nonce");
            response.addHeader("Access-Control-Allow-Headers", "mac");
            response.addHeader("Access-Control-Allow-Headers", "Authorization");
            response.addHeader("Access-Control-Max-Age", "1800");//30 min
    	}

        filterChain.doFilter(request, response);
    }
}
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页