Think about the combination of Servlet and Ajax

Speaking of Web applications in java, I knew only the MVC model (Servlet + JSP + Beans). I recently learned that there is a combination of ** Servlet + Ajax **, so record it. The feature is that ** Servlet can be called from javascript **.

Combination of Servlet + JSP + Beans

Since it is familiar, the explanation is omitted here.

java7.jpg

Combination of Servlet + Ajax

java8.jpg

Looking only at the above figure, it seems that there is not much difference, but in the case of Servlet + Ajax, ** response is received by javascript **, so there is no need to update the screen one by one.

Merit 1

For example, you can access the DB indirectly from javascript through servlet as shown below **. When dealing with a large amount of data, it is also possible to retrieve the data from the DB in small quantities.

java9.jpg

Merit 2

Compared to JSP, for the following reasons, ** the independence of the front and back is increased **, which makes development easier (in some cases). Exchange is possible if the JSON format is decided.

・ ** The caller is basically OK with html + jQuery ** → ** No need to declare beans or classes on the page ** ・ ** Exchange is JSON only ** ・ ** No need to update the screen ** ・ ** Multiple calls are possible as shown in the figure below **

java10.jpg

Requester (javascript)

You can select synchronous / asynchronous communication, but note that it is not parallel processing. For parallel processing, see I tried using javascript WebWorker. It seems that you may send the request JSON itself as the value of one element like Reference.

``sample.js`



function sampleAjax() {

  //Request JSON
  var request = {
    param1 : "param",
    param2 : 12345
  };

  //Send request to servlet with ajax
  $.ajax({
    type    : "GET",          //GET / POST
    url     : "http://localhost:8080/SampleWeb/urlServlet",  //Destination Servlet URL (change as appropriate)
    data    : request,        //Request JSON
    async   : true,           //true:asynchronous(Default), false:Sync
    success : function(data) {
      //Message received when communication is successful
      response1 = data["response1"];
      response2 = data["response2"];
    },
    error : function(XMLHttpRequest, textStatus, errorThrown) {
      alert("Some error occurred during the request:" + textStatus +":\n" + errorThrown);
    }
  });

}

Receive request (Servlet)

DB call etc. is also possible.

``sampleServlet.java`


package servlet;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(urlPatterns={"/urlServlet"})
public class SvDbViewRange extends HttpServlet {

    private static final long serialVersionUID = 1L;

    @Override
    public void doGet (HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {

    try {

        //Parameter acquisition
        String param1 = req.getParameter("param1");
        String param2 = req.getParameter("param2");

        //Processing (DB call, etc.)
        String response1 = "";
        String response2 = "";

        //output(Store the response in map and convert it to JSON)

        //JSON map
        Map<String, String> mapMsg = new HashMap<String, String>();

        //add to
        mapMsg.put("response1", response1);
        mapMsg.put("response2", response2);

        //Mapper(JSON <-> Map, List)
        ObjectMapper mapper = new ObjectMapper();

        //json string
        String jsonStr = mapper.writeValueAsString(mapMsg);  //list, map

        //Header setting
        res.setContentType("application/json;charset=UTF-8");   //JSON format, UTF-8

        //pw object
        PrintWriter pw = res.getWriter();

        //output
        pw.print(jsonStr);

        //Close
        pw.close();

    } catch(Exception e) {
        e.printStackTrace();
    }

    }

}

ObjectMapper Maven

Add the following to pom.xml.

``pom.xml`



  <dependencies>
    <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
    <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.5</version>
    </dependency>
  </dependencies>

Recommended Posts

Think about the combination of Servlet and Ajax
Think about the 7 rules of Optional
About the operation of next () and nextLine ()
About the mechanism of the Web and HTTP
About next () and nextLine () of the Scanner class
[Grails] About the setting area and the setting items of application.yml
[Technical memo] About the advantages and disadvantages of Ruby
About the description of Docker-compose.yml
Combination of search and each_with_index
About the same and equivalent
[Ruby] Questions and verification about the number of method arguments
[Ruby] About the difference between 2 dots and 3 dots of range object.
Think about the differences between functions and methods (in Java)
JSP-About the MVC model of Servlet, redirect forward, and scope
[Java] I thought about the merits and uses of "interface"
About the behavior of ruby Hash # ==
About the basics of Android development
About fastqc of Biocontainers and Java
About the equals () and hashcode () methods
This and that of the JDK
About the role of the initialize method
About removeAll and retainAll of ArrayList
About image upload of jsp (servlet)
Summary about the introduction of Device
About the log level of java.util.logging.Logger
About the version of Docker's Node.js image
What is testing? ・ About the importance of testing
About the classification and concept of Immutable / Mutable / Const / Variable of Java and Kotlin.
Folding and unfolding the contents of the Recyclerview
[Ruby basics] About the role of true and break in the while statement
(Determine in 1 minute) About the proper use of empty ?, blank? And present?
About the initial display of Spring Framework
About the error message Invalid redeclaration of'***'
About the treatment of BigDecimal (with reflection)
About the difference between irb and pry
About the number of threads of Completable Future
Check the version of the JDK installed and the version of the JDK enabled
[Rails / ActiveRecord] About the difference between create and create!
About the official start guide of Spring Framework
About the description order of Java system properties
About the idea of anonymous classes in Java
Compare the speed of the for statement and the extended for statement.
The story of introducing Ajax communication to ruby
[Java] The confusing part of String and StringBuilder
I compared the characteristics of Java and .NET
Learn the rudimentary mechanism and usage of Gradle 4.4
About call timing and arguments of addToBackStack method
What are the advantages of DI and Thymeleaf?
A note about the Rails and Vue process
A memo about the types of Java O/R mappers and how to select them
About the method
About the package
ArrayList and the role of the interface seen from List
[Ruby] I thought about the difference between each_with_index and each.with_index
[Rails] I learned about the difference between resources and resources
I tried using the Server Push function of Servlet 4.0
Please note the division (division) of java kotlin Int and Int
[For beginners] DI ~ The basics of DI and DI in Spring ~
The comparison of enums is ==, and equals is good [Java]
About the usefulness of monads from an object-oriented perspective
Talking about the merits of database bind variables ((1) Introduction)