SoFunction
Updated on 2025-03-08

Analysis of cross-domain problem solving Js in Java development

This article mainly introduces the analysis of the cross-domain problem solving in Java development. The article introduces the example code in detail, which has certain reference value for everyone's learning or work. Friends who need it can refer to it.

There are two mainstream methods: JSONP and CORS. Here is a note of the latter method. The theoretical basis is to add the following attributes to the http request header when requesting:

//Specify that other domain names are allowed to accessAccess-Control-Allow-Origin:http://localhost:8989

If the backend is developed in Java, you can add the following attributes in the return request

1. In cross-domain issues, if you do not operate cookies, you only need to add the following code to the backend code.

("Access-Control-Allow-Origin", "http://localhost:8989");
//The second parameter means which address to access,If you want to install all,Just use*Just

Although it is added to the response, HTTP is based on the application layer protocol of TCP (Transport Layer Protocol). There will be a "three-time handshake" process every time you request. Therefore, after adding it to the response, the client will be informed in the first request that you can request it.

If it is SpringMVC4.2 or above, a comment can be done

@CrossOrigin(origins=http://localhost:8080)

This annotation is the encapsulation of the above code, the source code is as follows:

@Target({, })
@Retention()
@Documented
public @interface CrossOrigin {
  @Deprecated
  String[] DEFAULT_ORIGINS = new String[]{"*"};
  @Deprecated
  String[] DEFAULT_ALLOWED_HEADERS = new String[]{"*"};
  @Deprecated
  boolean DEFAULT_ALLOW_CREDENTIALS = false;
  @Deprecated
  long DEFAULT_MAX_AGE = 1800L;

  @AliasFor("origins")
  String[] value() default {};

  @AliasFor("value")
  String[] origins() default {};

  String[] allowedHeaders() default {};

  String[] exposedHeaders() default {};

  RequestMethod[] methods() default {};

  String allowCredentials() default "";

  long maxAge() default -1L;
}

@Deprecated: If a certain class or method is added with this annotation, it means that this method or class is no longer recommended to be used, and a delete line will appear when calling, but it does not mean that it cannot be used. It is just that it is not recommended to use it, because there are better methods to call it.

2. If the cross-domain request involves the operation of cookies, add an attribute, the code and the annotation are respectively

("Access-Control-Allow-Origin", "http://localhost:8989");
("Access-Control-Allow-Credentials", "true");
@CrossOrigin(origins="http://localhost:8989",allowCredentials="true")

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.