Java analysis of Cross-domain problems and how to use cors to solve the cross-domain problems encountered by the front and back-end detached deployment project __ cross-domain

Source: Internet
Author: User
Tags aop error handling

Over time, the development of the front and back end separation is becoming more and more popular, the use of the company is more and more. But this form of development also poses a problem. That's a cross-domain problem. What is cross-domain

Cross-domain, refers to the browser can not execute other Web site script. It is caused by the browser's homology policy, which is the security restrictions imposed on JavaScript by browsers.
under what circumstances is not a cross-domain.
That is to meet the domain name, protocol, ports are the same that is not cross-domain.

For example
Http://www.beyondLi.com/index.html Call Http://www.beyondLi.com/server (non-Cross-domain)

Http://www.beyondLione.com/index.html Call Http://www.beyondLitwo.com/server (main domain name is different: One/two, Cross-domain)

Http://www.beyondLi.com:8080/index.html Call Http://www.beyondLi.com:8081/server (port is different: 8080/8081, Cross-domain)

Http://www.beyondLi.com/index.html Call Https://www.beyondLi.com/server (protocol different: Http/https, cross-domain) scene

Now we have the front-end separation of the deployment, the front end of the code and the back-end code on a different server, the front-end to use the AJAX request to invoke the backend interface to get the corresponding data. Solution

There are two scenarios for solving cross-domain problems in general, JSONP and Cors. Because JSONP need to do with the unity of the front and back to mark personal feeling more trouble, so I choose to use cors solution to this problem. cors Introduction

The Cross-origin Resource Sharing (CORS) is a draft of the Web work, which defines how browsers and servers communicate when accessing resources across domains. The basic idea behind cors is to use a custom HTTP header to allow browsers and servers to understand each other and decide whether the request or response succeeds. comparison between Cors and Jsonp

Compared with JSONP, Cors is more advanced, convenient and reliable.
1. JSONP can only implement get requests, while cors supports all types of HTTP requests.
2, the use of cors, developers can use the common XMLHttpRequest to initiate requests and access to data, compared to JSONP has better error handling.
3, Jsonp mainly by the old browser support, they often do not support cors, and most modern browsers have supported the Cors.
For a simple request, there is no custom header, either using Get or using post, its body is text/plain, and the request is sent with an extra head called Orgin. The origin header contains the header of the requesting page (protocol, domain name, port) so that the server can easily determine whether it should provide a response.
Server-side support for cors is mainly done by setting up Access-control-allow-origin.
Header Set Access-control-allow-origin *
To prevent XSS from attacking our servers, we can restrict the domain, such as
Access-control-allow-origin:http://beyondli.com Code Implementation

First, we have a preliminary understanding of Cross-domain and cors through reading above. Now let's think about a problem. Cross-domain should be configured on the front or back end. The answer, of course, is the back end. Imagine if this problem is solved by the front end and the background does not need any configuration, then it is not a random write an AJAX can access a variety of Web site interface. This is a bit scary. So it should be our backstage development to configure whether this allows for Cross-domain requests for switches, and can make certain restrictions and filters. Front-end code

There is nothing special, do not do too much introduction. Just a simple Ajax request to access the backend interface.

<! DOCTYPE html>

If we do not do any cross-domain processing access, we will report the following error, presumably meaning that we have not configured Access-control-allow-origin this header.
Background Code

Our core code is, in fact, very simple, this problem can be solved by simply setting the error attribute to the response header , so we can solve this problem by providing a filter or intercepting all AOP. The code is as follows ( I use the springboot for development, as long as you understand the nature of the problem, the following methods are selectively used.) ) method One (using filter)

/** * Created by Beyondli on 2017/7/29. * @desc Resolve Cross-domain/@Component public class Crossfilter implements Filter {public void Dofilter (ServletRequest req, Ser Vletresponse Res, Filterchain chain) throws IOException, servletexception {httpservletresponse response = (httpse
        Rvletresponse) Res;
        If you want to make a fine limit, only a domain name can be cross-domain access to this, you can change the * to the corresponding domain name.
        Response.setheader ("Access-control-allow-origin", "*");
        Response.setheader ("Access-control-allow-methods", "*");
        Response.setheader ("Access-control-max-age", "1728000");
        Response.setheader ("Access-control-allow-credentials", "true");
Response.setheader ("Access-control-allow-headers", "Origin, X-requested-with, Content-type, Accept");
        Response.setheader ("Access-control-allow-headers", "Origin, X-requested-with, Content-type, Accept");
    Chain.dofilter (req, res); The public void init (Filterconfig filterconfig) {} is public void Destroy () {}}} 
method Two (using AOP)
/**
 * Created by Beyondli on 2017/7/31.
 //
prove to be a configuration file (use @component also, because the @configuration will be found after the @component)
@Configuration
//prove to be a slice
@Aspect Public
class CONTROLLERAOP {
    //wrapping
    an AOP//execution expression This expression represents scanning controller all the methods of all the classes that perform this AOP
    @Around ("Execution" (* com.beyondli.controller. *.*(..))")
    Public Object TESTAOP (Proceedingjoinpoint Pro) throws Throwable {
        //Get response
        HttpServletResponse = ((servletrequestattributes) requestcontextholder.getrequestattributes ()). GetResponse ();
        Core Settings
        response.setheader ("Access-control-allow-origin", "*");

        The method that executes the call
        Object proceed = Pro.proceed ();
        Return proceed
    }

}

At this point we have access, the effect is as follows, the cross-domain problem solved perfectly.

The purpose of writing this article is mainly because of the more and more separation of the front and back, cross-domain problems encountered more and more high probability, so write this article, hoping to help students in need.

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.