Java Web uses CORS to implement cross-domain requests

from :  https://my.oschina.net/tbaby/blog/501333

 

Posted 2 articles about cross-domain issues, I hope that friends who see it will have a good experience!

 

 

A cloud service in the development laboratory before, the main backend is based on the jfinal framework using java. We encountered a small problem in development, because our development usually separates the front and back ends and uses AJAX to interact. But AJAX does not allow cross-domain, so the question is, how do we perform cross-domain AJAX?

 

1. What is AJAX?

Asynchronous JavaScript and XML ( Ajax  ) are key technologies driving a new generation of Web sites, popularly termed Web 2.0 sites. Ajax allows data retrieval in the background without interfering with the display and behavior of the Web application. Get data using a  XMLHttpRequest function, an API that allows client-side JavaScript to connect to a remote server over HTTP. Ajax is also the driving force behind many mashups, which integrate content from multiple places into a single Web application.

2. Why is there this problem?

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

Three, common solutions

(1) Use the script tag.

Script calls have no domain restrictions, and we can disguise the output data as script variables.

(2) Server-side script transfer

Server-side scripts using XMLHTTP have no domain restrictions, but consume server resources.

(3) Using iframes

Under each subdomain of the same domain name, if document.domain is set, JS can be called each other.

(4) JSONP

This method is also the best solution for normal AJAX and multi-person use.

JSONP (JSON with Padding) is an unofficial protocol, which allows integrating Script tags on the server side and returning them to the client side, and realizing cross-domain access in the form of javascript callback (this is just a simple implementation form of JSONP).

First register a callback on the client, and then pass the name of the callback to the server.

At this point, the server first generates json data.

Then generate a function in the way of javascript syntax, and the function name is the passed parameter jsonp.

Finally, the json data is directly placed in the function in the form of input parameters, so that a js syntax document is generated and returned to the client.

The client browser parses the script tag and executes the returned javascript document. At this time, the data is passed as a parameter to the predefined callback function of the client. (Dynamic execution of the callback function).

(5) COURSES

This is the solution we adopted this time.

CORS-CrossOrigin Resources Sharing, also known as cross-origin resource sharing, defines a way for browsers and servers to interact to determine whether to allow cross-origin requests. It's a compromise, with more flexibility, but more security than simply allowing all of these requirements. In short, CORS was born to allow AJAX to achieve controllable cross-domain access.

However, CORS also has certain risks. For example, the request can only indicate that it is from a specific domain but cannot verify whether it is trusted, and it is also easy to be invaded by a third party.

Fourth, use CORS in jfinal

Using cors in jfinal is very simple, thanks to the cors support library. We also uploaded this support library to our CDN server.

Download address: http://cdn.besdlab.cn/cors-lib.rar

(1) Add a support library to the development project

(2) Modify web.xml and 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 the interception of cors needs to be before jfinal!

(3) For example, we use jQuery here, other frameworks are similar.

   $("#login").click(function({
        $.ajax("http://测试地址", {
            type: "POST",
            xhrFields: {
                withCredentials: true,
                useDefaultXhrHeader: false
            },
            data: {
                username: "测试",
                password: "测试"
            },
            crossDomain: true,
            success: function(data, status, xhr{
            }
        });
   });

V. Summary

I don't know why the solution of cors is rarely seen in China, and it can't even be found in Baidu search. Our lab is also trying to use this technology to solve cross-domain problems. If you have any better solutions or encounter problems, we can discuss and solve them together!

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327031508&siteId=291194637