使用@Valid @RequestBody 的用意在于抛出notvalid的异常
来源:互联网 发布:用数据库统计访问次数 编辑:程序博客网 时间:2024/05/18 15:05
Different ways of validating @RequestBody in Spring MVC 3.2 with @Valid annotation
In spring MVC the @RequestBody annotation indicates a method parameter should be bound to a body of the request. @RequestBody parameter can treated as any other parameter in a@RequestMapping method and therefore it can also be validated by a standard validation mechanism. In this post I will show 2 ways of validating the @RequestBody parameter in your Spring MVC application.
In my sample application I want to create a new Task with not blank name and description. In order to do it I create an API endpoint that supports POST method and accepts Task as JSON.
Tip: To bootstrap the application I used: spring-mvc-quickstart-archetype .
Let's start with the task:
To handle the task we need a @Controller: The next thing we need to do is the validation. So let's do it.Validation with @ExceptionHandler
As of Spring 3.1 the @RequestBody method argument can be annotated with @Valid or @Validated annotation to invoke automatic validation. In such a case Spring automatically performs the validation and in case of error MethodArgumentNotValidException is thrown. Optional @ExceptionHandler method may be easily created to add custom behavior for handling this type of exception. MethodArgumentNotValidException holds both the parameter that failed the validation and the result of validation. Now, we can easily extract error messages and return it in an error object as JSON.
Exception handler method does not need to be located in the same controller class. It can be a global handler for all you API calls.
Validation with Errors/BindingResult object
As of Spring 3.2 @RequestBody method argument may be followed by Errors object, hence allowing handling of validation errors in the same @RequestMapping. Let's look at the code:
Both approaches produce the same result in the above example. Which is better? I don't know yet. And do you?
- 使用@Valid @RequestBody 的用意在于抛出notvalid的异常
- 使用@Valid @RequestBody 的用意在于抛出notvalid的异常
- lucene 抛出的异常
- 抛出异常的方法
- 抛出异常的特点
- 异常----异常对象的抛出
- Spring RequestBody 的使用
- @RequestBody的使用
- 抛出异常的爱情密码
- tomcat抛出的奇怪异常
- 页面捕获抛出的异常
- 异常的抛出基本问题
- 一个异常抛出的例子
- 一个异常抛出的例子
- 不抛出异常的swap
- 异常的捕捉和抛出
- python异常的抛出机制
- 自动抛出异常的应用
- 我用servlet读取数据库图片文件已经成功
- 网页正文提取工具Beautiful Soup
- Android 扫描wifi局域网ip
- 学习路径
- Unity 键盘,鼠标,触摸输入
- 使用@Valid @RequestBody 的用意在于抛出notvalid的异常
- Windows下Git的下载和安装配置
- tolua++入门
- Oracle中对超长内容的处理,避免出现can bind a LONG value only for insert into a LONG column错误
- 回型数组
- Springboot整合mybatis项目开发
- 提高EJB性能的十大技巧
- C++之类型转换
- Java异常处理机制