我有一个小问题。当我有一个包含一些字段的对象时,很容易通过表单传递这些字段:
Controller :
@RequestMapping("/")
public String hello(Model model) {
model.addAttribute("test", Test);
return "index";
}
html:
<form th:action="@{/process}" method="post" th:object="${test}">
<input type="text" th:field="*{value}"/>
<input type="submit" />
</form>
但是如果我不想有一个对象并且只传递字符串怎么办?类似的东西:
Controller :
@RequestMapping("/")
public String hello(Model model) {
model.addAttribute("test", "test string");
return "index";
}
html:
<form th:action="@{/process}" method="post">
<input type="text" th:field="${test}"/>
<input type="submit" />
</form>
不起作用。
感谢帮助!
对于评论中的下一个问题:
索引.html:
<form th:action="@{/process}" method="post">
<textarea th:text="${sourceText}"/>
<input type="submit" />
ggg.html:
<textarea th:text="${sourceText}"/>
Controller :
@RequestMapping("/")
public String hello(Model model) {
model.addAttribute("sourceText", "asdas");
return "index";
}
@RequestMapping("/process")
public String process(Model model, @ModelAttribute(value = "sourceText") String sourceText) {
return "ggg";
}
最佳答案
th:field 仅在您声明像 th:object 这样的对象时使用。
<form th:action="@{/process}" method="post">
<input type="text" th:value="${sourceText}" name="sourceText"/>
<input type="submit" />
</form>
Spring 通过“name”属性匹配值。只需在 Controller 中使用@RequestParam 即可捕获它
@RequestMapping("/process")
public String process(Model model, @RequestParam String sourceText) {
return "ggg";
}
关于spring - 如何仅以 thymeleaf 形式传递字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41467779/