Home Web Front-end JS Tutorial Using JQuery and Servlet to implement cross-domain submission request example sharing_jquery

Using JQuery and Servlet to implement cross-domain submission request example sharing_jquery

May 16, 2016 pm 05:00 PM
servlet

Principle: JavaScript's Ajax cannot cross domains, but it can complete the cross-domain by sending a request to a local Servlet. Then return the remote structure to the client. This way Ajax can work across domains. I will release a PHP version later, please pay attention. Below is the code

JS code:

Note: In Post mode, param1 and param2 are parameter values ​​sent to the remote, and there can be multiple.

Copy code The code is as follows:

//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 method
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");
}

/**
* JS sends a POST request to a Servlet at this address, with all parameters related to the remote request.
* Use POST method here to send to Servlet
* @param param remote request parameters
* @param rtype JS return type (not used yet)
* @return
*/
function getCrossDomainProxyRemote(param,rtype){
var url = "/cross/proxy";//Servlet’s 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:

Copy code The code is as follows:

public class CorssDomainProxy extends HttpServlet {

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

public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
boolean requestType = false;//Mark remote request type, default is GET method
PrintWriter out = resp.getWriter();
Enumeration keys = req.getParameterNames();//Get all parameter names passed in by the client
ArrayList params = new ArrayList();
String url=null;
while (keys.hasMoreElements()){
String key = (String) keys.nextElement();
/**
           * If the request parameter contains the following expressions, this parameter does not participate in the remote request
            */
if(key. equals("requesturl")){//Determine whether the parameter is, remote request address
   url = req.getParameter(key);
   }else if(key.equals("typedata")){//Judge Request data type, not used for the time being

}else if(key.equals("returntype")){//Determine the request return type, not used for the time being

}else{
Params.add (key); // Other additional parameters list, here is the parameters participating in the remote request
RequestType = TRUE; // Modify the mark, and the remote request is the post method
}
}}

HttpClient client = new HttpClient();
HttpMethod method = null;
if(requestType){//Determine the request method and instantiate the HttpMethod object, true:POST, false:GET
Method = new UTF8PostMethod(url);
for(String name: params){//Iterate the POST parameters and add them to the request
String _value = req.getParameter(name);
((PostMethod )method).setParameter(name,_value);
                                                                        method);//Execute the request
     String bodystr = method.getResponseBodyAsString();//Return the result
       out.println(bodystr);///Return the result to the client
                                                                                                                 */
private static class UTF8PostMethod extends PostMethod {
public UTF8PostMethod(String url) {
super(url);
}
@Override
public String getRequestCharSet() {
            return "UTF-8";
                  
    }

}
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

The servlet life cycle is divided into several stages The servlet life cycle is divided into several stages Feb 23, 2023 pm 01:46 PM

The Servlet life cycle refers to the entire process from creation to destruction of a servlet, which can be divided into three stages: 1. Initialization stage, calling the init() method to initialize the Servlet; 2. Running stage (processing requests), the container will Request to create a ServletRequest object representing an HTTP request and a ServletResponse object representing an HTTP response, and then pass them as parameters to the service() method of the Servlet; 3. Destruction phase.

What is a servlet What is a servlet Jan 28, 2023 am 09:51 AM

The full name of Servlet is "Java Servlet", which means small service program or service connector in Chinese. It is a program running on a Web server or application server. It serves as a request from a Web browser or other HTTP client and a database on the HTTP server or The middle layer between applications. Servlet has the characteristics of being independent of platform and protocol. Its main function is to browse and generate data interactively and generate dynamic Web content.

How does Java Servlet implement distributed session management? How does Java Servlet implement distributed session management? Apr 16, 2024 pm 02:48 PM

There are two ways to implement distributed session management in JavaServlet: 1. Session replication: Copy session data to each server. 2. Session distribution: Use a centralized storage service to store session data and access it from multiple servers. The specific implementation methods are: session replication configures true in the web. session data.

What are the application scenarios of Java Servlet? What are the application scenarios of Java Servlet? Apr 17, 2024 am 08:21 AM

JavaServlet can be used for: 1. Dynamic content generation; 2. Data access and processing; 3. Form processing; 4. File upload; 5. Session management; 6. Filter. Example: Create a FormSubmitServlet to handle form submission, taking name and email as parameters, and redirecting to success.jsp.

Java technology stack for web development: Understand Java EE, Servlet, JSP, Spring and other technologies commonly used in web development Java technology stack for web development: Understand Java EE, Servlet, JSP, Spring and other technologies commonly used in web development Dec 26, 2023 pm 02:29 PM

JavaWeb development technology stack: Master JavaEE, Servlet, JSP, Spring and other technologies used for Web development. With the rapid development of the Internet, in today's software development field, the development of Web applications has become a very important technical requirement. As a widely used programming language, Java also plays an important role in the field of Web development. The JavaWeb development technology stack involves multiple technologies, such as JavaEE, Servlet, JSP, Spr

Java Errors: Servlet Errors, How to Fix and Avoid Java Errors: Servlet Errors, How to Fix and Avoid Jun 25, 2023 pm 06:34 PM

Servlet is a very commonly used technology in Java Web application development. However, some Servlet errors will inevitably occur during the development process. How to solve and avoid Servlet errors has become a top issue for many Java developers. This article will introduce some common Servlet errors and their solutions based on personal experience and related information. ClassNotFoundException When we try to load a class, if the class does not exist or cannot be accessed by the system,

HttpSession interface in Servlet HttpSession interface in Servlet Sep 02, 2023 am 10:05 AM

In the world of Java Web development, understanding the HttpSession interface is key to creating dynamic and responsive web applications. In this article, we will explore what the HttpSession interface is, how it works, and why it plays a crucial role in the Servlet specification. What is the HttpSession interface? At its core, the HttpSession interface is a fundamental component of the JavaServlet API, which enables web developers to track a user's session across multiple HTTP requests. When a user accesses a web application for the first time, a unique session is created to represent their interaction. This session allows the application to maintain state between requests and remember information about

How to manually configure Servlet to run in Tomcat in Java? How to manually configure Servlet to run in Tomcat in Java? Apr 26, 2023 am 09:55 AM

1. The preparation work is as shown below. First create each file as required. If you think it can run, you are wrong (I was stuck here at the beginning). The project structure of idea. If you have learned to use idea to create servlet applications, you must You will find that the web.xml provided here is not complete at all. Please use the following code to include the above-mentioned servlet tag //Add the above-mentioned servlet tag code here 2. The problem with encoding the compiled file is as above. I wanted to compile it at first, but an error was reported. The reason here is that javac will read the source file code according to your operating system encoding, and my computer defaults to GBK, but we all write these source codes in Notepad, and Notepad uses UTF-8 by default. save at

See all articles