【问题标题】:Form validation in thymeleaf by SpringbootSpringboot 在 thymeleaf 中的表单验证
【发布时间】:2021-01-14 15:54:55
【问题描述】:

我是 Springboot 和 Thymeleaf 的新手,我正在创建一个网络,我在其中使用表单验证,我试图验证实体类中的字段以验证非空字段。

import javax.validation.constraints.NotBlank;

public class Student {

@NotBlank(message = "Name required")
public String name;
@NotBlank(message = "email required")
public String email;
@NotBlank(message = "address required")
public String address;
@NotBlank(message = "username required")
public String username;
@NotBlank(message = "password required")
public String password;

'''
constructor
getter and setter
'''
}

在我的 html 文件中没有显示错误,在服务器上显示错误。 如果有人有任何想法,请帮助我。

【问题讨论】:

  • 请分享html文件

标签: spring-boot thymeleaf


【解决方案1】:

为了使它起作用,在@ModelAttribute("student")旁边添加@valid注解。

    public String addUser(@Valid @ModelAttribute("student") Student student, BindingResult result, Model model){

还可以尝试在 Student 实体字段上方添加 @NotEmpty。 @NotEmpty 将检查对象是否有空字符串。

【讨论】:

  • 控制器必须是@Validated
  • @silentsudo 你能提供你的控制器类和 HTML 文件吗
【解决方案2】:

试试这个,

public String addUser(@Valid @ModelAttribute("student") Student student, Model model){
...
}

另外,在实体属性上添加@NotNull 并检查一次。

【讨论】:

    【解决方案3】:

    试试这个:

        public String addUser(@Valid @ModelAttribute("student") Student student, BindingResult result, Model model){
    

    另外,在实体属性上添加@NotNull 并检查一次。

    【讨论】:

      猜你喜欢
      • 2017-08-10
      • 2020-06-09
      • 2021-10-08
      • 2017-07-14
      • 1970-01-01
      • 2020-09-18
      • 1970-01-01
      • 2019-12-26
      • 1970-01-01
      相关资源
      最近更新 更多