Java如何实现跨域请求呢?相信大家在写前端脚本的时候经常会遇到发送数据到后台的情况,但是由于浏览器的限制,不同域名之间的数据是不能互相访问的,那前端怎么和后端如何进行数据之间的交换呢?今天就和大家分享一下Java后台实现跨域请求的解决方法。
一、定义一个类继承Filter
package com.zdnst.common.infra.filter.corsFilter;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Created by yongqin.zhong
* Date 7/14/2017.3:27 PM
*/
public class SimpleCORSFilter implements Filter {
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
// 跨域
String origin = httpRequest.getHeader("Origin");
if (origin == null) {
httpResponse.setHeader("Access-Control-Allow-Origin", "*");
} else {
httpResponse.setHeader("Access-Control-Allow-Origin", origin);
}
httpResponse.setHeader("Access-Control-Allow-Headers", "Origin, x-requested-with, Content-Type, Accept,X-Cookie");
httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
httpResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,OPTIONS,DELETE");
if ( httpRequest.getMethod().equals("OPTIONS") ) {
httpResponse.setStatus(HttpServletResponse.SC_OK);
return;
}
chain.doFilter(request, response);
}
@Override
public void init(FilterConfig arg0) throws ServletException {
}}
二、在web.xml的filter顶部位置增加以下配置
<filter-name>cors</filter-name>
<filter-class>com.zdnst.common.infra.filter.corsFilter.SimpleCORSFilter</filter-class>
</filter>
<filter-mapping>
<url-pattern>/*</url-pattern>
即可;
总结:在java后台增加了这样head头配置后,页面请求会自动重复调用两次接口,一次是预调用;“OPTIONS”状态的;
nginx跨域设置
nginx跨域问题
例子:访问//10.0.0.10/ 需要能实现跨域
操作:
//10.0.0.10/项目是部署在tomcat里面,tomcat跨域暂时还不会,按照网上的方法操作也没成功
只有用Nginx做个代理,解决跨域问题了!
1、将www.tangxiaoyue.com域名指向//10.0.0.11/。只有在域名上设置才能实现跨域。(10.0.0.11是Nginx的IP)
2、在nginx上的配置文件tang.conf进行设置
配置文件例如:
server {
listen 80;
server_name tangxiaoyue.com;
if ( $http_user_agent = "Mozilla/5.0"){
return 403;
}
location / {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
proxy_pass //10.0.0.10/;
proxy_set_header Host "tangxiaoyue";
}}
热点新闻