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.
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
First, access spring initializr.
Spring Web
and Thymeleaf
.
2.Artifact, Name changed to handling-form-submission
.Then click the GENERATE
button to download the Zip file.
Extract the downloaded Zip file and you're ready to go.
Open the previous folder with VS Code. We recommend installing the Java Extension Pack for extensions. It is said that you should install it.
Create a GreetingController.java file in src / main / java / com / example / handlingformsubmission /
.
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.
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.
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 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 you need result.html. Implementation will be done later.
Create a Greeting.java file in src / main / java / com / example / handlingformsubmission /
.
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.
Create a greeting.html file in src / main / resources / templates /
.
This html file is for displaying the form screen.
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.
Create a result.html file in src / main / resources / templates /
.
This html file is for displaying the result sent from the form screen.
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} "
.
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)
Enter any value for Id and Message and click the Submit button. You should see the Result screen. (Result.html is displayed)
done! Thank you for your hard work.
** Use @ModelAttribute ** ** How to use Thymeleaf ** ** Memo on how to use Thymeleaf with Spring Boot **
Recommended Posts