Mastering Cross-Origin Requests in Spring: JSONP and CORS Solutions

This article explains the concept of cross-origin, why it occurs in modern web architectures, and provides practical Spring‑based solutions using JSONP and CORS together with jQuery AJAX examples, complete with configuration snippets and code samples.

Programmer DD
Programmer DD
Programmer DD
Mastering Cross-Origin Requests in Spring: JSONP and CORS Solutions

What is Cross-Origin?

One sentence: if the IP, network protocol, and port are all identical, the request is same‑origin; otherwise it is cross‑origin.

Why Cross-Origin?

Two main reasons: web applications are often deployed on different servers, and front‑end/back‑end separation leads to different domains or subdomains (e.g., various baidu.com subdomains).

Using JSONP in Spring to Solve Cross-Origin

Spring 4 adds native JSONP support via a ControllerAdvice. Create an advice class (e.g., JsonpAdvice) that extends AbstractJsonpResponseBodyAdvice and specify the callback parameter name.

package cn.isuyang.web.sso.advice;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.AbstractJsonpResponseBodyAdvice;
/**
 * Use JSONP to enable cross‑origin support
 */
@ControllerAdvice("cn.isy.web.sso.web")
public class JsonpAdvice extends AbstractJsonpResponseBodyAdvice {
    public JsonpAdvice() {
        super("callback");
    }
}

The @ControllerAdvice("cn.isy.web.sso.web") limits the advice to the specified package, and super("callback") tells Spring to look for a callback query parameter (e.g., http://sso.isy.cn/logout?callback=successCallback).

You can also override beforeBodyWriteInternal in AbstractJsonpResponseBodyAdvice to return JSONP only when the callback is present.

jQuery AJAX with JSONP

$.ajax({
    type: "get",
    async: false,
    dataType: 'jsonp',
    url: 'http://sso.isy.cn/login.json',
    data: $("#loginForm").serialize(),
    crossDomain: true,
    jsonpCallback: "successCallback",
    xhrFields: { withCredentials: true },
    success: function(data) { /* handle success */ },
    error: function(data) {
        console.log("登录出错");
        $.we.utils.gotoUrl("/");
    }
});

Note: the request must use JSONP to bypass same‑origin restrictions.

Using CORS (Cross‑Origin Resource Sharing)

CORS allows browsers to make cross‑origin requests when the server includes specific response headers.

Access-Control-Allow-Origin: http://www.YOURDOMAIN.com
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Headers: Authorization
Access-Control-Allow-Credentials: true

In Spring, you can enable CORS by adding the @CrossOrigin annotation on a controller class or method.

CrossOrigin annotation example
CrossOrigin annotation example

jQuery AJAX with CORS

When CORS is configured, a regular AJAX request can be used (no JSONP needed).

$.ajax({
    type: "get",
    url: 'http://sso.isy.cn/login.json',
    data: $("#loginForm").serialize(),
    xhrFields: { withCredentials: true }, // required for cookies
    success: function(data) { /* handle success */ },
    error: function(data) {
        console.log("登录出错");
        $.we.utils.gotoUrl("/");
    }
});
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendspringCORSCross-OriginJSONPjQuery
Programmer DD
Written by

Programmer DD

A tinkering programmer and author of "Spring Cloud Microservices in Action"

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.