@Valid not working for spring rest controller

戏子无情 提交于 2020-07-10 07:01:09

问题


I have defined a rest endpoint method as:

@GetMapping("/get")
public ResponseEntity getObject(@Valid MyObject myObject){....}

This maps request parameters to MyObject.

MyObject is defined as(with lombok, javax.validation annotations):

@Value
@AllArgsConstructor
public class MyObject {

    @Min(-180) @Max(180)
    private double x;

    @Min(-90) @Max(90)
    private double y;

}

But validations are not working. Even with values out of prescribed range, request doesn't throw error and goes well.


回答1:


I see a couple of things here that you should fix. Let's start talking about the REST standard, the first rule is to think in endpoints as representation of resources, not operations, for example, in your code, I presume the MyObject class represents a Point (you should refactor the class to have a proper name), then the path value for the getObject can be "/point". The operations are mapped on the HTTP method, accordingly:

  • GET: Obtain info about a resource.
  • POST: Create a resource.
  • PUT: Update a resource.
  • DELETE: Delete a resource.

In getObject you're expecting to receive an object. The get method according to the REST standards means you want to retrieve some data, and usually you send some data included in the url like ../app-context/get/{id}, here the id is a parameter that tells your controller you want some info belonging to an id, so if you would invoke the endpoint like as ../app-context/get/1 to get info of some domain object identified by the number 1.

If you want to send data to the server, the most common HTTP method is a POST.

According to this, at design level you should:

  • Give a meaningful name to the MyObject class.
  • Check the operation you want to make in the getObject.
  • Assign a path to getObject representing a resource.

At code level, with the above comments, you could change this as:

@Data
@AllArgsConstructor
@NoArgsConstructor
public class MyObject {

  @Min(-180) @Max(180)
  private double x;

  @Min(-90) @Max(90)
  private double y;
}

@PostMapping("/point")
public ResponseEntity savePoint(@RequestBody @Valid MyObject myObject) {...}

I will explain the changes:

  • Add @PostMapping to fulfill the REST standard.
  • Add @RequestBody, this annotation take the info sent to the server and use it to create a MyObject object.
  • Add @NoArgsConstructor to MyObject, by default, the deserialisation use a default constructor (with no arguments). You could write some specialised code to make the things work without the default constructor, but thats up to you.



回答2:


Annotate your controller with org.springframework.validation.annotation.Validated



来源:https://stackoverflow.com/questions/62221284/valid-not-working-for-spring-rest-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!