试图将表单提交时的变量传递给结果页面,但每次都返回null。无论我尝试了多少变化。无法找到Thymeleaf模板中的占位符null
所以我得到映射,后为login.html的:
@GetMapping("/login")
public String greetingForm(Model model) {
model.addAttribute("User2", new User());
return "login";
}
@PostMapping("/login")
public String greetingSubmit(@ModelAttribute User regUser) {
//userRepository.save(regUser);
//String teststr = regUser.getName();
//System.out.println(teststr);
return "result";
}
实际的login.html是这样的:
的User.java文件<!DOCTYPE HTML>
<html xmlns:th="http://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="@{/demo/login}" th:object="${User2}" method="post">
<p>Username: <input type="text" th:field="*{name}" /></p>
<p>Password: <input type="text" th:field="*{password}" /></p>
<p>Balance: <input type="text" th:field="*{balance}" /></p>
<p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>
</body>
</html>
部分:
@Entity // This tells Hibernate to make a table out of this class
public class User {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
private String name;
private String password;
private int balance;
public int getBalance() {
return balance;
}
public void setBalance(int balance) {
this.balance = balance;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
和result.html是:
<!DOCTYPE HTML>
<html xmlns:th="http://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="'username: ' + ${User.name}" />
<p th:text="'password: ' + ${regUser != null ? regUser.password : 'NOT FOUND'}" />
<p th:text="'balance: ' + ${model != null ? regUser.balance : 'NOT FOUND'}" />
<a href="/demo/login">Submit another user?</a>
</body>
</html>
该公司密切关注该行多次抛出一个空的错误:
<p th:text="'username: ' + ${User.name}" />
特别${User.name}
,看起来像
org.springframework.expression.spel.SpelEvaluationException: EL1007E: Property or field 'name' cannot be found on null
所以我用尽了一切我能想到的的,
${User2.name}
${User}
${User2}
${regUser.name}
${teststr}
${#User.name}
等....
这是很奇怪的,如果我取消System.out.println(regUser.getName());
这将打印用户的名字就好了,但不会传递变量。它是我的占位符还是不能作为th:text
传递,因为它是User
对象?请帮助我很困惑!
编辑:教程我遵循(https://spring.io/guides/gs/handling-form-submission/) 如果您复制教程它工作得很好,但它只是传递一个字符串。虽然User.name将是一个字符串变量...