Last time, I displayed HTML on the screen with Try to display hello world with spring + gradle. This time I want to move the screen dynamically, so I would like to display the entered characters on the screen. Since it is a memorandum for beginners, I would be grateful if you could point out any strange points!
It looks like this after completion ↓ When you press send
I will add it as it is to the code used in the previous article, but for those who are only looking at this article, I will post the entire code without abbreviation.
Add a place to display the characters entered in hello.html created last time and a field to enter.
hello.html
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<title>hello</title>
</head>
<body>
<h1>Hello World!!</h1>
//Add from here ↓
<h1 th:text="${text}"></h1> ---1
<form th:method="POST" th:action="changeText"> ---2
<input type="text" name="inputText" /> ---3
<input type="submit"> ---4
</form>
//Add up to here ↑
</body>
</html>
method
, th: action
specifies the URL.name
.th ~ has come out. This is how to write thymeleaf. Read as time leaf. It is a template engine such as HTML and is used as standard in Spring Boot. When displaying data processed by java on the screen, it is nice to be able to check it on the screen while developing because it is HTML.
You can use it by adding the following to build.gradle
and updating it.
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
If you continue to read this article from the previous article, you should have filled it in without adding it because you selected thymeleaf as a dependency when creating the project.
How do you write in thymeleaf? When it becomes, this article is very easy to read => Thymeleaf cheat sheet
This is also added to the HelloController created last time.
HelloController.java
package helloSpring.Controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class HelloController {
@RequestMapping(value = "/", method = RequestMethod.GET)
public String hello(Model model) {
model.addAttribute("text", "The characters entered here are displayed"); //Add --- -1
return "hello";
}
@RequestMapping(value = "/changeText", method = RequestMethod.POST) //Add --- 2
public String changeText(@RequestParam(name = "inputText") String text, Model model) {
model.addAttribute("text", text);
return "hello";
}
}
<h1 th: text =" $ {text} "> </ h1>
added in hello.html
.that's all. Next, I would like to connect to the DB and display the data. Next => Creating
Recommended Posts