3

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?

Archie
  • 962
  • 2
  • 9
  • 20

1 Answers1

3

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.

davidxxx
  • 125,838
  • 23
  • 214
  • 215
  • Thanks, that almost worked: instead of `ConstraintViolationException ` there is a `org.springframework.validation.BindException` with a long nasty error message – Archie Apr 30 '18 at 12:42
  • You are welcome. You could paste the whole stacktrace in pastebin or any website that allows that. – davidxxx Apr 30 '18 at 14:23
  • Add a "BindingResult bindingResult" after "@Valid Filter filter" so that spring has a way to tell you about the binding errors – wesker317 Apr 30 '18 at 14:35