試圖將表單提交時的變量傳遞給結果頁面,但每次都返回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將是一個字符串變量...