[JAVA] A simple example of an MVC model

Basically, it follows the ** Clearly understandable introduction to Servlet & jsp Chapter 7 BMI calculation program **.

What is MVC model?

element role File
Model Performs the main processing of the application and data storage General class
View Display the screen to the user JSP file
Controller Receives a request from the user, asks the model to perform the process, and asks the view to display the result. Servlet class

javaBeams One of the areas where instances can be stored. There are the following rules.

  1. Can be serialized
  2. The class is public and belongs to the package
  3. Has a public, no-argument constructor
  4. The field is encapsulated
  5. Have getters / setters that follow the naming convention

Sample program

I will put a commentary for each code at any time.

Model Performs the main processing of the application and data storage Saved in model package.

Health.java


package model;

import java.io.Serializable;

public class Health implements Serializable {
  private double height, weight, bmi;
  private String bodyType;

  public double getHeight() {
    return height;
  }

  public void setHeight(Double height) {
    this.height = height;
  }

  public double getWeight() {
    return weight;
  }

  public void setWeight(Double weight) {
    this.weight = weight;
  }

  public void setBmi(Double bmi) {
    this.bmi = bmi;
  }

  public double getBmi() {
    return this.bmi;
  }

  public void setBodyType(String bodyType) {
    this.bodyType = bodyType;
  }

  public String getBodyType() {
    return this.bodyType;
  }
}

This code is the so-called JavaBeans.

HealthCheckLogic.java


package model;

public class HealthCheckLogic {
  public void execute(Health health) {
    //Calculate and set BMI
    double weight = health.getWeight();
    double height = health.getHeight();
    double bmi = weight / (height / 100.0 * height / 100.0);
    health.setBmi(bmi);

    //Set by judging the physique from the BMI index
    String bodyType;
    if (bmi < 18.5) {
      bodyType = "Skinny type";
    } else if (bmi < 25) {
      bodyType = "usually";
    } else {
      bodyType = "obesity";
    }
    health.setBodyType(bodyType);
  }
}

Nothing to write in particular.

Controller It receives a request from the user, asks the model to perform the process, and asks the view to display the result. Saved in Servlet package.

HealthCheck.java


package servlet;

import java.io.IOException;

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

import model.Health;
import model.HealthCheckLogic;

@WebServlet("/HealthCheck")
public class HealthCheck extends HttpServlet {
  private static final long serialVersionUID = 1L;

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

    //forward
    RequestDispatcher dispatcher =
        request.getRequestDispatcher
            ("/WEB-INF/jsp/healthCheck.jsp");
    dispatcher.forward(request, response);
  }

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

    //Get request parameters
    String weight = request.getParameter("weight"); //height
    String height = request.getParameter("height"); //body weight

    //Set input value to property
    Health health = new Health();
    health.setHeight(Double.parseDouble(height));
    health.setWeight(Double.parseDouble(weight));
    //Perform a health check and set the results
    HealthCheckLogic healthCheckLogic = new HealthCheckLogic();
    healthCheckLogic.execute(health);

    //Save to request scope
    request.setAttribute("health", health);

    //forward
    RequestDispatcher dispatcher =
        request.getRequestDispatcher
            ("/WEB-INF/jsp/healthCheckResult.jsp");
    dispatcher.forward(request, response);
  }
}

URL pattern

Described in @WebServlet ("/ HealthCheck ").

serialVersionUID private static final long serialVersionUID = 1L; feels like a kind of magic, but it's different. Required when serialized, that is, when importing java.io.Serializable. Used as version control for the Serializable class.

Request scope

The scope generated for each request. It becomes possible to share an instance between the forward destination and the forward source.

request.setAttribute("Attribute name",instance)

Specify the management name of the instance to be saved in the scope in ** attribute name **. Specify the instance to be saved in ** instance **

When acquiring an instance from the request scope, describe as follows. This time, healthCheckResult.jsp is used for this process.

Type name of the instance to get= (Type of instance to get)request.getAttribute("Attribute name")

Note that a cast is required

forward

By using forward, it is possible to move the processing to another Servlet class or JSP file.

RequestDispatcher dispatcher =
request.getRequestDispatcher
    ("Forward destination");
dispatcher.forward(request, response);

How to specify the forward destination JSP file → / Path from WebContent Servlet class → / URL pattern

View Display the screen to the user. Here, save in / WebContent / Web-INF / jsp.

healthCheck.jsp


<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Refreshing health check</title>
</head>
<body>
<h1>Refreshing health check</h1>
<form action="/example/HealthCheck" method="post">
height:<input type="text" name="height">(cm)<br>
body weight:<input type="text" name="weight">(kg)<br>
<input type="submit" value="Diagnosis">
</form>
</body>
</html>

Line 10 `<form action =" / example / HealthCheck "method =" post "> ʻThe action attribute is specified as follows. In the case of Servlet class → / application name / URL pattern For JSP file → / Application name / Path from WebContent

healthCheckResult.jsp


<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ page import="model.Health" %>
<%
//Get Health stored in request scope
Health health = (Health) request.getAttribute("health");
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Refreshing health check</title>
</head>
<body>
<h1>Refreshing health check results</h1>
<p>
height:<%= health.getHeight() %><br>
body weight:<%= health.getWeight() %><br>
BMI:<%= health.getBmi() %><br>
Physique:<%= health.getBodyType() %>
</p>
<a href="/example/HealthCheck">Return</a>
</body>
</html>

The second line, <% @ page import =" model.Health "%>, calls Health.class in the model package. This code may be a great way to understand how to use javaBeans.

Finally

Please refer to ** Introduction to Servlet & JSP that is refreshing ** (written by Daigo Kunimoto). The copyright of the source code of this article belongs to Flarelink Co., Ltd. I am using it according to Creative Commons BY-SA 4.0.

Recommended Posts

A simple example of an MVC model
A simple example of a Servlet that displays Japanese
[Note] MVC model simple summary
MVC model
An example of a FactoryBot [KeyError: Factory not registered: "user"] error
[MVC model] A memo that a beginner learned MVC
A simple sample of ArBiMap (two-way map)
Stuck in an enum in front of a blacksmith
A collection of simple questions for Java beginners
Create a Service with an empty model Liferay 7.0 / DXP
[Meaning of model: of form_with]
Example of using vue.config.js
What is MVC model?
I made a server side of an online card game ⑤
I made a server side of an online card game ③
I made a server side of an online card game ⑥
I want to make a specific model of ActiveRecord ReadOnly
A record of how a machine shop makes an in-house system
I made a server side of an online card game ④
I made a server side of an online card game ②
Let's get an internal representation of a floating point number
JSP-About the MVC model of Servlet, redirect forward, and scope
I made a simple MVC sample system using Spring Boot
Existing records disappear when building a model of has_one (rails)