The json scheme

implementation

In the Controller, the direct return com. Fasterxml. Jackson. Databind. Util. JSONPObject object, front-end code can be used for the json project acceptance.

@requestMapping (value = "/test")
 @responseBody public Object test(@requestParam (required = false,name = "callback") String callback) {Map result = new HashMap<>(); Result. put("result"," returned result"); If (callback = = null | | "" equals (the callback)) {college return result; 
} else {
 return new JSONPObject(callback, result); // JSONP request, return JOSNP data 
} 
}Copy the code

disadvantages

JSONP can only use GET requests. For RESTful apis, sending POST/PUT/DELET requests becomes a problem, which is not conducive to interface unification.

Share the CORS scheme

implementation

CORS requires both browser and server support. Currently, all browsers support this function, and Internet Explorer cannot be lower than Internet Explorer 10. Acting without the front-end processing, the back-end code, Header Header to add Access – Control – Allow – Origin: https://static.ixiaozhi.com to tell the browser to Allow the domain name.

CORS has simple and non-simple requests, and the difference can be seen in The Ruan Yifeng weblog in Resources.

On the Java server side, we use Filter to add the relevant Header information in bulk.

CORSFilter class code:

package com.ixiaozhi.filter; import org.springframework.web.filter.OncePerRequestFilter; import javax.servlet.FilterChain; College import javax.mail. Servlet. ServletException; College import javax.mail. Servlet. HTTP. It; College import javax.mail. Servlet. HTTP. HttpServletResponse; import java.io.IOException; 

/**
 * Created by ixiaozhi
 */ public class CORSFilter extends OncePerRequestFilter {@override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain FilterChain) throws ServletException, IOException {// CORS domain name whitelist, which does not support formal. Allow all can use * response. AddHeader (" Access - Control - Allow - Origin ", "https://static.ixiaozhi.com"); 
 // For non-simple requests, the browser automatically sends an OPTIONS request, If (request.getheader (" access-Control-request-method ")! = null && "OPTIONS".equals(request.getMethod())) { response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE"); response.addHeader("Access-Control-Allow-Headers", "Content-Type"); response.addHeader("Access-Control-Max-Age", "1"); } college filterChain. DoFilter (request, response); } college}Copy the code

The filter is configured in web.xml:

College cors com. Ixiaozhi. Filter. CORSFilter college cors / * collegeCopy the code

Otherwise, the front-end code uses normal Ajax calls without concern for cross-domain issues.

The resources

  • Cross-domain resource sharing (CORS