简体   繁体   中英

Spring MVC 4 @RequestParam DTO mandatory attributes

I've created a DTO object that contains as many attributes as parameters my @RestController needs to receive. Some of them are mandatory and others are not.

The controller method looks as follows:

@RequestMapping(path = "/endpoint_url", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public List<ReturnDTO> endpoint(@RequestParam(required = false) FilterDTO filter) { ... }

I want to know if there's any way to make some of the FilterDTO attributes mandatory similarly as it's done with the @RequestParam(required = true) annotation.

I've tried the @NotNull annotation from javax.validation.constraints.NotNull but it doesn't seem to work.

Any ideas are kindly appreciated!

The idea is that you will need to use @Validated or @Valid from org.springframework.validation.annotation with your @RequestBody object so it will look like this

@RequestMapping(path = "/endpoint_url", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public List<ReturnDTO> endpoint(@Validated @RequestParam FilterDTO filter){}

then all variables in the FilterDTO are optional unless you add @NotNull annotation to them

so it will be as

@NotNull
private String name

this mean name cannot be null or exception will be thrown

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM