【发布时间】:2016-10-31 03:09:25
【问题描述】:
我刚刚开始发现 Spring MVC,并被这个简单的项目所困扰。在模板 index1.html 中有一个播放器对象 (th:object="${player}") 和字段值 (th:field="{playerId}"), (th:field="{ playerName}") 无法解析。模板 index2.html 中的情况与 (${player.playerId}) 和 (${player.playerName}) 相同。您能建议这可能是什么原因吗?
PlayerController.java
@Controller
public class PlayerController {
Logger log = LoggerFactory.getLogger(this.getClass());
@RequestMapping(value = "/create", method = RequestMethod.GET)
public String showForm(Model model) {
model.addAttribute("player", new Player());
return "create";
}
@RequestMapping(value = "/create", method = RequestMethod.POST)
public String processForm(@ModelAttribute Player player, Model model) {
model.addAttribute("player", player);
String info = String.format("Player Submission: playerId = %d, playerName = %s",
player.getPlayerId(), player.getPlayerName());
log.info(info);
return "view";
}
}
模型
public class Player{
private int playerId;
private String playerName;
.... getters and setters
}
观点
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8" >
<title>Form Submission</title>
</head>
<body>
<h1>Player</h1>
<form action = "#" th:action="@{/create}" th:object="${player}" method="post">
<p>Id: <input type="text" th:field="*{playerId}" /></p>
<p>Name: <input type="text" th:field="*{playerName}" /></p>
<p><input type="submit" value="Add" /></p>
</form>
</body>
</html>
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Player info</title>
</head>
<body>
<p th:text="'ID: ' + ${player.playerId}" />
<p th:text="'Name: ' + ${player.playerName}" />
</body>
</html>
【问题讨论】:
-
您的 html 文件在哪里?应该是 ito /resources/templates
-
@cralfaro 是的,html 文件位于 /resources/templates 中。我附上了上面的项目结构截图。
标签: spring spring-mvc thymeleaf