Cross-origin access of AJAX-two effective solutions

Source: Internet
Author: User

The new W3C policy implements HTTP cross-origin access, and I am looking for a long time to solve this problem:
You only need to add Access-Control-Allow-Origin to the header information returned by the servlet.
For example, to enable all my local cross-Origin Access, set response. setHeader ("Access-Control-Allow-Origin", "http: // 127.0.0.1 /*");
In this way, my local AJAX request in Project A can request the servlet in Project B across domains.
The Code is as follows:
Html js ajax requests:
Copy codeThe Code is as follows:/* Create a new XMLHttpRequest object to talk to the Web server */
Var xmlHttp = false;
/* @ Cc_on @*/
/* @ If (@ _ jscript_version> = 5)
Try {
XmlHttp = new ActiveXObject ("Msxml2.XMLHTTP ");
} Catch (e ){
Try {
XmlHttp = new ActiveXObject ("Microsoft. XMLHTTP ");
} Catch (e2 ){
XmlHttp = false;
}
}
@ End @*/
If (! XmlHttp & typeof XMLHttpRequest! = 'Undefined '){
XmlHttp = new XMLHttpRequest ();
}
Var url = "http: // 127.0.0.1: 2012/esb/servlet/HttpClient? RandomType = MIX ";
XmlHttp. open ("GET", url, true );
// Setup a function for the server to run when it's done
XmlHttp. onreadystatechange = function (){
If (xmlHttp. readyState = 4 ){
Var response = xmlHttp. responseText;
Alert (response );
}
}
// Send the request
XmlHttp. send (null );

Servlet code:
Copy codeThe Code is as follows: protected void service (HttpServletRequest req, HttpServletResponse resp)
Throws ServletException, java. io. IOException {
Resp. setHeader ("Pragma", "no-cache ");
Resp. setHeader ("Cache-Control", "no-cache ");
// The following sentence is the core
Resp. setHeader ("Access-Control-Allow-Origin", "http: // 127.0.0.1 /*");
Resp. setDateHeader ("Expires", 0 );
ServletOutputStream sos = resp. getOutputStream ();
Try {
Sos. write (obj. toString (). getBytes ("GBK "));
} Catch (Exception e ){
System. out. println (e. toString90)
} Finally {
Try {
Sos. close ();
} Catch (Exception e ){
LOG. error (e );
}
}
}

The code can be tested on the local machine. After two days, I put the servlet on the server and then perform a local test.
Although the above method solves the problem perfectly, the above article also says. There may be security issues, and whether the new standards support the same problem, so we can apply another clever way to achieve the same effect, because js does not have cross-origin problems, if the servlet on our server returns a JS script, you can. We can use javascript src in Project A to access the servlet of Project B, and then transmit data through the js Script output by servlet. Based on this idea, I tested the following code:
JS Code of the page:
Copy codeThe Code is as follows: function loadAjax (){
Id = "testesbscript ";
OScript = document. getElementById (id );
Var head = document. getElementsByTagName ("head"). item (0 );
If (oScript ){
Head. removeChild (oScript );
}
OScript = document. createElement ("script ");
Var url = "http: // 127.0.0.1: 2012/esb/servlet/HttpClient? RandomType = MIX & success = justHandle
OScript. setAttribute ("id", id );
OScript. setAttribute ("type", "text/javascript ");
OScript. setAttribute ("language", "javascript ");
Head. appendChild (oScript );
}
// JsutHandle is an inverse function. In servlet code, eval is used for execution.
Function justHandle (dd ){
Alert (dd );
}

Servlet code:
Copy codeThe Code is as follows: protected void service (HttpServletRequest req, HttpServletResponse resp)
Throws ServletException, java. io. IOException {

Object obj = "test ";
ServletOutputStream sos = resp. getOutputStream ();
StringBuffer sb = new StringBuffer ();
Resp. setCharacterEncoding ("GBK ");

Resp. setHeader ("Charset", "GBK ");
Resp. setContentType ("charset = GBK ");
// The following sentence indicates a javascript script file.
Resp. setContentType ("text/javascript ");

Sb. append ("eval (/" "+ paramMap. get ("success") + "(/'" + obj. toString () + "/')/")");
Try {
Sos. write (sb. toString (). getBytes (this. character_encoding ));
} Catch (Exception e ){
System. out. println (e. toString ());
} Finally {
Try {
Sos. close ();
} Catch (Exception e ){
System. out. println (e. toString ());
}
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.