首页 > 解决方案 > Spring Boot @Valid 不给出错误消息或有错误始终设置为 False

问题描述

控制器类代码。

@GetMapping("/admin/home")
public String adhomePage(@ModelAttribute("schoolModel") SchoolModel school, Model model) {
    return "admin/home";
}

@PostMapping("/admin/saveschool")
public String saveSchool(@Valid @ModelAttribute("schoolModel") SchoolModel schoolModel, BindingResult result) {
    System.out.println(schoolModel.toString()+">>>>>>>>>>>>>>>>>>>>");
    System.out.println(result.hasErrors()+"RESULT HASE ERROR");
    System.out.println(result.getAllErrors().toString());
    if (result.hasErrors()) {
        System.out.println("ERROR");
        System.out.println(result.getAllErrors().toString());
    }
    return "admin/home";
}

型号分类代码

package com.gatepass.web.model;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Size;

import org.springframework.lang.NonNull;


public class SchoolModel {
    
    @NotEmpty(message = "User's name cannot be empty.")
    @NotBlank()
    @NonNull()
    @Size(min=2, max=3)
    private Long id;
    
    @NotEmpty(message = "User's name cannot be empty.")
    @Size(min=2, max=2)
    private String name;
    
    @NotEmpty(message = "User's name cannot be empty.")
    @Size(min=2, max=2)
    private String email;
    
    @NotEmpty(message = "User's name cannot be empty.")
    @Size(min=2, max=30)
    private String mobileNumber;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getMobileNumber() {
        return mobileNumber;
    }

    public void setMobileNumber(String mobileNumber) {
        this.mobileNumber = mobileNumber;
    }

    @Override
    public String toString() {
        return "SchoolModel [id=" + id + ", name=" + name + ", email=" + email + ", mobileNumber=" + mobileNumber + "]";
    }
    
}

代码

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
 <link th:href="@{/css/style.css}" rel="stylesheet" />
<title>Insert title here</title>
</head>
<body>
    <h1>HOME PAGE VIEW FOR ADMIN</h1>
    <form th:action="@{/logout}" method="post">
        <input type="submit" value="logout">
        <input 
          type="hidden" 
          th:name="${_csrf.parameterName}" 
          th:value="${_csrf.token}" />
    </form>
      
      <br></br>
    <form th:action="@{/admin/saveschool}" th:object="${schoolModel}" method="post">
        <input type="text" th:field="*{id}">
        <input type="text" th:field="*{name}">
        <input type="text" th:field="*{email}">
        <input type="text" th:field="*{mobileNumber}">
        <br></br>
        <input type="submit" value="submit"/>
    </form>
    
</body>
</html>

我正在插入一个空值,但验证不起作用我不明白我也尝试过@validate 但它不起作用的问题是什么。

在这张图片中,如果您看到我没有插入任何值并提交表单 但是如果您在控制台中看到它给出错误但它必须是真的 我是spring boot的新手,请帮我解决这个问题。

我正在尝试在 Spring Boot 应用程序中添加验证规则,我创建了一个包含学校对象的表单,并且该学校对象与 modelAttribute 映射。

因此,当我提交发布请求时,它应该验证我在 SchoolModel 类中添加的规则,但它不是工作学校模型有数据但它不验证数据并且绑定结果有一个错误的结果导致 hase 错误

控制器类

评论后新更新的代码............ XML FILE

    <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.gatepass.web</groupId>
    <artifactId>gatepass</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>GatePassSystem</name>
    <description>A project where student will register and they will get their gate pass for outside visiting</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
      <dependencies>
      
        <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        
        <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    
       <dependency>
          <groupId>mysql</groupId>
          <artifactId>mysql-connector-java</artifactId>
          <scope>runtime</scope>
        </dependency>

        <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        
        <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-devtools</artifactId>
          <scope>runtime</scope>
          <optional>true</optional>
        </dependency>
        
        <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-test</artifactId>
          <scope>test</scope>
        </dependency>
            
        <dependency>
          <groupId>org.springframework.security</groupId>
          <artifactId>spring-security-test</artifactId>
          <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
        </dependency>
       <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-validation</artifactId>
       </dependency>        
      </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

模型类

    package com.gatepass.web.model;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Size;



@Valid
public class SchoolModel {
    
    
    private Long id;
    
    @Valid
    @NotEmpty(message = "User's name cannot be empty.")
    @Size(min=2, max=2)
    private String name;
    
    @Valid
    @NotEmpty(message = "User's name cannot be empty.")
    @Size(min=2, max=2)
    private String email;
    
    @Valid
    @NotEmpty(message = "User's name cannot be empty.")
    @Size(min=2, max=30)
    private String mobileNumber;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getMobileNumber() {
        return mobileNumber;
    }

    public void setMobileNumber(String mobileNumber) {
        this.mobileNumber = mobileNumber;
    }

    @Override
    public String toString() {
        return "SchoolModel [id=" + id + ", name=" + name + ", email=" + email + ", mobileNumber=" + mobileNumber + "]";
    }
    
}

控制器类

    package com.gatepass.web.controller;


import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;

import com.gatepass.web.model.SchoolModel;
import com.gatepass.web.repo.RoleJpa;

@Validated
@Controller
public class WelcomeController {
    
    @Autowired
    RoleJpa roleJpa;
    
    @GetMapping("/user/home")
    public String ushomePage() {
        System.out.println(SecurityContextHolder.getContext().getAuthentication().toString()+"---USER HOME");
        //Optional<Role> r = roleJpa.findById(1L);
        return "user/home";
    }

    
    @GetMapping("/admin/home")
    public String adhomePage(@ModelAttribute("schoolModel") SchoolModel school, Model model) {
        return "admin/home";
    }
    
    @PostMapping("/admin/saveschool")
    public String saveSchool(@Valid @ModelAttribute("schoolModel") SchoolModel schoolModel, BindingResult result) {
        System.out.println(schoolModel.toString()+">>>>>>>>>>>>>>>>>>>>");
        System.out.println(result.hasErrors()+"RESULT HASE ERROR");
        System.out.println(result.getAllErrors().toString());
        if (result.hasErrors()) {
            System.out.println("ERROR");
            System.out.println(result.getAllErrors().toString());
        }
        return "admin/home";
    }
    
    @GetMapping("/manager/home")
    public String mghomePage() {
        System.out.println(SecurityContextHolder.getContext().getAuthentication().toString()+"---MANAGER HOME");
        return "manager/home";
    }

}

标签: javaspringspring-boot

解决方案


@NotEmpty 和 @NotBlank() 只能作用于字符串类型的属性。@Size 是一样的。所以..

@NonNull(message = "User's name cannot be empty.")
@Min(2)
@Max(3)
private Long id;

Spring 示例:https ://spring.io/guides/gs/validating-form-input/


推荐阅读