How to automatically validate rest parameters in @

2019-08-01 06:58发布

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?

标签: java spring rest
1条回答
爷、活的狠高调
2楼-- · 2019-08-01 07:42

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

查看更多
登录 后发表回答