erondem
erondem

Reputation: 582

@Valid and @NotNull Annotations does not catch empty field in post request

Hi I have one field JSON POST Request.

import lombok.*;
import javax.validation.constraints.NotNull;

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class WebURLRequest {

    @NotNull(message = "URL can not be null")
    private String url;
}

In Controller, I have annotated as @Valid and @RequestBody but when I sent a post request like this I except to this returned a meaningful message as I write down in DTO. Instead of this message, since url is not found in request body, Service layer throws NullPointerException. I know I can handle this in Service layer or in Controller with a Null check but shouldn't this handled by @NotNull annotation?

Controller

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@PostMapping("/to-deep")
    public ResponseEntity<DeepResponse> toDeep(@Valid @RequestBody WebURLRequest webURLRequest) {
        return new ResponseEntity<>(converterService.toDeep(webURLRequest), HttpStatus.OK);
    }

The request body I sent

{
"somethingElse":""
}

SOLUTION:

I added this dependency to pom file

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

Upvotes: 0

Views: 1489

Answers (1)

erondem
erondem

Reputation: 582

Thanks to @M. Deinum I added this dependency to pom file and it solves my problem.

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

Upvotes: 1

Related Questions