How to automatically validate rest parameters in @

2019-08-01 07:09发布

问题:

I want to automatically validate REST parameters on a spring REST service.

I tried it using @Valid @NotNull, but the rest request does not get rejected automatically, but the dao method is executed with null argument. Why?

@RestController
public class RestController {
    @RequestMapping(value = "/")
    public Boolean getResponse(@Valid @NotNull @Length(max = 20) String username) {
          return daoService.lookup(username); //is executed if username = null
    }
}

How can I get automatically a returned HTTP error, eg 400?

回答1:

Here is an example of validation on request parameters..

public ResponseEntity<AgencyResource> saveAgency(
    @Valid @RequestBody AgencyResource agencyResource) {
 return new ResponseEntity<AgencyResource>(agencyResource, HttpStatus.OK);
 }

This is from the POST http://www.leveluplunch.com/java/tutorials/017-validate-spring-rest-webservice-request/

Hope this helps.

Thanks, Paul



标签: java spring rest