Spring Boot+Thymeleaf猜宝可梦游戏:验证输入与宝可梦名称匹配
解决猜宝可梦游戏的两个问题
问题1:文本框预填宝可梦名称
当前表单直接绑定了pokemon对象的name属性,而该对象本身携带正确的宝可梦名称,导致Thymeleaf自动填充输入框。解决核心是将表单输入与正确宝可梦信息分离:
修改GetMapping代码
把正确的宝可梦存入Session用于后续验证,同时给表单绑定空的输入属性:
@GetMapping("/play") public String play(Model model, HttpSession session) throws JsonProcessingException { Pokemon pokemon = p.getPokemon(); // 存储正确宝可梦到Session session.setAttribute("currentPokemon", pokemon); // 绑定空输入字段,避免预填 model.addAttribute("userGuess", ""); return "displayPokemon"; }
修改displayPokemon.html
调整表单绑定目标为userGuess,不再关联pokemon的name属性:
<!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="${session.currentPokemon.image}"/> <h1>Who's That Pokemon?!</h1> <form th:action="@{/play}" method="post"> <p>Guess: <input type="text" th:value="${userGuess}" name="userGuess" id="name" placeholder="Name" /></p> <p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p> </form> </body> </html>
问题2:验证用户输入是否正确
通过Session取出正确宝可梦名称,与用户输入对比后返回验证结果:
修改PostMapping代码
@PostMapping("/play") public String checkPokemonSubmit(@RequestParam String userGuess, HttpSession session, Model model) { Pokemon currentPokemon = (Pokemon) session.getAttribute("currentPokemon"); // 忽略大小写和前后空格,提升体验 boolean isCorrect = currentPokemon.getName().equalsIgnoreCase(userGuess.trim()); model.addAttribute("userGuess", userGuess); model.addAttribute("correctName", currentPokemon.getName()); model.addAttribute("isCorrect", isCorrect); return "simpleResult"; }
修改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:if="${isCorrect}" style="color: green;"> 恭喜你猜对了!正确名称:<span th:text="${correctName}"></span> </p> <p th:if="${!isCorrect}" style="color: red;"> 猜错啦!正确名称是:<span th:text="${correctName}"></span> </p> <p>你的猜测:<span th:text="${userGuess}"></span></p> <a href="/play">继续猜下一只</a> </body> </html>
额外说明
- 用Session存储当前宝可梦,避免前端篡改验证逻辑,保证验证安全性。
- 大小写忽略和空格处理,能减少用户输入失误带来的挫败感。
内容的提问来源于stack exchange,提问作者lostInCodeKeys
相关产品推荐
相关产品推荐

