这篇文章很详细的介绍了JS的跨域,给出的解决方案是springboot的方式,假如不用spring boot 或者 spring版本低于4.2就需要自己实现;
参考了spring boot的实现方式,并有所简化,代码如下:
java" id="highlighter_233447">
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
|
package com.lvluo.web.filter.CorsFilter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.http.HttpHeaders; public class CorsFilter implements Filter { public static final String ACCESS_CONTROL_REQUEST_METHOD = "Access-Control-Request-Method" ; public static final String OPTIONS = "OPTIONS" ; public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; if (isCorsRequest(httpRequest)) { httpResponse.setHeader( "Access-Control-Allow-Origin" , "*" ); httpResponse.setHeader( "Access-Control-Allow-Methods" , "POST, GET, PUT, DELETE" ); httpResponse.setHeader( "Access-Control-Allow-Credentials" , "true" ); // response.setIntHeader("Access-Control-Max-Age", 1728000); httpResponse .setHeader( "Access-Control-Allow-Headers" , "Origin, X-Requested-With, Content-Type, Accept, Accept-Encoding, Authorization" ); if (isPreFlightRequest(httpRequest)) { return ; } } chain.doFilter(request, response); } public void init(FilterConfig filterConfig) { } public void destroy() { } public boolean isCorsRequest(HttpServletRequest request) { return (request.getHeader(HttpHeaders.ORIGIN) != null ); } /** * Returns {@code true} if the request is a valid CORS pre-flight one. */ public boolean isPreFlightRequest(HttpServletRequest request) { return (isCorsRequest(request) && OPTIONS.equals(request.getMethod()) && request .getHeader(ACCESS_CONTROL_REQUEST_METHOD) != null ); } } |
接着在web.xml配置filter即可
1
2
3
4
5
6
7
8
|
< filter > < filter-name >corsFilter</ filter-name > < filter-class >com.lvluo.web.filter.CorsFilter</ filter-class > </ filter > < filter-mapping > < filter-name >corsFilter</ filter-name > < url-pattern >/api/*</ url-pattern > </ filter-mapping > |
前端测试的JS代码,其中客户端的
1
2
3
4
5
6
7
8
9
10
11
|
$.ajax({ headers : { 'Authorization' : 'Bearer iBoxSO9QdrHR0' }, url: 'http://localhost:8080/service/api/ping' , type: 'GET' , dataType: 'json' , success : function (result){ $( "#result" ).html(result.code); } }) |
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://my.oschina.net/lifereader/blog/909524