chrisblo
chrisblo

Reputation: 878

Spring Boot validation of RequestBody Dto annotated in Rest API

In my controller I have annotated the request parameter with the @Valid annotation and the field of my DTO with the @NotNull annotation, but the validation doesn't seem to work.

Are there any configurations to do in order to proceed with the validation? Following there are the Controller and the DTO class details.

@RepositoryRestController
@RequestMapping(value = "/download_pdf")
public class PurchaseController {

    @Autowired
    private IPurchaseService iPurchaseService;

    @Loggable
    @RequestMapping(value = "view_order", method = RequestMethod.POST)
    public ResponseEntity getPDF(@RequestBody @Valid CustomerOfferDto offer,
                                 HttpServletResponse response) {
        return iPurchaseService.purchase(offer, response);
    }
}

public class CustomerOfferDto {
    @NotNull
    private String agentCode;

    // getter and setter...

 }

Upvotes: 2

Views: 5455

Answers (2)

HarishVijayamohan
HarishVijayamohan

Reputation: 598

Following are the steps I did to make it work.

Add dependency:

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

Constraints in DTO class:

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@ValidTaskDTO
public class TaskDTO {

    @FutureOrPresent
    @NotNull(message = "DueDate must not be null")
    private ZonedDateTime dueDate;

    @NotBlank(message = "Title cannot be null or blank")
    private String title;

    private String description;

    @NotNull
    private RecurrenceType recurrenceType;

    @Future
    @NotNull(message = "RepeatUntil date must not be null")
    private ZonedDateTime repeatUntil;

}

RestController method with @Valid annotation on requestBody argument:

@RestController
@RequestMapping("/tasks")
@Validated
public class TaskController {

    @PostMapping
    public TaskDTO createTask(@Valid @RequestBody TaskDTO taskDTO) {
      .....
    }

}

On making a POST request with requestbody containing null value for dueDate, I got the expected error message as shown below.

{
  "timestamp": "2021-01-20T11:38:53.043232",
  "status": 400,
  "error": "Bad Request",
  "message": "DueDate must not be null"
}

I hope this helps. For details on class level constraints, hav a look at this video.

Upvotes: 2

Sebastian Ullrich
Sebastian Ullrich

Reputation: 1047

In my projects, this usually happens when I change my code from lets say Entity to DTO and forget to add @ModelAttribute to my DTO parameter.

If this also happened to you, try adding @ModelAttribute("offer") to your DTO parameter.

Upvotes: 1

Related Questions