Think about the combination of Servlet and Ajax

49

Speaking of Web applications in java, I only knew the MVC model (Servlet + JSP + Beans). I recently learned that there is a Servlet + Ajax combination, so I'll keep a record of it. It is characterized by being able to call Servlet from javascript.

Combination of Servlet + JSP + Beans

Since it is familiar, I will omit the explanation 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, javascript receives the response, so there is no need to update the screen each time.

Merit 1

For example, it is possible to access the DB indirectly from javascript through the servlet as follows. When handling a large amount of data, it is also possible to extract data from the DB to a small portion.

java9.jpg

Merit 2

Compared to JSP, the independence of the front and back is increased for the following reasons, so development is easier (in some cases). If you decide on the format of JSON, you can exchange it.

The caller is basically OK with html + jQuery   → page no longer needs beans or class declarations  ・ Exchange is JSON only  ・ No need to update the screen  ・ Multiple calls are also possible as shown in the figure below

java10.jpg

The requester (javascript)

You can choose synchronous and asynchronous communication, but be aware that it is not parallel processing.  For parallelism, refer to Using Javascript WebWorker.  As you can see, you can send the request JSON itself as the value of one element.

sample.js

function sampleAjax() {

  //リクエストJSON
  var request = {
    param1 : "param",
    param2 : 12345
  };

  //ajaxでservletにリクエストを送信
  $.ajax({
    type    : "GET",          //GET / POST
    url     : "http://localhost:8080/SampleWeb/urlServlet",  //送信先のServlet URL(適当に変えて下さい)
    data    : request,        //リクエストJSON
    async   : true,           //true:非同期(デフォルト), false:同期
    success : function(data) {
      //通信が成功した場合に受け取るメッセージ
      response1 = data["response1"];
      response2 = data["response2"];
    },
    error : function(XMLHttpRequest, textStatus, errorThrown) {
      alert("リクエスト時になんらかのエラーが発生しました:" + textStatus +":\
" + errorThrown);
    }
  });

}

Receiving a Request (Servlet)

DB calls are 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 {

        //パラメータ取得
        String param1 = req.getParameter("param1");
        String param2 = req.getParameter("param2");

        //処理(DB呼び出し等)
        String response1 = "";
        String response2 = "";

        //出力(レスポンスをmapに格納してJSON化)

        //JSONマップ
        Map<String, String> mapMsg = new HashMap<String, String>();

        //追加
        mapMsg.put("response1", response1);
        mapMsg.put("response2", response2);

        //マッパ(JSON <-> Map, List)
        ObjectMapper mapper = new ObjectMapper();

        //json文字列
        String jsonStr = mapper.writeValueAsString(mapMsg);  //list, map

        //ヘッダ設定
        res.setContentType("application/json;charset=UTF-8");   //JSON形式, UTF-8

        //pwオブジェクト
        PrintWriter pw = res.getWriter();

        //出力
        pw.print(jsonStr);

        //クローズ
        pw.close();

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

    }

}

ObjectMapper Maven

The following is added to the 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>
Share:
49
キーちゃん
Author by

キーちゃん

フリーランスエンジニアです。 宜しくお願い致します。

Updated on February 21, 2020