http中解决跨域的几种方法(代码实测)

版权声明:转载请注明出处 https://blog.csdn.net/chenmingxu438521/article/details/90720622

一、概念

1.什么是跨域,跨域是浏览器安全机制,其实就是说你请求访问的域名与ajax请求地址不一致,浏览器会直接无法返回请求结果。

二、跨域的例子展示

1.项目demotesta

1.1.目录结构

1.2.pom.xml

<dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>javax.servlet-api</artifactId>
   <version>3.0.1</version>
   <scope>provided</scope>
</dependency>
<dependency>
   <groupId>com.alibaba</groupId>
   <artifactId>fastjson</artifactId>
   <version>1.2.41</version>
</dependency>

1.3.FormServlet.java

@WebServlet("/FromServlet")
public class FromServlet extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String userName = req.getParameter("userName");
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("userName", userName);
		resp.getWriter().println(jsonObject.toJSONString());
	}
}

2.项目demotestb

2.1.项目结构

2.2.pom.xml

<dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>javax.servlet-api</artifactId>
   <version>3.0.1</version>
   <scope>provided</scope>
</dependency>

2.3.b.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>B网站访问</title>
</head>
<script type="text/javascript"
	src="./js/jquery-1.9.1.min.js?t=2017-07-27"></script>
<script type="text/javascript">
	$(document).ready(function() {
		$.ajax({
			type : "get",
			async : false,
			url : "http://a.a.com/a/FromServlet?userName=644064",
			dataType : "json",
			success : function(data) {
				alert("获取结果:"+data["userName"]);
			},
			error : function() {
				alert('fail');
			}
		});

	});
</script>

<body>
	<img alt="" src="http://a.a.com/a/imgs/log.png">
</body>
</html>

3.结果展示(demotestb项目中的页面去访问demotesta项目中的接口地址,这样的话你就理解开篇的第一句话的意思了,这就是跨域)

看下控制台的信息 (ajax的跨域问题)

三、第一种方式解决跨域

1.添加header请求头去解决(后端解决问题)

1.1.在demotesta项目中的FromServlet.java中添加

@WebServlet("/FromServlet")
public class FromServlet extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String userName = req.getParameter("userName");
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("userName", userName);
		resp.getWriter().println(jsonObject.toJSONString());
                //允许浏览器跨域问题允许所有的
		resp.setHeader("Access-Control-Allow-Origin", "*");
	}
}

1.2.访问结果

1.3.结果出来了,问题解决

四、第二种方式解决跨域

1.jsonp解决跨域问题,只支持get请求,不支持post请求,在demotestb项目中

1.1.b.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>B网站访问</title>
</head>
<script type="text/javascript"
	src="./js/jquery-1.9.1.min.js?t=2017-07-27"></script>
<script type="text/javascript">
	$(document).ready(function() {
		$.ajax({
			type : "get",
			async : false,
			url : "http://a.a.com/a/FromServlet?userName=644064",
			dataType : "jsonp",//数据类型为jsonp  
			jsonp : "jsonpCallback",//服务端用于接收callback调用的function名的参数  
			success : function(data) {
				alert("获取结果:"+data["userName"]);
			},
			error : function() {
				alert('fail');
			}
		});

	});
</script>

<body>
	<img alt="" src="http://a.a.com/a/imgs/log.png">
</body>
</html>

1.2.FromServlet.java

@WebServlet("/FromServlet")
public class FromServlet extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String userName = req.getParameter("userName");
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("userName", userName);
		String jsonpCallback = req.getParameter("jsonpCallback");
		resp.getWriter().println(jsonpCallback+"("+jsonObject.toJSONString()+")");
	}
}

1.3.结果访问

五、第三种方式解决跨域

1.  使用HttpClinet转发进行转发(在demotestb项目中)

1.1.项目结构

1.2.pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.ysfj</groupId>
  <artifactId>demotestb</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
   <dependencies>
  	<dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.0.1</version>
      <scope>provided</scope>
    </dependency>
    
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.4.1</version>
</dependency>
</dependencies>
</project>

1.2.ToFormServlet.java

@WebServlet("/ToFromServlet")
public class ToFromServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
           this.doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		// 创建默认连接
		CloseableHttpClient httpClient = HttpClients.createDefault();
		// 创建get请求
		HttpGet httpGet = new HttpGet("http://a.a.com/a/FromServlet?userName=" + req.getParameter("userName"));
		CloseableHttpResponse response = httpClient.execute(httpGet);
		int code = response.getStatusLine().getStatusCode();
		// 获取状态
		System.out.println("http请求结果:" + code);
		if (code == 200) {
			String result = EntityUtils.toString(response.getEntity());
			System.out.println(result);
			resp.getWriter().print(result);
			response.close();
			httpClient.close();
			// 将string转换html框架
		}
	}
}

1.3.b.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>B网站访问</title>
</head>
<script type="text/javascript"
	src="./js/jquery-1.9.1.min.js?t=2017-07-27"></script>
<script type="text/javascript">
	$(document).ready(function() {
		$.ajax({
			type : "get",
			async : false,
			url : "http://b.b.com/b/ToFromServlet?userName=644064",
			dataType : "json",
			success : function(data) {
				alert("获取结果:"+data["userName"]);
			},
			error : function() {
				alert('fail');
			}
		});

	});
</script>

<body>
	<img alt="" src="http://a.a.com/a/imgs/log.png">
</body>
</html>

1.4.访问结果

六、第四种方式解决跨域

1.nginx的反向代理解决跨域

1.1.nginx的配置

1.2.本地hosts配置

1.3.项目目录

1.4.代码(跨域demotestb项目中的b.jsp访问demotesta项目的FormServlet.java)

1.4.1.b.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>B网站访问</title>
</head>
<script type="text/javascript"
	src="./js/jquery-1.9.1.min.js?t=2017-07-27"></script>
<script type="text/javascript">
	$(document).ready(function() {
		$.ajax({
			type : "get",
			async : false,
			url : "http://ky.chenmingxu.com/A/FromServlet?userName=644064",
			dataType : "json",  
			success : function(data) {
				alert("获取结果:"+data["userName"]);
			},
			error : function() {
				alert('fail');
			}
		});

	});
</script>

<body>
	<img alt="" src="http://a.a.com/a/imgs/log.png">
</body>
</html>

1.4.2.FormServlet.java

@WebServlet("/FromServlet")
public class FromServlet extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String userName = req.getParameter("userName");
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("userName", userName);
		resp.getWriter().println(jsonObject.toJSONString());
	}
}

1.4.3.测试结果

总结:这样也是可以完成跨域的解决问题

七、结束

希望能帮助到你们!!!

猜你喜欢

转载自blog.csdn.net/chenmingxu438521/article/details/90720622