Validate a list of DTOs when reaching our endpoint
1. Dependencies - pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
or
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
<version>2.2.6.RELEASE</version>
</dependency>
(By default, Spring uses hibernate-validator, which implements the JSR-380)
2. Controller class - REST level
// Enables validation in method level
@Validated
@RestController
@RequestMapping("/api/project")
public class DayActivityResource {
// Our list object cannot be null
// List elements are validated each, using @Valid
@PostMapping("/day-activities")
public ResponseEntity<List<DayActivityDTO>> createDayActivities(@NotNull @RequestBody List<@Valid DayActivityDTO> dayActivityDtos) {
// ...
}
}
3. DTO classes with constraint annotations
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import javax.validation.constraints.Valid;
public class DayActivityDTO implements Serializable {
private String id;
private String activityId;
private String activityTypeId;
// We want this String to be numeric
private String generalFactor;
// A log date must always exist
private LocalDate logDate;
// Validate nested object
private DayActivityRecurringInfo recurringInfo;
private String sendUpdateToEmail;
}
// Nested class
public class DayActivityRecurringInfo {
private Integer recurEveryDays;
private Integer recurForWeeks;
}
Δεν υπάρχουν σχόλια:
Δημοσίευση σχολίου
What may be missing, or could get better?