spring boot@valid未给出错误消息或has error始终设置为false

yeotifhr  于 2021-08-20  发布在  Java
关注(0)|答案(2)|浏览(281)

控制器类代码。

@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 + "]";
    }

}

html代码

<!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应用程序中添加验证规则。我创建了一个包含学校对象的表单,该学校对象Map为modelattribute。
因此,当我提交post请求时,它应该验证我在schoolmodel类中添加的规则,但它不是有效的。学校模型有数据,但它没有验证数据,绑定结果有错误的结果

注解后的新更新代码。。。。。。。。。。xml文件

<?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";
    }

}
yi0zb3m4

yi0zb3m41#

我刚刚尝试了一个小的演示项目,它对我来说很好。
控制器。

import javax.validation.Valid;

import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.demo.test.dto.DemoDto;

@RestController
@Validated
public class DemoController {

    @PostMapping("/demo")
    String getValidationResponse(@Valid @RequestBody DemoDto demoDto) {
        return "all Valid";
    }

}

模范班

import javax.validation.Valid;
import javax.validation.constraints.NotNull;

    @Valid
    public class DemoDto {

        @Valid
        @NotNull
        private String name;

        @Valid
        @NotNull
        private int age;

        public String getName() {
            return name;
        }

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

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }

    }

pom.xml

<?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.demo.test</groupId>
    <artifactId>demovalidator</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demovalidator</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>11</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </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>

Postman 请求响应。

有效请求

ldioqlga

ldioqlga2#

@notempty和@notblank()只能处理字符串类型的属性@大小是一样的。所以

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

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

相关问题