我有一个使用 Thymeleaf 模板引擎的 Spring Boot 应用程序,该应用程序假设提交一个表单,然后继续到下一页,从上一个提交函数中获取 ID。 但是当我将值添加到下一个 View 的隐藏字段时,它不接受它。 我想知道我做错了什么。
Controller
@Controller
public class FormController {
@Autowired
UserCategoryServiceImpl userCategoryService;
@GetMapping("/form3")
public String getForm3(Model model){
model.addAttribute("form3", new UserCategory());
return "form3";
}
@PostMapping("/form3")
public String postAndGetForm4(@ModelAttribute UserCategory userCategory, Model model, BindingResult bindingResult){
userCategoryService.saveCategory(userCategory);
model.addAttribute("catID", userCategory.getId());
if(bindingResult.hasErrors()){
return "form3";
}
return "form4";
}
}
Views
1: Form3
<form method="post" th:object="${form3}">
<label>Name</label><input th:field="*{name}" type="text" name="userName">
<button type="submit">Submit</button>
</form>
2: Form4
<form>
<input type="hidden" value="*{catID}">
</form>
Model
@Entity
@Table(name = "user_category")
public class UserCategory {
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "id", insertable = false, updatable = false, nullable = false)
private Long id;
@Column(name = "name")
private String name;
//Getter and Setters
第一个表单(Form3)提交成功,但是catID的值无法显示在下一个表单(Form4)的隐藏字段
最佳答案
这个问题已经很老了,也许你已经解决了它,但没有在 Stack Overflow 上发布你的解决方案。
发布的代码不完整,但在我看来,在 Form4 中,您应该直接使用模型属性而不是属性的字段。
在 Form3 中,*{name}
是模型属性 ${form3}
的一个字段这样语法就可以工作了。但在 Form4 中,catID
是一个完全独立的模型属性,因此在 Thymeleaf 模板中,您应该使用美元符号而不是星号,如 th:value="${catID}"
中所示。 .
顺便说一句,我注意到您的输入标签没有使用结束斜杠。这可能可行,但这是不好的做法,因为它是格式错误的 XML。
最后,对于最后一个表单,如果您想直接使用该值,则需要指定 input
标签的name
手动属性:<input type="hidden" name="catID" th:value="${catID}"/>
注意:使用th:field=${catId}
不起作用,因为th:field
需要使用th:object
关于form
标签。
关于java - HTML 隐藏字段在 Spring Boot Thymeleaf 中未接收模型属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43768077/