【问题标题】:Why @Valid do not works为什么@Valid 不起作用
【发布时间】:2020-07-12 20:41:49
【问题描述】:

我正在参加在线课程,讲师放置了两个注释来验证我的类别对象中的字段。名称属性中的@Notnull 注释和控制器中的@Valid,在他的视频中,错误http响应从500变为400,因为它正在验证属性。在他放回验证之前,他返回了 500。我的一直返回 500。换句话说,注释 @Valid 和 @Notnull 似乎没有任何效果,有人知道为什么吗? 这是我的代码:

我的Pom:

<?xml version="1.0" encoding="UTF-8"?>

4.0.0 org.springframework.boot spring-boot-starter-parent 2.3.1.发布 罐子——> com.algaworks.algamoney-api algamoney-api 1.0.0-快照 algamoney-api Spring Boot 演示项目

<properties>
    <java.version>1.8</java.version>
</properties>

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

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>javax.validation</groupId>
        <artifactId>validation-api</artifactId>
        <version>2.0.1.Final</version>
    </dependency>
    <dependency>
        <groupId>org.flywaydb</groupId>
        <artifactId>flyway-core</artifactId>
        <version>6.4.4</version>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
</dependencies>

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

我的控制器

package com.example.algamoney.api.resource;

import java.net.URI;
import java.util.List;
import java.util.Optional;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import org.springframework.web.util.UriBuilder;

import com.example.algamoney.api.model.Categoria;
import com.example.algamoney.api.repository.CategoriaRepository;

@RestController
@RequestMapping("/categoria")
public class CategoriaResource {
    
    @Autowired
    private CategoriaRepository categoriaRepository;
    
    @GetMapping("/listar")
    public List<Categoria> listar(){
        return categoriaRepository.findAll();
    }
    
    @PostMapping("/criar")
    public ResponseEntity<Categoria> criar(@Valid @RequestBody Categoria categoria, HttpServletResponse response) {
        Categoria categoriaSalva = categoriaRepository.save(categoria);
        URI uri = ServletUriComponentsBuilder.fromCurrentRequestUri().path("/{codigo}")
                .buildAndExpand(categoria.getCodigo()).toUri();
        response.setHeader("Location", uri.toASCIIString());
        return ResponseEntity.created(uri).body(categoriaSalva);
    }
    
    @GetMapping("/buscar/{codigo}")
    public Optional<Categoria> buscarCategoriaPorCodigo(@PathVariable Long codigo) {
        return categoriaRepository.findById(codigo);
    }

}

我的对象

package com.example.algamoney.api.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;

@Entity
@Table(name = "categoria")
public class Categoria {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    
    @NotNull(message = "Nome não pode ser nulo")
    private String nome;
    
    public Long getCodigo() {
        return id;
    }
    public void setCodigo(Long codigo) {
        this.id = codigo;
    }
    public String getNome() {
        return nome;
    }
    public void setNome(String nome) {
        this.nome = nome;
    }
    
}

【问题讨论】:

  • 你必须在你的控制器中包含@Validated
  • 请包含请求正文和错误堆栈跟踪。
  • 尝试将 RequestBody annot 放在 PostMapping annot 之后,而不是放在 Valid annot 之后

标签: java spring validation


【解决方案1】:

有些注释是 JSR 380 的一部分,有些是 JSR 303。 所以尝试包含以下支持大多数 javax 验证的依赖项。

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>6.1.5.Final</version>
</dependency>

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


【讨论】:

    【解决方案2】:

    【讨论】:

    • OP 说“@Valid”不起作用,他没有提到“@valid”无法识别
    猜你喜欢
    • 1970-01-01
    • 2013-06-18
    • 2017-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-16
    • 2017-10-04
    相关资源
    最近更新 更多