简体   繁体   中英

Make Spring java object request parameter required

I have the following controller code

@GetMapping("/users")
public ResponseEntity<UserDto> getUsers(Filter filter) {
    return ResponseEntity.ok(userService.findUsers(filter));
}

Filter.java:

public class Filter {
    private Integer page;

    private Integer size;

    private String sort;

    ... lots of other parameters
}

The request parameters are written as a Java object to avoid adding lots of parameters to controller. However, all of the parameters are made optional by Spring. What I want is to have some parameters like page and size required, but others like sort optional. If I had them as controller parameters, I could use @RequestParam(required = true/false) . Is it possible to do something similar in Java class?

You can use the javax.validation API to specify some constraints on the fields of a class.
In your case you could use @NotNull and @NotEmpty according to your requirements and the field types such as :

import javax.validation.constraints.NotNull;
import javax.validation.constraints.NotEmpty;
...

public class Filter {

    @NotNull
    private Integer page;

    @NotEmpty
    private Integer size;

    private String sort;

    ... lots of other parameters
}

Then specify the @Valid annotation for the parameter you want to validate :

import javax.validation.Valid;
...
@GetMapping("/users")
public ResponseEntity<UserDto> getUsers(@Valid Filter filter) {
    return ResponseEntity.ok(userService.findUsers(filter));
}

If the filter parameter doesn't respect the constraints, a ConstraintViolationException is thrown that you can leave or catch to map it to a specific client 4XX error by using a Spring exception handler such as @ControllerAdvice .

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