Solution for Cross-domain access implemented with JSONP

Source: Internet
Author: User
Tags json stub in domain port number to domain

Cross-domain access has been one of the problems that has plagued many developers. Because of security concerns, Cross-domain access is not possible by default, otherwise assume today I wrote a paragraph of JS to change the Google icon, tomorrow he wrote a piece of code to go to the Google homepage of the text all turned into Sanskrit, that also got?

First, talk about what is the same domain. Domain is defined in this way, protocol name +host + port number, only these 3 are the same, can be said to be the same domain, the same domain access is not subject to the same source policy restrictions, you can use your JS code arbitrary to manipulate resources, but different domains you can not do so.

There are many ways to resolve cross-domain access, the most common one-way cross-domain access is Jsonp (Json with Padding), which solves the idea that if domain A (acting as a client) is to operate on domain B (acting as a server), So as long as it's on the field a JS function name passed to Domain B, it is then encapsulated in domain B, which resolves the function name from domain A and converts the resource on domain B into a JSON object, combining the two together, and the combined string is the form of the function call of the domain A function name (domain B JSON object). Then, when domain A uses the script src=\ ' #\ ' "> Domain a function name (domain B JSON object), it achieves the effect of domain A function processing domain B resources.

In order to be more persuasive, we do a very simple experiment here, assuming that domain A (client) has an application deployed on the http://localhost:8180, domain B (server side) has an application deployed on the http://localhost:8080, Obviously these 2 domains are different because of ports, so domain A must be accessed across domains if you want to access domain B. Domain A has a JS function, Domain B provides a JSON object, we want the JS function of domain A to manipulate the JSON object of domain B. What will happen?

Service side (we are deployed on http://localhost:8080):

First put on domain B (server-side code), which uses a Java servlet to receive requests from the client with callback function name parameters, and to wrap the JSON object supplied with its own side, wrapping it as a jsonp and then putting it in the response output stream.

Package Com.charles.jsonp; 
Import java.io.IOException; 
     
Import Java.io.PrintWriter; 
Import javax.servlet.ServletException; 
Import Javax.servlet.http.HttpServlet; 
Import Javax.servlet.http.HttpServletRequest; 
     
Import Javax.servlet.http.HttpServletResponse; 
     
Import Org.json.simple.JSONObject;  /** * Servlet Implementation Class Jsonpservlet */public class Jsonpservlet extends HttpServlet {private static 
            
    Final long serialversionuid = 1L; 
        /** * @see httpservlet#httpservlet () * * * Public jsonpservlet () {super (); TODO auto-generated Constructor stub}/** * @see httpservlet#doget (httpservletrequest request, H Ttpservletresponse response) */protected void doget (HttpServletRequest request, httpservletresponse response) t Hrows servletexception, IOException {//TODO auto-generated method stub//get the Callbac K function which comes from CLIent String callbackfuncfromclient= request.getparameter ("Callbackfunc"); 
        Create a JSON object Jsonobject jsoninfo = new Jsonobject (); 
        Jsoninfo.put ("name", "Charles"); 
        Jsoninfo.put ("title", "Technical Lead"); 
        Jsoninfo.put ("info", "Talent Man"); Create a string which stands for a JavaScript with the format func (jsonobject) StringBuffer jsonpstring = new S 
        Tringbuffer (); 
             
             
        Jsonpstring.append (callbackfuncfromclient). Append ("()). Append (Jsoninfo.tojsonstring ()). Append (") "); 
        Construct the output JSONP and output to the client response.setcharacterencoding ("Utf-8"); 
        PrintWriter out = Response.getwriter (); 
        Out.println (jsonpstring); 
    Out.flush (); /** * @see Httpservlet#dopost (httpservletrequest request, httpservletresponse response) * * PR otected void DoPost (HttpServletRequest request, HttpServletResponse RespoNSE) throws Servletexception, IOException {//TODO auto-generated method stub}} 

Then we map this servlet to a URL, see web.xml:

<servlet> 
    <description>this servlet would create a JSONP object,it wraps the JS function and the JSON OBJEC t</description> 
    <display-name>JSONPServlet</display-name> 
    <servlet-name> Jsonpservlet</servlet-name> 
    <servlet-class>com.charles.jsonp.jsonpservlet</servlet-class > 
  </servlet> 
  <servlet-mapping> 
    <servlet-name>jsonpservlet</servlet-name > 
    <url-pattern>/JSONPServlet</url-pattern> 
  </servlet-mapping>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.