Java implements cross-domain requests with cors

Source: Internet
Author: User

Before a cloud service in the development lab, the main backend was to use Java based jfinal framework. We encountered a small problem in development, because our development is usually to separate the front and back end of the interaction with Ajax. But Ajax is not allowed across domains Oh, so the question is, how do we cross-domain Ajax?

First, what is Ajax?

Asynchronous JavaScript and XML (Ajax ) are key technologies that drive a new generation of Web sites (popular terminology for Web 2.0 sites). Ajax allows data retrieval in the background without disturbing the display and behavior of the WEB application. Using XMLHttpRequest functions to get data, it is an API that allows client-side JavaScript to connect to a remote server via HTTP. Ajax is also a driving force for many mashups, which can make content collections from multiple locations a single WEB application.

Second, why do you have this problem?

Ajax itself actually interacts with the data through the XMLHttpRequest object, and the browser does not allow the JS code to cross-domain operations for security reasons, so it warns.

Iii. Common Solutions

(1) Use the script tag.

The script call has no domain restrictions, and we can disguise the output data as a script variable.

(2) server-side script relay

Server-side scripting uses XMLHTTP without domain restrictions, but consumes the resources of the servers.

(3) using IFRAME

In the same domain name under each sub-domain name, if set Document.domain, then can call JS each other.

(4) JSONP

This method is also the most solution to normal Ajax and multi-person use.

JSONP (JSON with Padding) is an unofficial protocol that allows the server-side integration of script tags back to the client to achieve cross-domain access in the form of JavaScript callback (this is simply a JSONP implementation form).

First register a callback with the client and then pass the callback name to the server.

At this point, the server becomes JSON data.

Then, in JavaScript syntax, a function is generated, and the function name is the parameter Jsonp passed up.

Finally, the JSON data is placed directly into the function in the form of a parameter, so that a document of JS syntax is generated and returned to the client.

The client browser parses the script tag and executes the returned JavaScript document, where the data is passed in as a parameter to the client's pre-defined callback function. (Dynamic execution callback function).

(5) CORS

This is the solution we have adopted this time.

Cors-crossorigin resources sharing, also known as cross-origin resource sharing, defines a way for browsers and server interactions to determine whether cross-domain requests are allowed. It is a compromise, with greater flexibility, but more secure than simply allowing all these requirements to be made. In short, cors is meant to enable Ajax to achieve controllable cross-domain access.

However, Cors also has a certain risk, such as the request can only be described from a specific domain but can not verify the credibility, but also vulnerable to third-party intrusion.

Iv. using Cors in jfinal

The use of cors in jfinal is straightforward, thanks to the support library with Cors. We also uploaded this support library to our CDN server.

: Http://cdn.besdlab.cn/cors-lib.rar

(1) Add a support library to your development project

(2) Modify Web. XML to add the following code

   <filter>          <filter-name >CORS</filter-name>          <filter-class> com.thetransactioncompany.cors.corsfilter</filter-class>           <init-param>               <param-name>cors.allowOrigin</param-name>              <param-value>*</param-value>          </init-param>          < init-param>              < param-name>cors.supportedmethods</param-name>              <param-value>get, post, head, put, delete</param-value>          </init-param>          <init-param>               <param-name> cors.supportedheaders</param-name>              <param-value>Accept, Origin, X-Requested-With, Content-Type,  Last-modified</param-value>         </init-param>           <init-param>               <param-name>cors.exposedHeaders</param-name>              <param-value>set-cookie </param-value>         </init-param>           <init-param>              < param-name>cors.supportscredentials</param-name>              <param-value>true</param-value>          </init-param>      </filter>       <filter-mapping>          < filter-name>cors</filter-name>          < Url-pattern>/*</url-pattern>     </filter-mapping>

Note that Cors interception is required before jfinal!

(3) For example, we use jquery here, similar to other frameworks.

   $ ("#login"). Click (function ()  {        $.ajax (" HTTP//Test Address ", {            type: " POST ",             xhrFields: {                 withcredentials: true,                  usedefaultxhrheader: false            },             data: {                 username:  "Test",                 password:  "Testing"               },            crossdomain:  true,            success: function (data , &NBSP;STATUS,&NBSP;XHR)  {            }         });    });

V. Summary

Cors This solution does not know why in the country rarely can see, and even baidu search is not searched. Our laboratory is also trying to use this technology to solve cross-domain problems, if you have any better way or have encountered problems we can discuss and solve together Oh!


Java implements cross-domain requests with cors

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.