[Ajax] Javaweb cross-domain problems and their solutions

What is Ajax

When Ajax does not appear, most of the network resource acquisition to go through this process:
1, the browser sends a request
2, the server accepts the request, returns a resource
3, the browser get resources, interface refresh (this is mandatory refresh )
but this will be a problem that I can not partial refresh page content, if you want to refresh the content must refresh the entire screen. This is very tasteless, for example, I want to point to an article in praise, praise after point total number of points need to be refreshed like the article, we can not give me the entire page to refresh it again, this experience is bad.
To solve this problem, Ajax emerged, Ajax is not a language, nor is it a new technology, it is a combination of a series of technologies, Ajax's full name Asynchronous JavaScript + XML. When using Ajax access to resources, but the dynamic response operation, the corresponding request issued, return results or obtain resources, which quickly display (or update) to the local interface, at the same time so that you can get resources, without refreshing the entire interface.

Why can not cross-domain Ajax

Ajax can not cross-domain, because browsers follow the homologous policy: not the "same protocol, the same domain name, with the port," the web resources can not access each other. Ajax is the use of homologous protocol, Ajax can not access the resources of non-homologous.

But from the form it can be cross-domain, which is why? There is a big brother to know that is very detailed on peace:
because the page is submitted after the original domain name to another use form, the interface has been refreshed, the script can not get the original page content of the new page, the browser think it's safe.
AJAX can read and respond to the content, so the browser can not allow you to do so.

If you're careful you will find that, in fact request has been sent out (Status Code: 200 OK), you just can not get a response only. So the essence of this strategy is the browser, a domain name JS, in the case without permission, may not read the contents of another domain. But the browser does not prevent you from sending a request to another domain.

Author: Hang shall
link: https://www.zhihu.com/question/31592553/answer/190789780
Source: know almost
copyrighted by the author. Commercial reprint please contact the author authorized, non-commercial reprint please indicate the source.

How to solve the problem of cross-domain Ajax?

The prevailing method of cross-domain Ajax two solutions to the problem, one is Jsonp (Json with padding), the principle is to use the src attribute <script> tags, dynamic loading js function parameters, because the src attribute is not homologous restriction, the same img, iframe, link and other labels are not homologous limited, but can only be sent Jsonp get request; the other is CORS (Cross Origin Resource Sharing), CORS implementation will need to specify additional parameters in response to the service side of the head, so that the server tells the browser, do not let it prohibits communication between the client and the server.

HEARTS

CORS principle: the server, in response to the parameter is added after receiving the request, Access-Control-Allow-Origin , Access-Control-Allow-Methods, Access-Control-Max-Age, Access-Control-Allow-Headers, Access- Control-Allow-Credentials other parameters, to be received by the browser determines whether the server supports cross-domain request by setting these parameters after the return value. So we added a filter on the server, all incoming requests are plus response parameters.
Below an example to illustrate the use CORS:

CORS examples

Directory consisting
Here Insert Picture Description
Test.java core part

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setCharacterEncoding("utf-8");
		response.getWriter().write("{\"name\":\"xxxxxxxx\"}");
}

SimpleCORSFilter.java core part

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletResponse httpServletResponse = (HttpServletResponse) response;
		//设置所有的请求都可以实现Ajax跨域
		httpServletResponse.setHeader("Access-Control-Allow-Origin", "*"); 
		//支持http的POST,GET,OPTIONS,DELETE四种请求方式
		httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
		httpServletResponse.setHeader("Access-Control-Max-Age", "60");
		httpServletResponse.setHeader("Access-Control-Allow-Headers", "x-requested-with");
		//是否支持cookie跨域
		//httpServletResponse.addHeader("Access-Control-Allow-Credentials", "true");
		
		chain.doFilter(request, response);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

Point to note: Access-Control-Allow-Credentials used to mark whether to support cross-domain cookie, but the case is set to true, Access-Control-Allow-Origin can not be set *because the Cookie header carries information request , if the Access-Control-Allow-Origin value *, the request fails. In the case of the specified domain may be provided Access-Control-Allow-Credentials true, the specified domain name can be requested to accept Cookie.

After writing the filter, the filter needs to be configured in web.xml specific configuration as follows:
web.xml core part

  <filter>
    <filter-name>Simple CORSFilter</filter-name>
    <filter-class>filter.SimpleCORSFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>Simple CORSFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Ajax test</title>
<!-- 引入jQuery -->
<script src="./js/jquery.min.js"></script>
<script type="text/javascript">
	$.ajax({
		//从本地localhost的8080端口向www.xxxx.com域名的8080端口发送ajax请求
	    url:"http://www.xxxx.com:8080/Ajax_Cross_Origin/Test",
	    type: "get",
	    dataType:"json",
	    xhrFields: {
	    	//设置要不要携带Cookie信息,true为携带,fasle为不携带
	        withCredentials: false
	    },
	    crossDomain: true,
	    success:function (data) {
	    	 alert("12345");
	         console.log(data);
	    }
	});
	
</script>
</head>

<body>
<h1>测试ajax跨域</h1>
</body>
</html>

I project will be deployed in tomcat container server's domain name is www.xxxx.com, then tomcat this machine also deployed the project, input http://localhost:8080/Ajax_Cross_Origin/index.html, you can see the following information in the Network:
Here Insert Picture Description
see the following message in the Console :
Here Insert Picture Description
Ajax cross-domain request was successful.

jsonp

In practice, CORS frequency of use is much higher than Jsonp, so do not go into detail here the specific implementation of the Jsonp. One thing to note is that although Jsonp to solve the issues raised by cross-domain Ajax technology, but it had nothing to do Ajax a cent, because Jsonp is achieved by <script> src attribute realized, Ajax is achieved through XMLHttpRequest of. For those who want to learn more about Jsonp junior partner, strongly recommend that you look at this article:
Jsonp solve the problem of cross-domain ajax
wrote great!

Published 61 original articles · won praise 16 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_41427568/article/details/103818920