之前用jsonp 解决跨域问题,现在用CORS实现跨域请求解决java 跨域问题:
主要代码如下
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
|
package com.hy.fliter;
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.apache.commons.httpclient.HttpStatus;
/**
* Created by WangShuai on 2016/7/30.
*/
public class CorsFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException { }
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) servletResponse;
HttpServletRequest request = (HttpServletRequest) servletRequest;
// 指定允许其他域名访问
response.setHeader( "Access-Control-Allow-Origin" , "*" );
// 响应类型
response.setHeader( "Access-Control-Allow-Methods" , "POST, GET, DELETE, OPTIONS, DELETE" );
// 响应头设置
response.setHeader( "Access-Control-Allow-Headers" , "Content-Type, x-requested-with, X-Custom-Header, HaiYi-Access-Token" );
if ( "OPTIONS" .equals(request.getMethod())){
response.setStatus(HttpStatus.SC_NO_CONTENT);
}
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() { }
}
|
web.xml 代码如下配置
1
2
3
4
5
6
7
8
|
<filter>
<filter-name>cors</filter-name>
<filter- class >com.hy.fliter.CorsFilter</filter- class >
</filter>
<filter-mapping>
<filter-name>cors</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
|
以上所述是小编给大家介绍的使用CORS实现JavaWeb跨域请求问题的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对服务器之家网站的支持!