[Introduction to Spring Boot] Submit a form using thymeleaf

Purpose

For those who have finished working on the Spring Quickstart Guide, those who have started learning Spring Boot, and those who want to review it.

We will share what we have learned by actually working on the official guide Handling Form Submission.

The completed form is here.

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

スクリーンショット 2020-07-08 13.44.23.png

スクリーンショット 2020-07-08 13.44.30.png

The development environment and the review so far are as follows.

Development environment


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

Click here for a review of the Quickstart Guide Click here for a review of Building a RESTful Web Service Click here for a review of Consuming a RESTful Web Service Click here for a review of Accessing Data with JPA

1. Start the Spring Boot project!

First, access spring initializr.

  1. Click the ADD DEPENDENCIES button to 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.

スクリーンショット 2020-07-08 9.35.18.png

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

2. Add code!

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

スクリーンショット 2020-06-30 10.08.25.png

Let's create GreetingController.java!

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

スクリーンショット 2020-07-08 9.55.33.png

Add the code 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 {
  //abridgement
}

SpringBoot treats this class as a controller by annotating it with @ Controller. Since HTML is created by transitioning to View, View must be specified in the return value of the method described later.

Although it will not appear this time, the annotation @ RestController will be treated as a controller as well, but the return value of the method will be the content of the response without transitioning to View.

② 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 there is a GET request with 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 data in the second argument and use that data on the View side with the name of the first argument.

This time, I'm passing the instantiated Greeting object to the View with the name greeting. Greeting will be implemented later.

** 3. Method return value ** View is specified as the return value of the method. This time we are returning greeting. That means you need greeting.html. 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 given when there is a POST request with the URL described in () will be called. 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 thevalue is set for each variable of theGreeting class.

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

Let's create Greeting.java!

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

スクリーンショット 2020-07-08 13.23.40.png

Add the code 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. Declaration of variables **

Greeting.java


private long id;
private String content;

Two variables are declared: long type id and String type content. Since the access modifier is private, it can only be accessed from within 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 value sent in 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.

スクリーンショット 2020-07-08 13.52.37.png

Add the code 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. Described as 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% There is also 8B)!

th:action

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

th:object

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

th:field

Write 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 will be th: field =" * {id} ", th: field =" * {content} ". In addition, the variable name described in th: field =" * {variable name} " is the id attribute and name attribute 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.

スクリーンショット 2020-07-08 14.57.32.png

Add the code 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 a mixture of character strings, you can combine the character strings and variables by enclosing the character strings with '' and concatenating them with +.

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

3. Let's run it!

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

Enter the following command in the terminal and press Enter.

Terminal


$ ./mvnw spring-boot:run

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

スクリーンショット 2020-07-08 15.23.43.png

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

スクリーンショット 2020-07-08 15.25.36.png

done! Thank you for your hard work.

Reference site

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

Recommended Posts

[Introduction to Spring Boot] Submit a form using thymeleaf
[Introduction to Spring Boot] Form validation check
Introduction to Spring Boot ① ~ DI ~
Introduction to Spring Boot ② ~ AOP ~
Introduction to Spring Boot Part 1
How to make a hinadan for a Spring Boot project using SPRING INITIALIZR
Spring Boot Form
Java beginner tried to make a simple web application using Spring Boot
Steps to create a simple camel app using Apache Camel Spring Boot starters
Create a Spring Boot application using IntelliJ IDEA
How to add a classpath in Spring Boot
An introduction to Spring Boot + in-memory data grid
Apply Twitter Bootstrap 4 to Spring Boot 2 using Webjars
[Introduction to Spring Boot] Authentication function with Spring Security
Introduction to Ratpack (9) --Thymeleaf
How to create an Excel form using a template file with Spring MVC
Create a portfolio app using Java and Spring Boot
How to write a unit test for Spring Boot 2
If you want to separate Spring Boot + Thymeleaf processing
A memorandum of addiction to Spring Boot2 x Doma2
[JUnit 5 compatible] Write a test using JUnit 5 with Spring boot 2.2, 2.3
[Spring Boot] How to create a project (for beginners)
Try Spring Boot from 0 to 100.
[Java] Thymeleaf Basic (Spring Boot)
Try using Spring Boot Security
Deploy Spring Boot applications to Heroku without using the Heroku CLI
Until INSERT and SELECT to Postgres with Spring boot and thymeleaf
I tried to get started with Swagger using Spring Boot
8 things to insert into DB using Spring Boot and JPA
I made a simple MVC sample system using Spring Boot
How to control transactions in Spring Boot without using @Transactional
Introduction to Spring Boot x OpenAPI ~ OpenAPI made with Generation gap pattern ~
Spring Boot Tutorial Using Spring Security Authentication
[Rails 6] How to create a dynamic form input screen using cocoon
How to set Spring Boot + PostgreSQL
Fitted in Spring Boot using a bean definition file named application.xml
Things to consider when running a specified job using Spring Batch
I made a simple search form with Spring Boot + GitHub Search API.
Sample code to unit test a Spring Boot controller with MockMvc
How to use ModelMapper (Spring boot)
Upgrade spring boot from 1.5 series to 2.0 series
A memo that touched Spring Boot
Thymeleaf usage notes in Spring Boot
How to display characters entered in Spring Boot on a browser and reference links [Introduction to Spring Boot / For beginners]
Introduction to Java development environment & Spring Boot application created with VS Code
How to sort a List using Comparator
What is a Spring Boot .original file?
Item 87: Consider using a custom serialized form
[Introduction to Java] How to write a Java program
Introduction to Ratpack (Extra Edition) --Using Sentry
Try using Spring Boot with VS Code
Story when moving from Spring Boot 1.5 to 2.1
Changes when migrating from Spring Boot 1.5 to Spring Boot 2.0
Changes when migrating from Spring Boot 2.0 to Spring Boot 2.2
[Introduction to JSP + Servlet] A little animation ♬
Implement CRUD with Spring Boot + Thymeleaf + MySQL
Asynchronous processing with Spring Boot using @Async
Implement paging function with Spring Boot + Thymeleaf
Spring Boot + Thymeleaf BootStrap installation method memo
How to split Spring Boot message file
Form class validation test with Spring Boot