Home > Blockchain >  Spring Boot validator does`t work properly
Spring Boot validator does`t work properly

Time:02-17

I have encountered such a problem that the validator does not see the data that I transmit in the body.

WARN 4088 --- [io-28852-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.bind.MethodArgumentNotValidException: Validation failed for argument [0] in public org.springframework.http.ResponseEntity<account.entitys.User> account.controllers.Authentication.singUp(account.entitys.User) with 2 errors: [Field error in object 'user' on field 'password': rejected value [null]; codes [NotEmpty.user.password,NotEmpty.password,NotEmpty.java.lang.String,NotEmpty]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.password,password]; arguments []; default message [password]]; default message [must not be empty]] [Field error in object 'user' on field 'lastname': rejected value []; codes [NotEmpty.user.lastname,NotEmpty.lastname,NotEmpty.java.lang.String,NotEmpty]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.lastname,lastname]; arguments []; default message [lastname]]; default message [must not be empty]] ]

Controller:

import javax.validation.Valid;

@RequestMapping("/api/auth")
@Controller()
public class Authentication {

    ArrayList<User> data = new ArrayList<>();

    @PostMapping("signup")
    public ResponseEntity<User> singUp(@Valid @RequestBody User user) {
        data.add(user);
        return new ResponseEntity<>(user, new HttpHeaders(), HttpStatus.OK);
    }
}

User:

import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.*;

import javax.validation.constraints.NotEmpty;


@Data
@Getter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class User {
    @NotEmpty
    private String name;
    @NotEmpty
    private String lastname;
    @NotEmpty
    private String email;
    @JsonIgnore
    @NotEmpty
    private String password;
}

Json:

{"name":"John","lastname":"Doe","email":"[email protected]","password":"secret"}

Gradle:

implementation 'org.springframework.boot:spring-boot-starter-validation'
implementation group: 'javax.validation', name: 'validation-api', version: '2.0.1.Final'
implementation group: 'org.hibernate', name: 'hibernate-validator', version: '6.1.0.Final'

I am a beginner, I don't have enough experience and this is the first time I have encountered such a problem. If I don't use a validator then everything works.

CodePudding user response:

You have both @JsonIgnore and @NotEmpty on the field password. The first annotation will tell spring to ignore the value for the field password, thus password will always remain null. This will cause the @NotEmpty validation rule to always fail. Remove @JsonIgnore and try again.

  • Related