spring - 如何仅以 thymeleaf 形式传递字符串?

标签 spring thymeleaf

我有一个小问题。当我有一个包含一些字段的对象时,很容易通过表单传递这些字段:

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/

相关文章:

java - Spring 从 REQUIRED_NEW 方法调用 REQUIRED 方法

java - org.springframework.beans.NotWritablePropertyException

java - TemplateEngine 未在模板文件夹中查找文件

spring-mvc - 使用 Spring Boot 和 Thymeleaf 将复选框映射到列表

页面上的 Spring MVC + Thymeleaf div 未生成

spring - 对于 Thymeleaf 中的每个运算符

java - 开始使用 OSGI 的最佳方式是什么?

java - 是否可以让我的自定义验证注释在持久化时被忽略?

java - 使用固定值映射 JPA 中的枚举?

java - 如何将隐藏值从 Thymeleaf 模板传递到 Controller (Spring Boot)?