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.
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: trueIn Spring, you can enable CORS by adding the @CrossOrigin annotation on a controller class or method.
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("/");
}
});Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
