[Java] [Introduction to Spring Boot] Form submission using thymeleaf

6 minute read

Purpose

For those who have completed Spring Quickstart Guide, those who have started learning Spring Boot, and those who want to review,

I will share what I learned by actually working on the official guide Handling Form Submission.

Here is the completed form.

I will implement the process of displaying the value entered on the Form screen on the Result screen.

![Screenshot 2020-07-08 13.44.23.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/555244/4f501b36-035e-2014-29fa-(ba078394de6f.png)

![Screenshot 2020-07-08 13.44.30.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/555244/7170b180-6d05-3dc0-75e2-(4829a418324a.png)

The development environment, the review so far is as follows.

Development environment


OS: macOS Mojave version 10.14.6
Text Editor: Visual Studio Code (VSCode)
Java: 11.0.2

Review of Quickstart Guide is here Review of Building a RESTful Web Service Review of Consuming a RESTful Web Service Review of Accessing Data with JPA

Let’s start #1.SpringBoot project!

First, access spring initializr.

  1. Click the ADD DEPENDENCIES button and add Spring Web and Thymeleaf. 2.Artifact, Name changed to handling-form-submission.
  2. Change Java to 11.

Then click the GENERATE button to download the Zip file.

![Screenshot 2020-07-08 9.35.18.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/555244/dd1d177a-bb6a-135b-729f-(01cae1a1827c.png)

Extract the downloaded Zip file and you’re ready to go.

2.Let’s add code!

Open the previous folder with VS Code. We recommend that you install the extension Java Extension Pack. It is said that you should install it.

![Screenshot 2020-06-30 10.08.25.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/555244/80331ebc-b6e3-af7b-181a-(3c8921288b00.png)

Let’s create GreetingController.java!

Create a GreetingController.java file in src/main/java/com/example/handlingformsubmission/.

Screenshot 2020-07-08 9.55.33.png

Add the code by referring to the formula.

GreetingController.java


package com.example.handlingformsubmission;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;

@Controller
public class GreetingController {

  @GetMapping("/greeting")
  public String greetingForm(Model model) {
    model.addAttribute("greeting", new Greeting());
    return "greeting";
  }

  @PostMapping("/greeting")
  public String greetingSubmit(@ModelAttribute Greeting greeting) {
    return "result";
  }

}

We will dig deeper into the added code.

@Controller

GreetingController.java


@Controller
public class GreetingController {
  // omitted
}

By annotating with @Controller, Spring Boot treats this class as a controller. Since it transits to View and creates HTML, you must specify View as the return value of the method described below.

Although it doesn’t appear this time, the annotation @@RestController` is also treated as a controller in the same way, but the return value of the method does not transit to View and the content of the response is used.

② greetingForm method

GreetingController.java


@GetMapping("/greeting")
public String greetingForm(Model model) {
  model.addAttribute("greeting", new Greeting());
  return "greeting";
}

1.@GetMapping By adding this annotation, the method given when the GET request is made at the URL described in () will be called. This time it is @GetMapping("/greeting"). Therefore, when there is a GET request at http://localhost8080/greeting, the greetingForm method is called.

2.model.addAttribute It receives the argument of Model class as the argument of the method. This is to set the data to be passed to the View side. Data is passed to the View side by using the addAttribute (first argument, second argument) method, You can set the data in the second argument and use that data on the View side with the name of the first argument.

This time, we are passing the instantiated Greeting object to the View with the name greeting. I will implement Greeting later.

3. Method return value View is specified as the return value of the method. This time we are returning greeting. This means that greeting.html is required. Implementation will be done later.

② greetingSubmit method

GreetingController.java


@PostMapping("/greeting")
public String greetingSubmit(@ModelAttribute Greeting greeting) {
  return "result";
}

1.@PostMapping By adding this annotation, the method added will be called when there is a POST request at the URL described in (). This time it is @PostMapping("/greeting"). Therefore, when there is a POST request at http://localhost8080/greeting, the greetingSubmit method is called.

2.@ModelAttribute This annotation in the method argument is for setting the value sent by POST to the specified class. This time, the value sent to the greeting variable is stored, and the value is set to each variable of the Greeting class.

3. Method return value View is specified as the return value of the method. This time we are returning result. That means result.html is required. Implementation will be done later.

Let’s create ##Greeting.java!

Create a Greeting.java file in src/main/java/com/example/handlingformsubmission/.

![Screenshot 2020-07-08 13.23.40.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/555244/44c14f06-935b-2e05-5279-(4d6d24b7ff83.png)

Add the code by referring to the formula.

Greeting.java


package com.example.handlingformsubmission;

public class Greeting {

  private long id;
  private String content;

  public long getId() {
    return id;
  }
  public void setId(long id) {
    this.id = id;
  }public String getContent() {
    return content;
  }
  public void setContent(String content) {
    this.content = content;
  }

}

We will dig deeper into the added code.

1. Variable declaration

Greeting.java


private long id;
private String content;

Two variables are declared, a long id and a string content. Since the access modifier is private, it can be accessed only from the same class.

**2. Definition of getter and setter methods **

Greeting.java


public long getId() {
  return id;
}
public void setId(long id) {
  this.id = id;
}

public String getContent() {
  return content;
}
public void setContent(String content) {
  this.content = content;
}

Prepare getter and setter methods to store and retrieve the values sent by form.

Let’s create ##greeting.html!

Create a greeting.html file in src/main/resources/templates/. This html file is for displaying the form screen.

![Screenshot 2020-07-08 13.52.37.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/555244/1b102753-32ad-ab96-5e36-(9118401308e4.png)

Add the code by referring to the formula.

greeting.html


<!DOCTYPE HTML>
<html xmlns:th="https://www.thymeleaf.org">
<head>
    <title>Getting Started: Handling Form Submission</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
    <h1>Form</h1>
    <form action="#" th:action="@{/greeting}" th:object="${greeting}" method="post">
      <p>Id: <input type="text" th:field="*{id}" /></p>
      <p>Message: <input type="text" th:field="*{content}" /></p>
      <p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
    </form>
</body>
</html>

We will dig deeper into the description of thymeleaf in the added code.

thymeleaf is a template engine that can be handled by springboot. Enter th:○○. [Thymeleaf tutorial] written in Japanese (https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf_ja.html#thymeleaf%E3%81%AE%E7%B4%B9%E4%BB% 8B) is also available!

th:action

Replaces the content of the action attribute of the form tag. The description method is th:action="@{}". Since method=”post”, greetingController’s greetingSubmit method is called when the Submit button is pressed.

th:object

The object is specified by th:object. This allows you to write variables like *{id} instead of greeting.id to refer to variables in the object.

th:field

Enter th:field="*{variable name}" to display the variables in the object specified by th:object. This time, since there are id and content in the Greeting class, it becomes th:field="*{id}" and th:field="*{content}". In addition, the variable name described in th:field="*{variable name}" becomes the id and name attributes of input.

Let’s create ##result.html!

Create a result.html file in src/main/resources/templates/. This html file is for displaying the result sent from the form screen.

Screenshot 2020-07-08 14.57.32.png

Add the code by referring to the formula.

result.html


<!DOCTYPE HTML>
<html xmlns:th="https://www.thymeleaf.org">
<head>
    <title>Getting Started: Handling Form Submission</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>Result</h1>
    <p th:text="'id:'+ ${greeting.id}" />
    <p th:text="'content:'+ ${greeting.content}" />
    <a href="/greeting">Submit another message</a>
</body>
</html>

We will dig deeper into the description of thymeleaf in the added code.

th:text

Variables can be displayed as text by setting th:text="{variable name}". When displaying mixed character strings, you can enclose the character string with '' and connect with + to combine and display the character string and variable.

This time, since the id and content of the Greeting class sent in the form are displayed, It becomes th:text="'id:'+ ${greeting.id}", th:text="'content:'+ ${greeting.content}".

3.Let’s run!

Now that the application is ready to run, let’s check it.

Enter the following command in the terminal and press Enter.

terminal


$ ./mvnw spring-boot:run

Then, when you access http://localhost:8080/greeting, the following form screen should be displayed. (Greeting.html is displayed)

![Screenshot 2020-07-08 15.23.43.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/555244/cf93a2f5-1add-fae6-aaf2-(0e412c5db479.png)

Enter any value in Id and Message and click the Submit button. Then you should see the Result screen. (Result.html is displayed)

![Screenshot 2020-07-08 15.25.36.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/555244/4d0bcc95-31de-4478-aac0-(ed5a383d0c41.png)

done! Thank you for your hard work.

Reference site

Use @ModelAttribute How to use Thymeleaf Notes on how to use Thymeleaf with Spring Boot