我正在使用Sping Boot 和Thymeleaf创建一个“猜那个口袋妖怪”游戏。它非常简单。显示一个口袋妖怪的图像和一个接受用户输入的文本框。我该如何检查文本框的值与口袋妖怪的名称?
口袋妖怪类有字符串名称和字符串图像(用于图像url)
用于“displayPokemon.html”文件的代码
@GetMapping("/play")
public String play(Model model) throws JsonProcessingException {
Pokemon pokemon = p.getPokemon();
model.addAttribute("pokemon", pokemon);
return "displayPokemon";
}
用于显示口袋妖怪和文本字段的.html文件
<!DOCTYPE HTML>
<html xmlns:th="https://www.thymeleaf.org">
<head>
<title>Guess that Pokemon v1.0</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<img th:src="${pokemon.image}"/>
<h1>Who's That Pokemon?!</h1>
<form action="#" th:action="@{/play}" th:object="${pokemon}" method="post">
<p>Guess: <input type="text" th:field="*{name}" id="name" placeholder="Name" /></p>
<p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>
</body>
</html>
这是当前的@PostMapping。它显示来自文本字段的输入,但仅此而已。
@PostMapping("/play")
public String checkPokemonSubmit(@ModelAttribute Pokemon pokemon, Model model) {
model.addAttribute("pokemon", pokemon);
return "simpleResult";
}
简单结果. html页面
<!DOCTYPE HTML>
<html xmlns:th="https://www.thymeleaf.org">
<head>
<title>Guess that Pokemon - Result</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>Result</h1>
<p th:text="'Name: ' + ${pokemon.name}" />
<a href="/play">Guess Another Pokemon</a>
</body>
</html>
目前,文本字段是在点击/play端点时预先填充口袋妖怪的名称。我希望该字段为空,然后根据显示的图像检查字段中的输入pokemon.name。希望这是有意义的。如果需要任何其他信息,我很乐意为你们抓住它。
1条答案
按热度按时间t1qtbnec1#
我建议创建一个专用对象来存储用户的答案。
首先将您的
@GetMapping
更新为如下所示:这样可以确保Thymeleaf有一个“空”的
AnswerFormData
示例与HTML中的表单绑定。对于
AnswerFormData
:按如下方式更新模板:
最后,像这样更新
@PostMapping
:另请参见Form handling with Thymeleaf