Spring boot validation错误信息在Controller中存在,但为什么在渲染页面时无法正常获取?

问题描述

Spring boot validation错误信息在Controller中存在,但在渲染页面时无法正常获取
尝试通过println打印,发现controller中错误信息是正常存在的

问题出现的环境背景及自己尝试过哪些方法

Eclipse 2023-03
Spring Boot 2.7.10

相关代码

TestUser.java

@Data
@Entity
@AllArgsConstructor
@NoArgsConstructor(access=AccessLevel.PUBLIC, force=true)
public class TestUser{
    @Id
    @NotBlank(message = "user is required.")
    private String name;
    
    @Email(message = "wrong email format.")
    @NotBlank(message = "email is required.")
    private String email;
    
    @NotBlank(message = "password is required.")
    private String password;
}

TestUserController.java

@Controller
@RequestMapping("/user")
public class TestUserController {
    
    @GetMapping
    public String showRegisterForm() {
        return "user";
    }
    
    @PostMapping
    public String register(@Valid TestUser testUser, Errors errors) {
        if (errors.hasErrors()) {
            return "user";
        }
          
        return "redirect:/";
    }
    
    @ModelAttribute(name = "testUser")
    public TestUser testUser() {
        return new TestUser();
    }
}

user.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>User</title>
<link rel="stylesheet" th:href="@{/styles.css}" />
</head>
<body>
<form method="POST" th:action="@{/user}" th:object="${testuser}">

<div th:if="${#fields.hasErrors()}">
    <span class="validationError">
    Something went wrong.
    </span>
</div>

<label for="name">Name: </label>
<input type="text" th:field="*{name}" />
<span class="validationError"
      th:if="${#fields.hasErrors('name')}"
      th:errors="*{name}">Name Error</span>
<br />

<label for="email">Email address: </label>
<input type="text" th:field="*{email}" />
<span class="validationError"
       th:if="${#fields.hasErrors('email')}"
       th:errors="*{email}">Email Error</span>
<br />

<label for="password">City: </label>
<input type="text" th:field="*{password}"/>
<span class="validationError"
      th:if="${#fields.hasErrors('password')}"
      th:errors="*{password}">Password Error</span>
<br/>
<input type="submit" value="Submit User"/>
</form>
</body>
</html>

你期待的结果是什么?实际看到的错误信息又是什么?

期待的结果是页面中类型为validationError的span标签正常渲染并在表单页面显示错误信息,但实际看到的情况是页面中这些span标签并没有被渲染

阅读 1.8k
2 个回答

自己检查了半天发现是个很初级的错误,靠打印模型里的值才发现有两个testUser对象,模版里th:object写的是testuser,添加到模型的参数却是testUser,难怪模版找不到要的值了

这种好久没写了,你试下
你页面上用的fields对象取得错误信息
return user;之前将errors放到request中,name设置为fields

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题