How to validate request parameter if it is not a bean in spring MVC?

时光总嘲笑我的痴心妄想 提交于 2019-12-23 11:15:10

问题


Below is a POST end point in my spring MVC REST service. I want to use spring validation frame work to make sure that list I receive is not empty. How do I do it? Do I have to provide wrapper bean to around listOfLongs?

    @RequestMapping(value = "/some/path", method = RequestMethod.POST)
    @ResponseBody
    public Foo bar(@Valid @NotEmpty @RequestBody List<Long> listOfLongs) {

     /*   if (listOfLongs.size() == 0) {
            throw new InvalidRequestException();
        }
     */

        // do some useful work
    }

What should be the Request Body?

1) [123,456,789]
2) { listOfLongs : [123,456,789]}

回答1:


Providing a wrapper bean is a good practice.

class LongList {

 @NotEmpty
 private List<Long> listOfLongs;

 // Setters and Getters ...

}

Then, the Request Body should be { listOfLongs : [123,456,789]}

@RequestMapping(value = "/some/path", method = RequestMethod.POST)
@ResponseBody
public Foo bar(@Valid @RequestBody LongList listOfLongs) {   

    // do some useful work
}


来源:https://stackoverflow.com/questions/16908689/how-to-validate-request-parameter-if-it-is-not-a-bean-in-spring-mvc

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