【问题标题】:List with springboot and thymeleaf使用 springboot 和 thymeleaf 列出
【发布时间】:2018-10-10 23:02:10
【问题描述】:

我正在尝试获取从 html 表单发送到服务器的对象列表作为我列表的参数,然后我将遍历这些条目,然后通过 springboot th:each 返回它们。但它似乎根本不起作用。加载时会出现表单,但是当我在其中输入值时,它会返回一个错误页面,但是 URL 会变成:

http://localhost:8080/@%7B/%7D?%24%7Bcontent%7D=hello

eclipse 中的这个输出说:

Expression "content" is not valid: only variable expressions ${...} or selection expressions *{...} are allowed in Spring field bindings 

注意:这里的内容是我表单中的值属性。 我的控制器如下所示:

@Controller
public HelloList() {
    this.addUs = new ArrayList <>();
}

@RequestMapping("/")
public String getlist(@RequestParam (required = false) String content, Model model) {
    if (content != null && !content.trim().isEmpty()) {
        this.addUs.add(content);
    }

    model.addAttribute("list",addUs);
    return "index";
}

index.html 看起来像这样

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Insert title here</title>
</head>
<body>
<div>
    <ul>
        <li th:each="amHere: ${addUs}">
            <span th:text="${amHere}">hello! world</span>
        </li>
    </ul>

    <form action="@{/}" method="GET">
        <input type="text" name="content"/>
        <input type="submit" value="Submit"/>
    </form>
</div>
</body>
</html>

这可能是重复的,但我遇到的大多数解决方案似乎都没有帮助。因此,任何帮助都会受到赞赏。提前谢谢你。

【问题讨论】:

  • 更新:在stackoverflow“运行代码sn-p”选项卡中,我可以看到运行html文件后,它显示默认子元素“hello!world”。但在我的电脑上,这没有发生。我只看到表格。所以我不确定发生了什么。
  • 你可能想要method="post"

标签: java arrays maven spring-boot thymeleaf


【解决方案1】:

原来我错过了构造函数中列表的初始化。我通过在构造函数中首先向它添加一个值来初始化列表。

this.addUs.add("Hello World");

因为@RequestMapping 在我的案例 index.html 中映射到主路径,所以任何请求都会自动发送到那里。 working example

【讨论】:

    【解决方案2】:

    action = "@{/}" 应该是 th:action="@{/}"。这就是您看到奇怪 url 的原因(因为它是 url 编码 @{/})。 Thymeleaf 只计算以th: 开头的表达式。

    我不确定其他错误。您粘贴的 html 似乎与您收到的错误不匹配。

    如果你对http://localhost:8080/@%7B/%7D?%24%7Bcontent%7D=hello 进行urldecode,你会得到http://localhost:8080/@{/}?${content}=hello,这与你的表单不匹配。

    【讨论】:

    • 是的,你是对的,我在表单中输入了一个错字,从表单操作方法中省略了“th”。我纠正了这一点,但现在我仍然无法访问列表模型,即使我可以看到任何时候我按下从 from 发送我的值,url 都会显示参数及其值。
    • "localhost:8080/?content=Hello" 错误输出为Could not parse as each: "items ${addUs}"。似乎当我有 th:each="items : ${addUs}" 和 th:text="${items}" 时,列表根本不会出现。但是当我把它们取下来时,chrome会显示默认值“hello!world”。
    猜你喜欢
    • 2021-04-05
    • 2018-11-06
    • 1970-01-01
    • 2021-11-05
    • 1970-01-01
    • 2019-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多