Spring MVC with hibernate Validator to validate single basic type

后端 未结 3 1316
我寻月下人不归
我寻月下人不归 2021-02-19 07:45

Below is the mapped method that I am having trouble with, no matter what value I pass to it the validation returns \"passed validation.\"

@RequestMapping(value          


        
3条回答
  •  忘掉有多难
    2021-02-19 08:13

    I am hoping to not have to define an object that only contains a long value just so that I can run validation on it.

    Defining a wrapping bean would IMHO be the smartest move, as hibernate-validator is completly centered around the notion of the bean, and is, after all, a reference implementation of the bean validation specification. One of the primary motivators of the spec is to acknowledge validation as a cross-cutting concern that spans across different app layers, and provide a mechanism to gracefully handle this. That is the reason why it is centered around beans, its the objects that get passed through the layers.

    On the other hand, validating primitves programtically is not a big deal after all, your code can simply be something like

    @RequestMapping(value = "test", method = RequestMethod.POST)
    @ResponseBody
    public String getTest(@RequestBody long longValue, BindingResult result) {
      if (longValue > 32) {
         result.rejectValue("longValue", "error.longValue", "longValue max constrained failed");
        return "failed validation";
      } else {
        return "passed validation";
      }
    }
    

    So in my opinion, either go for the programatic validation if its simple enough, or simply wrap the value.

提交回复
热议问题