Servlet processing (jQuery) Ajax requests

1. jQuery

jQuery is a JavaScript function library, which greatly simplifies JavaScript programming and is easy to learn. jQuery is the most popular open source js framework, and provides a lot of extensions.

2. Ajax

Ajax(Asynchronous JavaScript and XML) is a kind of web development technology to create interactive web applications. It is not a new technology. Its purpose is to achieve the local refresh of the page. Ajax technology can make the previous application not refresh the whole page every time it submits, so as to improve the performance of the operation.

3. GET and POST

The two most commonly used HTTP methods are GET and POST.

Definition: GET requests data from specified resources, and POST submits data to be processed from specified resources.

Data content: after the GET request data is attached to the url, only ASCII characters (ASCII encoding) are allowed, and the requested data will be exposed in the address bar. The POST request will put the requested data in the package body of the HTTP request package, and also allow binary data, without exposing the data in the address bar.

Data length: GET is limited. When using GET requests, the data size is limited by the URL length (the maximum length of the URL is 2048 characters). POST is unlimited.

Security: GET is less secure (compared to POST) because the data sent is part of the URL. Never use GET when sending passwords or other sensitive information! POST is safer than GET because parameters are not saved in the browser history or web server logs.

4. Jackson

Jackson is a widely used Java open source framework for serializing and deserializing json. The Jackson community is relatively active and the update speed is relatively fast. From the statistics in Github, Jackson is one of the most popular json parsers, and the default json parser of Spring MVC is Jackson.

5. Servlet processing (jQuery) Ajax request (do not send data / send key/value data / send json data)

Development environment: eclipse+jsp+jQuery+servlet+tomcat+ajax

5.1 Servlet processing (jQuery) Ajax request (do not send data, return normal text)

(1) construction environment:

Create a new Java web project in eclipse (the JRE System Library package will be imported automatically). For example, I write the project name as AjaxDemo1, and deploy the project to tomcat server. The following is the directory structure of the project in Eclipse:

Let's not worry about the jar package in lib. Note that there is a jquery-3.2.1.min.js. This is the development package of jQuery. We can download it on the Internet, copy and paste the JS file into the WebContent directory. Next I will analyze step by step. Let's develop.

(2) write index.jsp file

    

 1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
 2 
 3 <%-- <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> --%>
 4 <%
 5     String path = request.getContextPath();
 6     String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
 7             + path + "/";
 8 %>
 9 <!DOCTYPE html>
10 <html>
11 <head>
12 <base href="<%=basePath%>">
13 <title>I LOVE YOU</title>
14 <link rel="stylesheet" type="text/css" href="">
15 <script type="text/javascript" src="index.js"></script>
16 <script type="text/javascript" src="jquery-3.2.1.min.js"></script>
17 
18 
19 </head>
20 <body>
21 
22 
23 <button id="mybutton" value="Asynchronous request server" onclick="fun1()" >(jquery)(jQuery)ajax Request (do not send data)</button>
24 <spand id="show" />
25 
26 <br/>
27 <hr/>
28 
29 
30 <button id="mybutton1" value="Asynchronous request server" onclick="fun2()" >Send data in the format key/value ( jquery)ajax request</button>
31 <spand id="show1" />
32 
33 <br/>
34 <hr/>
35 <button id="mybutton2" value="Asynchronous request server" onclick="fun3()" >Send data in the format json Of(jquery)ajax request</button>
36 <spand id="show2" /><br/>
37 
38 </body>

Here we implement three buttons and call the corresponding function. Let's first look at the first button (id="mybutton"). This file introduces two JS files. One is the index.js file that we wrote by ourselves, the other is the JS file that we used when we used the jQuery framework to develop. I put index.jsp, index.js, jquery-3.2.1.min.js in the WebContent directory (easy to operate).

Write index.js file

    

 1 /**
 2  * 
 3  */
 4 //Use jquery Submission ajax Request (without data)
 5 function fun1(){
 6     
 7     $.ajax({
 8         
 9         type:"POST",                    //Sending mode
10         url:"AjaxServlet",                //Request address
11         data:"",                           //Data is empty.
12         success:function(data){             //Callback function after success
13             
14             $("#show").html(data);            //Page display content
15             
16         }            
17     });
18 }
19 
20 
21 //Use jquery Submission key/value Data ( ajax Request)
22 
23 function fun2(){
24     
25     $.ajax({
26         
27         type:"POST",
28         url:"AjaxServlet1",
29         data:"username=wly&password=1314520",        //key/value data
30         success:function(data){
31             
32             $("#show1").html(data);
33             
34         }            
35     });
36 
37 }
38 
39 
40 //Use jquery Submission json Data ( ajax Request)
41 
42 function fun3(){
43     
44     var user={                        //accord with json Data format standard javascript object
45             "username":"wly",
46             "password":"1314520"    
47     };    
48 $.ajax({
49         
50         type:"POST",
51         url:"AjaxServlet2",
52         contentType:"application/json;charset=UTF-8", //Content type used when sending data to the server
53         data:JSON.stringify(user),    //take javascript Object to json Character string
54         
55         //The data type of the expected server response. Server return json Character string. jquery Will automatically handle json Translate into js object
56         dataType:"json",    //Equivalent to calling JSON.parse(data)Method. At this time, we can save it.      
57         success:function(data){
58             
59             $("#show2").html(data.username+" "+data.password);
60             
61         }            
62     });
63 }

Observe fun1() function. data is empty. It's very simple. The code has comments. I don't explain too much here. It reflects the style of jQuery and is easy to use.

(4) write Srvlet file

    

package com.servlet;

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;

public class AjaxServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.print("I miss you ha ha!");
        out.close();
    }

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

 

The code is very simple, just return a sentence (plain text). There's nothing to say.

(5) web.xml file configuration Servlet

    

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>AjaxDemo</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
   
  <servlet>
      <servlet-name>AjaxServlet</servlet-name>
      
      <servlet-class>com.servlet.AjaxServlet</servlet-class>
  </servlet>
  
  <servlet>
      <servlet-name>AjaxServlet1</servlet-name>
      
      <servlet-class>com.servlet.AjaxServlet1</servlet-class>
  </servlet>
  
  
   <servlet>
      <servlet-name>AjaxServlet2</servlet-name>
      
      <servlet-class>com.servlet.AjaxServlet2</servlet-class>
  </servlet>
  
    
  
  <servlet-mapping>
      
      <servlet-name>AjaxServlet</servlet-name>
      <url-pattern>/AjaxServlet</url-pattern>
      
  </servlet-mapping>
  
   <servlet-mapping>
      
      <servlet-name>AjaxServlet1</servlet-name>
      <url-pattern>/AjaxServlet1</url-pattern>
      
  </servlet-mapping>
  
  <servlet-mapping>
      
      <servlet-name>AjaxServlet2</servlet-name>
      <url-pattern>/AjaxServlet2</url-pattern>
      
  </servlet-mapping>
  
</web-app>

Configuration is simple. It's needless to say here. This is an advanced version of ajax. If you don't understand, you can read my first blog: Servlet handles native Ajax requests

(6) run program

Start tomcat, enter the address in the browser, and click the button. The operation effect is as follows:

    

5.2 Servlet processing (jQuery) Ajax request (sending key/value data, returning normal text)

(1) write jsp file

The index.jsp file above has been written. Just look at the second button.

(2) write js file

index.js above has been written. Pay attention to fun2() function, which sends key/value type data.

(3) write Servlet file

   

 1 package com.servlet;
 2 
 3 import java.io.IOException;
 4 import java.io.PrintWriter;
 5 
 6 import javax.servlet.ServletException;
 7 import javax.servlet.http.HttpServlet;
 8 import javax.servlet.http.HttpServletRequest;
 9 import javax.servlet.http.HttpServletResponse;
10 
11 public class AjaxServlet1 extends HttpServlet {
12 
13     protected void doGet(HttpServletRequest request, HttpServletResponse response)
14             throws ServletException, IOException {
15 
16         response.setContentType("text/html;charset=UTF-8");
17         PrintWriter out = response.getWriter();
18         String username = request.getParameter("username");
19         String password = request.getParameter("password");
20         System.out.println(username + " " + password);
21         out.print("helloworld " + "username:" + username + " password:" + password);
22         out.close();
23 
24     }
25 
26     protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
27         this.doGet(req, resp);
28     }
29 }

Use request.getParameter(String stringParam) to accept the data from the client. Returns a connection string.

(4)web.xml file configuration Servlet

It's already configured. I won't talk about it here.

(5) run program

    

5.3 Servlet processing (jQuery) Ajax request (sending json data, returning json data)

(1) import Jackson's jar package

Jackson is a third-party class library used to parse json data. Through the above project directory, we find that there are three Jaskson related development packages under lib. Jackson core module consists of three parts:

1. Jackson core package, which provides related API based on "flow pattern" parsing, includes JsonPaser and JsonGenerator. Jackson's internal implementation is to generate and parse json through JsonGenerator and JsonParser of high-performance flow pattern API.

2. Jackson annotations annotation package, which provides standard annotation function;

3. Jackson databind data binding package, which provides the related API (ObjectMapper) based on "object binding" resolution and the related API (JsonNode) based on "tree model" resolution; the API based on "object binding" resolution and the API based on "tree model" resolution rely on the API based on "flow mode" resolution.

If you are interested, you can study the source code. I won't talk about it here. Here we find that there are fewer jar packages imported by Jackson (compared with JSON LIB).

(2) create a new entity User class

   

 1 package com.entity;
 2 
 3 public class User {
 4 
 5     private String username;
 6 
 7     private String password;
 8 
 9     public String getUsername() {
10         return username;
11     }
12 
13     public void setUsername(String username) {
14         this.username = username;
15     }
16 
17     public String getPassword() {
18         return password;
19     }
20 
21     public void setPassword(String password) {
22         this.password = password;
23     }
24 
25     @Override
26     public String toString() {
27         return "User [username=" + username + ", password=" + password + "]";
28     }
29 
30 }

 

It's easy to understand, not to say much.

(3) write jsp file

It's already written. Just look at the third button.

(4) write js file

Just look at the fun3() function. The code has comments. Note that the content type property is used to send data to the server. Here we set the content type: "application / json; charset = UTF-8". Specifies that the format of the sent data is json format and the character encoding is UTF-8. There is also a dataType property. We set it to "json". When the server responds successfully, we call the callback function, which is equivalent to knowing the data type of the server's response, and then we can automatically convert the json string into a javascript object. Equivalent to JSON.parse(data) method. We omit this method here, because jQuery has helped us format it.

(5) compile Servlet file

First, write Jackson's tool class.

   

 1 package com.util;
 2 
 3 import java.io.BufferedReader;
 4 import java.io.IOException;
 5 import java.io.InputStreamReader;
 6 import java.io.UnsupportedEncodingException;
 7 
 8 import javax.servlet.http.HttpServletRequest;
 9 
10 import com.entity.User;
11 import com.fasterxml.jackson.databind.ObjectMapper;
12 
13 public class JsonReader {
14 
15     public static User receivePost(HttpServletRequest request) throws UnsupportedEncodingException, IOException {
16 
17         // Read request content
18         BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
19 
20         String line = null;
21         StringBuilder sb = new StringBuilder();
22 
23         while ((line = br.readLine()) != null) {
24             sb.append(line);
25         }
26 
27         // take json String to java object
28         ObjectMapper json = new ObjectMapper();
29         User user = json.readValue(sb.toString(), User.class);
30         return user;
31     }
32 
33 }

Second, write a servlet

 1 package com.servlet;
 2 
 3 import java.io.IOException;
 4 
 5 import javax.servlet.ServletException;
 6 import javax.servlet.http.HttpServlet;
 7 import javax.servlet.http.HttpServletRequest;
 8 import javax.servlet.http.HttpServletResponse;
 9 
10 import com.entity.User;
11 import com.fasterxml.jackson.databind.ObjectMapper;
12 import com.util.JsonReader;
13 
14 public class AjaxServlet2 extends HttpServlet {
15 
16     protected void doGet(HttpServletRequest request, HttpServletResponse response)
17             throws ServletException, IOException {
18 
19         // response.setContentType("text/html;charset=UTF-8");
20 
21         response.setContentType("application/json;charset=UTF-8");
22 
23         User user = JsonReader.receivePost(request);
24 
25         System.out.println(user);
26 
27         ObjectMapper mapper = new ObjectMapper();
28 
29         // take java Object to json Character string
30         String json = mapper.writeValueAsString(user);
31 
32         System.out.println(json);
33         response.getWriter().print(json);
34 
35     }
36 
37     protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
38         this.doGet(req, resp);
39     }
40 }

We have noticed that there is an ObjectMapper class. ObjectMapper is the core of JSON operations. All JSON operations of Jackson are implemented in ObjectMapper. It's in jackson-databind-2.0.0-jar. Here we introduce the methods commonly used under ObjectMapper class. The method of public < T > t readvalue (jsonparser JP, class < T > ValueType) can convert JSON strings into java objects. public String writeValueAsString(Object value) this method can convert java objects into JSON strings. First, introduce the two methods used. Look at the source code for others.

(6) web.xml file configuration Servlet

Similarly, it has been configured. Not much here.

(7) run the program

   

6. summary

(1) use jQuery to make the code more concise and easy to understand (jQuery is lightweight).

(2) jQuery encapsulates all Ajax operations into a function $. ajax(), which enables developers to concentrate on business logic when dealing with Ajax without concern for complex browser compatibility and the creation and use of XMLHttpRequest objects. JQuery has perfect Ajax operation.

(3) Jackson performance analysis:

1. Jackson relies on fewer jar packages and is easy to use.

2. Compared with other Java json frameworks such as Gson, Jackson can parse large json files faster.

3. Jackson runs with low memory consumption and good performance

Jackson has a flexible API that can be easily extended and customized.

Source code link of this blog: https://pan.baidu.com/s/1qn1GAdcKVIIWkiCitiXEGg  Extraction code: nuip

Keywords: Java JSON JQuery JSP

Added by Repgahroll on Tue, 29 Oct 2019 08:44:54 +0200