Spring Boot 验证大小

Spring boot validation size

提问人:GPPiotr 提问时间:9/3/2023 最后编辑:GPPiotr 更新时间:9/3/2023 访问量:86

问:

当我在 postman 中测试我的端点时,我的验证不起作用。 http://localhost:8080/departments 当我作为 POST 方法输入这个 json 时,它仍然有效,即使它不应该工作,因为 departmentName String 上方的 @Size(min = 2) 注释。

{ “departmentName”: “a”, “departmentAdress”:“米佐多拉”, “部门代码”:“IT-19” }

package com.dailycodebuffer.Springboottutorial.entity;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;

@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class Department {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long departmentId;
    @NotBlank(message = "Please add Department Name")
    @Size(min = 2, message = "Department Name must be at least 2 characters long")
    private String departmentName;
    private String departmentAdress;
    private String departmentCode;
}
package com.dailycodebuffer.Springboottutorial.controller;

import com.dailycodebuffer.Springboottutorial.entity.Department;
import com.dailycodebuffer.Springboottutorial.error.DepartmentNotFoundException;
import com.dailycodebuffer.Springboottutorial.service.DepartmentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Optional;

@RestController
@Validated
public class DepartmentController {

    @Autowired
    private DepartmentService departmentService;

    private final Logger LOGGER = LoggerFactory.getLogger(DepartmentController.class);

    @PostMapping("/departments")
    public Department saveDepartment(@Valid @RequestBody Department department) {
        LOGGER.info("Inside saveDepartment of DepartmentController");
        return departmentService.saveDepartment(department);
    }

    @GetMapping("/departments")
    public List<Department> fetchDepartmentList() {
        LOGGER.info("Inside fetchDepartment of DepartmentController");
        return departmentService.fetchDepartmentList();
    }

    @GetMapping("/departments/{departmentId}")
    public Optional<Department> fetchDepartmentById(@PathVariable Long departmentId) throws DepartmentNotFoundException {
        return departmentService.fetchDepartmentById(departmentId);
    }

    @DeleteMapping("/departments/{departmentId}")
    public String deleteDepartmentById(@PathVariable Long departmentId) {
        departmentService.deleteDepartmentById(departmentId);
        return "Succes";
    }

    @PutMapping("/departments/{departmentId}")
    public Department updateDepartment(@PathVariable Long departmentId, @RequestBody Department department) {
        return departmentService.updateDepartment(departmentId, department);
    }

    @GetMapping("/departments/name/{departmentName}")
    public Department fetchDepartmentByName(@PathVariable String departmentName) {
        return departmentService.fetchDepartmentByName(departmentName);
    }

}


<?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>3.1.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <groupId>com.dailycodebuffer</groupId>
    <artifactId>Spring-boot-tutorial</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>Spring-boot-tutorial</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>20</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</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-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>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>2.0.1.Final</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.28</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

我尝试使用 json 的 postman,但当我输入一个字母时,甚至当我从 json departmentName 中删除时,它都不起作用

Spring Spring-Boot REST 验证邮 递员

评论


答:

0赞 abi rajasekar 9/3/2023 #1

尝试使用下面的导入来调整大小..... 导入 jakarta.validation.constraints.Size;

评论

0赞 GPPiotr 9/3/2023
这种导入不走运。
1赞 anicetkeric 9/3/2023 #2

您需要添加到控制器而不是实体。@Validated

  1. @Valid方法级验证的注释。
  2. @Validated验证组的注释。
    @RestController
    @Validated
    public class DepartmentController {
    
        @Autowired
        private DepartmentService departmentService;
    
        @PostMapping("/departments")
        public Department saveDepartment(@Valid @RequestBody Department department) {
            return departmentService.saveDepartment(department);
        }
        ...
    }

Spring boot 3.x.x 支持 Jakarta EE 9。Spring Boot 3.0.0 M1发行说明。 您需要将 javax.validation 依赖项更改为 spring-boot-starter-validation

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

用于:

导入 jakarta.validation.constraints.Size;