gpt4 book ai didi

java - IntelliJ : cannot resolve vars 中的 Spring Boot + thymeleaf

转载 作者:IT老高 更新时间:2023-10-28 13:49:03 26 4
gpt4 key购买 nike

我正在IntelliJ上使用spring boot和thymeleaf编写一个简短的web表单应用程序,但似乎在html文件中,模型中的所有字段都无法解析。这是我的代码:

Controller 类:

@Controller
public class IndexController{

@RequestMapping(value = "/", method = RequestMethod.GET)
public String index(){
return "index";
}

@RequestMapping(value="/", method = RequestMethod.POST)
public String addNewPost(@Valid Post post, BindingResult bindingResult, Model model){
if(bindingResult.hasErrors()){
return "index";
}
model.addAttribute("title",post.getTitle());
model.addAttribute("content",post.getContent());
return "hello";
}
}

模型类:

public class Post {

@Size(min=4, max=35)
private String title;

@Size(min=30, max=1000)
private String content;

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}

public String getContent() {
return content;
}

public void setContent(String content) {
this.content = content;
}
}

然后是index.html:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head lang="en">

<title>Spring Framework Leo</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>

<h3>Spring Boot and Thymeleaf</h3>


<form action="#" th:action="@{/}" th:object="${post}" method="post">
<table>
<tr>
<td>Title:</td>
<td><input type="text" th:field="*{title}" /></td>
<td th:if="${#fields.hasErrors('title')}" th:errors="*{title}">Title error message</td>
</tr>
<tr>
<td>Content:</td>
<td><input type="text" th:field="*{content}" /></td>
<td th:if="${#fields.hasErrors('content')}" th:errors="*{content}">Content error message</td>
</tr>
<tr>
<td><button type="submit">Submit post</button></td>
</tr>
</table>
</form>

“帖子”、“标题”和“内容”下总是有红线,但我不知道如何解决。是 IntelliJ 的问题还是我的代码的问题?

最佳答案

更新

TL;DR: 跳到下面接受的答案:https://stackoverflow.com/a/44804086/474034

正如多人评论中提到的,这个解决方案是不正确的。 Thymeleaf 文档(参见 http://thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html )在所有示例中都有一个包含 www. 的版本:

<html xmlns:th="http://www.thymeleaf.org">

另见Standard-Dialect.xml在 Github 上,将 namespace-uri 声明为:

namespace-uri="http://www.thymeleaf.org" 

原答案

我有两段不同的代码:第一段显示错误,第二段没有显示。我观察到 xmlns:th 属性存在差异。

首页:无效!

<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">

第二页:工作中!

<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://thymeleaf.org">

我删除了 www.,它对我有用!

关于java - IntelliJ : cannot resolve vars 中的 Spring Boot + thymeleaf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38710585/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com