Java 使用springboot和thymeleaf列出
我试图获取从html表单发送到服务器的对象列表作为列表的参数,然后我将循环遍历这些条目,然后通过springbootJava 使用springboot和thymeleaf列出,java,arrays,maven,spring-boot,thymeleaf,Java,Arrays,Maven,Spring Boot,Thymeleaf,我试图获取从html表单发送到服务器的对象列表作为列表的参数,然后我将循环遍历这些条目,然后通过springbootth:each返回它们。但它似乎根本不起作用。加载时,表单会出现,但当我在其中输入值时,它会返回一个错误页面,但URL会变为: http://localhost:8080/@%7B/%7D?%24%7Bcontent%7D=hello eclipse中的输出表示: Expression "content" is not valid: only variable expressio
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
注意:这里的内容是我表单中的value属性。
我的控制器如下所示:
@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";
}
@控制器
公共希腊主义者(){
this.addUs=newarraylist();
}
@请求映射(“/”)
公共字符串getlist(@RequestParam(required=false)字符串内容,模型){
if(content!=null&&!content.trim().isEmpty()){
this.addUs.add(内容);
}
model.addAttribute(“列表”,addUs);
返回“索引”;
}
html如下所示
在此处插入标题
-
你好世界
action=“@{/}”
应该是th:action=“@{/}”
。这就是您看到奇怪url的原因(因为它是url编码@{/}
)。thymileaf只计算以th:
开头的表达式
我不确定另一个错误。看起来您粘贴的html与您得到的错误不匹配
如果您解码
http://localhost:8080/@%7B/%7D?%24%7B内容%7D=hello
,您会得到http://localhost:8080/@{/}?${content}=hello
,这与您的表单不符。结果表明,我缺少构造函数中列表的初始化。我通过在构造函数中首先添加一个值来初始化列表,如下所示
this.addUs.add("Hello World");
因为@RequestMapping
被映射到my case index.html中的主路径,所以任何请求都会自动发送到那里。
Update:在stackoverflow的“运行代码片段”选项卡中,我可以看到在运行html文件后,它显示默认的子元素“hello!world”。但在我的电脑上,这并没有发生。我只看到表格。所以我不知道发生了什么。你可能想要
method=“post”
是的,你是对的,我在表单中输入了一个拼写错误,表单操作方法中的“th”被遗漏了。我纠正了这一点,但现在仍然无法访问列表模型,即使我可以看到,每当我按下从发送值时,url都会显示的参数及其值。“”错误输出是无法解析为each:“items${addUs}”
。似乎当我有th:each=“items:${addUs}”和th:text=“${items}”时,列表根本不会出现。但当我取下它们时,chrome显示默认值“hello!world”。