Using jquery and servlet to implement cross domain submission requests sample points

Source: Internet
Author: User
Tags json static class

  This article mainly introduces examples of Cross-domain submission requests using jquery and servlet, which can be referenced by friends in the following

Principle: JavaScript Ajax cannot be cross-domain, but it can be done across domains by issuing a request to a servlet in the local area. The remote structure is then returned to the client. This will allow Ajax to cross the domain. In the back, and then send a PHP version, please pay attention AH. Here is the code   JS code:   NOTE: In the post mode, param1 and param2 are sent to the remote parameter values, can have more than one.     Code as follows://get mode function Reqeustcrossdomainproxyget () {    var url = "http://www.baidu.com";/ Remote Request address     var param = {' requesturl ': url, ' typedata ': ' JSON '};     var data = Getcrossdomainproxyremote (param, "json"); //post mode function Reqeustcrossdomainproxypost (param1,param2) {    var url = apiserver+ "/api/lucene/query"; & nbsp   var param = {' requesturl ': url, ' typedata ': ' JSON ', ' param1 ':p aram1, ' param2 ':p aram2};     var data = Getcrossdomainproxyremote (param, "json"); }  /**  * JS sends a POST request to a servlet in this address, all parameters about the remote request.  * is sent here to the servlet  * @param param remote Request parameters  * @param rtype js return type (temporarily unavailable)  * @return  */func tion Getcrossdomainproxyremote (param,rtype) {    var url = "/cross/proxy";//servlet URL address    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:     Code as follows: public class Corssdomainproxy extends HttpServlet {      public void Doget (HttpServletRequest req, HttpServletResponse resp)             throws Serv Letexception, IOException {        This.dopost (req, resp);         }       public void DoPost (HttpServletRequest req, HttpServletResponse resp)           &NB Sp Throws Servletexception, IOException {        Boolean requesttype = false;//mark Remote request type, default to get way         PrintWriter out = Resp.getwriter ();         Enumeration keys = Req.getparameternames ()//Remove all parameters incoming by client         Arrayli st<string> params = new arraylist<string> ();         String url=null;         while (keys.hasmoreelements ()) {            String key = (string ) keys.nextelement ();            /**              * If there are several representations within the request parameter, this parameter does not participate in the remote request              */            if (key.equals ("Requesturl")) {//Determine if parameter is, remote request address                 URL = req.getparameter (key);     &NBSP ;      }else if (key.equals ("Typedata")) {//Judging request data type, temporarily not used              } else if (key.equals ("ReturnType")) {//Judgment request return type, temporarily not used              }else{&NBSp               Params.add (key)//Other add parameter list, here is the parameter of participating remote request         &NBSP ;       RequestType = true;//modification tag, table request for a post mode            ,     &NB Sp  }           HttpClient client = new HttpClient ();         HttpMethod method = null;         if (RequestType) {//Judging request mode, and instantiating HttpMethod object, True:post,false:get         & nbsp   method = new Utf8postmethod (URL);             for (String name:params) {//Iteration post parameter, join to request           & nbsp     String _value = req.getparameter (name);                 ((Postmethod) method) Setparameter (Name,_value);                    }else{            m Ethod = new GetMethod (URL);   &nbsp    }                Client.executemethod (method);//Execute request     & nbsp   String bodystr = method.getresponsebodyasstring ()//return result         OUT.PRINTLN (BODYSTR); Return results to client    }      /**      * internal class, convert URL string to UTF-8      * @author Administrator      *      */    private static class Utf8postmethod extends Postm Ethod {          public utf8postmethod (String URL) {            &NB Sp Super (URL);         }          @Override         PU Blic String Getrequestcharset () {              return "UTF-8";      &NBS P  }     }  }  

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.