Sample sharing of cross domain submission requests using JQuery and servlets

  • 2020-03-30 01:39:58
  • OfStack

How it works: JavaScript Ajax can't cross domains, but it can do so by making a request to a local Servlet, which does the work. The remote structure is then returned to the client. This allows Ajax to cross domains. In the back, and send a version of PHP, please pay attention to ah. Here's the code

JS code:

Note: in Post mode, param1 and param2 are parameter values sent to the remote and can have multiple values.


//The GET method
function reqeustCrossDomainProxyGet(){
    var url = "http://www.baidu.com";//Remote request address
    var param = {'requesturl':url,'typedata':'JSON'};
    var data = getCrossDomainProxyRemote(param,"json");
}
//Post way
function reqeustCrossDomainProxyPost(param1,param2){
    var url = apiServer+"/api/lucene/query";
    var param = {'requesturl':url,'typedata':'JSON','param1':param1,'param2':param2};
    var data = getCrossDomainProxyRemote(param,"json");
}

function getCrossDomainProxyRemote(param,rtype){
    var url = "/cross/proxy";//The URL address of the Servlet
    var returndata;
    $.ajax({
        url: url,type: 'POST',dataType: rtype,timeout: 40000,data:param, async:false,
        error: function(response,error) {alert(response.status);},
        success: function(data){returndata=data;}
    });
    return returndata;
}

Java code:


public class CorssDomainProxy extends HttpServlet {

    public void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        this.doPost(req, resp);     
    }

    public void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        boolean requestType = false;//Marks the remote request type, default to GET
        PrintWriter out = resp.getWriter();
        Enumeration keys = req.getParameterNames();//Takes all the parameter names passed in by the client
        ArrayList<String> params = new ArrayList<String>();
        String url=null;
        while (keys.hasMoreElements()){
            String key = (String) keys.nextElement();
            
            if(key.equals("requesturl")){//Determine whether the parameter is the remote request address
                url = req.getParameter(key);
            }else if(key.equals("typedata")){//Not used to determine the request data type

            }else if(key.equals("returntype")){//This is not used to determine the return type of the request

            }else{
                params.add(key);//Other add parameters list, here are the parameters to participate in the remote request
                requestType = true;//Modify the mark, table for remote request for POST
            }
        }

        HttpClient client = new HttpClient();
        HttpMethod method = null;
        if(requestType){//Determine the request mode and instantiate the HttpMethod object, true:POST,false:GET
            method = new UTF8PostMethod(url);
            for(String name : params){//Iterate over the POST parameter, adding it to the request
                String _value = req.getParameter(name);
                ((PostMethod)method).setParameter(name,_value);
            }
        }else{
            method = new GetMethod(url);
        }       
        client.executeMethod(method);//Perform the requested
        String bodystr = method.getResponseBodyAsString();//Returns the result
        out.println(bodystr);//Returns the result to the client
    }

    
    private static class UTF8PostMethod extends PostMethod { 
        public UTF8PostMethod(String url) { 
            super(url); 
        } 
        @Override
        public String getRequestCharSet() { 
            return "UTF-8"; 
        } 
    }

}


Related articles: