Implementation of jsonp cross-domain and rest interface

    jsonp is a mode of json, which is specially used to solve the problem of front-end cross-domain request data. It allows script tags to be generated on the server side and returned to the client side to achieve site access in the form of javascript callback.
    Generally speaking, Ajax request data does not have permission to request cross-domain data. You can only request the interface under this domain name, and then call the services of other domain names, that is, the mode of your own front-end -> your own back-end -> other people's back-end, which is still very unusual. convenient.
The front-end of your own -> the back-end of others is a cross-domain request. Although the browser does not allow the script program in the page to read data cross-domain, it allows HTML to refer to cross-domain resources, so the front-end call js files can be cross-domain. As long as it is a resource file, it can support cross-domain.
    To support cross-domain, in addition to the front-end script to implement jsonp mode requests, the server also needs to encapsulate the returned data into a common js file format. When the front-end receives the data in the js file format, it will automatically parse the data and process it. And because js natively supports json, the server can process the data in json format.
    In the process of transmission, the front-end can pass a callback parameter, the server parses it and returns it to the front-end as a function name, and the front-end verifies whether the callback parameter is consistent.
    This calling method is jsonp.

Front-end implementation:
$.ajax({
        url: "//xxx.com/xxx",
        type: "get",
        dataType: "jsonp",
        data: "",
        success: function(s) {
            alert(s);
        }
    })


Server implementation:
1) servlet interface
@RequestMapping(value="/xxx")  
public void doGet(HttpServletRequest request, HttpServletResponse response) {  
    String callback = request.getParameter("callback");  
    response.setContentType("application/x-javascript");  
    response.setCharacterEncoding("UTF-8");  
    
    try {  
      PrintWriter out = response.getWriter();  
      String jsonp = "jsonp data";
      out.write(callback+ "(" + jsonp + ")");   
      out.flush();  
      out.close();  
    } catch (IOException e) {  
      e.printStackTrace ();  
    }  
}  

2) Rest interface
1.web.xml adds monitoring
<listener>      
    <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>  
</listener>

2.java implementation:
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String callback = request.getParameter("callback");
String jsonp = "jsonp data";
return callback + "(" + jsonp + ")";

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326991848&siteId=291194637