springboot cors解决跨域问题

 1 package com.baselogic.boot.corsdemo;
 2 
 3 import org.slf4j.Logger;
 4 import org.slf4j.LoggerFactory;
 5 import org.springframework.web.filter.GenericFilterBean;
 6 
 7 import javax.servlet.*;
 8 import javax.servlet.http.HttpServletResponse;
 9 import java.io.IOException;
10 
11 /**
12  * CORS Filter
13  *
14  * This filter is an implementation of W3C's CORS
15  * (Cross-Origin Resource Sharing) specification,
16  * which is a mechanism that enables cross-origin requests.
17  *
18  */
19 public class CORSFilter extends GenericFilterBean implements Filter {
20 
21     private Logger logger = LoggerFactory.getLogger(this.getClass());
22 
23     @Override
24     public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
25             throws IOException, ServletException {
26 
27         HttpServletResponse httpResponse = (HttpServletResponse) response;
28         httpResponse.setHeader("Access-Control-Allow-Origin", "*");
29 //        httpResponse.setHeader("Access-Control-Allow-Methods", "*");
30         httpResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
31 
32 //        httpResponse.setHeader("Access-Control-Allow-Headers", "*");
33         httpResponse.setHeader("Access-Control-Allow-Headers",
34                 "Origin, X-Requested-With, Content-Type, Accept, X-Auth-Token, X-Csrf-Token, WWW-Authenticate, Authorization");
35         httpResponse.setHeader("Access-Control-Expose-Headers", "custom-token1, custom-token2");
36         httpResponse.setHeader("Access-Control-Allow-Credentials", "false");
37         httpResponse.setHeader("Access-Control-Max-Age", "3600");
38 
39         StringBuilder sb = new StringBuilder();
40         sb.append("\nCORS HEADERS:\n");
41         sb.append("---------------\n");
42         httpResponse.getHeaderNames()
43                 .forEach(name -> {
44                             sb.append(name).append(": ").append(httpResponse.getHeader(name)).append("\n");
45                         }
46                 );
47         logger.debug("********** CORS Configuration Completed **********");
48         logger.debug(sb.toString());
49 
50         chain.doFilter(request, response);
51     }
52 
53 
54 } 

 

jsonp只支持GET请求 ,cors相比于jsonp 支持更广泛的请求方式

 

上一篇:【python实战】还是单身,深入linux内核架构与原理


下一篇:关于springcloud的一些问题总结.txt