在Spring MVC中使用注解的方式校验RequestParams
概述
Spring MVC支持Bean Validation,通过这个验证技术,可以通过注解方式,很方便的对输入参数进行验证,之前使用的校验方式,都是基于Bean对象的,但是在@RequestParam中,没有Bean对象,这样使得校验无法进行,可以通过使用@Validated注解,使得校验可以进行。
校验bean对象
一般校验bean对象,为了可以自动的校验属性,可以通过两步解决:
一、声明对象
package com.github.yongzhizhan.draftbox.model;
import javax.validation.constraints.Size;
/**
* 带验证的对象
* @author zhanyongzhi
*/
public class Foo {
private String validString;
@Size(min = 1, max = 5)
public String getValidString() {
return validString;
}
public void setValidString(final String vValidString) {
validString = vValidString;
}
}
二、通过@Valid注解使用对象
@ResponseBody
@RequestMapping(value = "validObject", method = RequestMethod.POST)
@ResponseStatus(HttpStatus.OK)
public String validObject(
@RequestBody()
@Valid Foo vFoo, BindingResult vBindingResult){
return vFoo.getValidString();
}
校验RequestParams
使用校验bean的方式,没有办法校验RequestParam的内容,一般在处理Get请求的时候,会使用下面这样的代码:
@ResponseBody
@RequestMapping(value = "validString", method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
public String validString(
@RequestParam(value = "str", defaultValue = "")
String vStr){
return vStr;
}
使用@Valid注解,对RequestParam对应的参数进行注解,是无效的,需要使用@Validated注解来使得验证生效。操作步骤如下:
一、声明错误处理类
package com.github.yongzhizhan.draftbox.controller;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import javax.validation.ValidationException;
@ControllerAdvice
@Component
public class GlobalExceptionHandler {
@Bean
public MethodValidationPostProcessor methodValidationPostProcessor() {
return new MethodValidationPostProcessor();
}
@ExceptionHandler
@ResponseBody
@ResponseStatus(HttpStatus.BAD_REQUEST)
public String handle(ValidationException exception) {
System.out.println("bad request, " + exception.getMessage());
return "bad request, " + exception.getMessage();
}
}
二、声明@Validated并加上校验注解
package com.github.yongzhizhan.draftbox.controller;
import com.github.yongzhizhan.draftbox.model.Foo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
import javax.validation.constraints.Size;
@RestController
@SuppressWarnings("UnusedDeclaration")
@Validated
public class IndexController {
@ResponseBody
@RequestMapping(value = "validString", method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
public String validString(
@RequestParam(value = "str", defaultValue = "")
@Size(min = 1, max = 3)
String vStr){
return vStr;
}
}
代码
参考
Bean Validation 技术规范特性概述
Validation, Data Binding, and Type Conversion
在Spring MVC中使用注解的方式校验RequestParams的更多相关文章
- Spring MVC 中采用注解方式 Action中跳转到另一个Action的写法
Spring MVC 中采用注解方式 Action中跳转到另一个Action的写法 在Action中方法的返回值都是字符串行,一般情况是返回某个JSP,如: return "xx" ...
- Spring MVC 中 @ModelAttribute 注解的妙用
Spring MVC 中 @ModelAttribute 注解的妙用 Spring MVC 提供的这种基于注释的编程模型,极大的简化了 web 应用的开发.其中 @Controller 和 @Rest ...
- spring 以及 spring mvc 中常用注解整理
spring 以及 spring mvc 中常用注解整理 @RequestMapping(映射路径) @Autowired(注入 bean 对象) 例如: @Autowired private Bas ...
- Spring MVC中基于注解的 Controller
终于来到了基于注解的 Spring MVC 了.之前我们所讲到的 handler,需要根据 url 并通过 HandlerMapping 来映射出相应的 handler 并调用相应的方法以响 ...
- 0001 - Spring MVC中的注解
1.概述 Spring MVC框架提供了功能强大的注解,大大简化了代码开发的同时也提升了程序的可扩展性 2.注解 2.1.@RequestMapping Spring MVC通过@RequestMap ...
- Spring MVC中@RequestMapping注解使用技巧(转)
@RequestMapping是Spring Web应用程序中最常被用到的注解之一.这个注解会将HTTP请求映射到MVC和REST控制器的处理方法上. 在这篇文章中,你将会看到@RequestMapp ...
- Spring MVC中@ControllerAdvice注解实现全局异常拦截
在网上很多都把Advice翻译成增强器,其实从翻译工具上看到,这个单词翻译是忠告,通知的意思. 首先这个注解实在Spring Web包下,而Spring MVC离不开Spring Web的依赖,所以经 ...
- spring mvc中的注解说明
注解扫描 context:component-scan 包扫描 <context:component-scan base-package="org.bdp"> < ...
- Spring Mvc如何通过注解的方式设置视图解析器的优先级
<bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalRes ...
随机推荐
- poj-1469-COURSES-二分图匹配-匈牙利算法(模板)
题意:N个学生,P个课程,问能不能找到课程的P个匹配. 思路:[早上睡醒了再写] 代码: #include <iostream> #include <cstdio> #incl ...
- Volley HTTP库系列教程(5)自定义一个Volley请求
Implementing a Custom Request Previous Next This lesson teaches you to Write a Custom Request parse ...
- [POJ2777]Count Color(线段树)
题目链接:http://poj.org/problem?id=2777 给你一个长为L想线段,向上面染色,颜色不超过30种,一共有O次操作,操作有两种: C a b c 在[a,b]上染上c颜色 P ...
- 终于成功仿了一次Kalman滤波器
终于成功仿了一次Kalman滤波器 首先是测试了从网上down的一段代码 % KALMANF - updates a system state vector estimate based upon a ...
- jupyterhub
pkill jupyterhub #激活python环境 pyenv activate jupyterhub #启动jupyterhub /fly/start_jupyterhub.sh cd ~/r ...
- HDU 5001 Walk
解题思路:这是一道简单的概率dp,只要处理好相关的细节就可以了. dp[d][i]表示走d步时走到i的改概率,具体参考代码: #include<cstdio> #include<cs ...
- UML时序图
时序图定义 : 描述了对象之间传递消息的时间顺序, 用来表示用例中的行为顺序, 是强调消息时间顺序的交互图; 时序图描述的事物: 时序图描述系统中类和类之间的交互, 将这些交互建模成消息交换, 时序图 ...
- Spring的5种通知
1.前置通知 Before advice Advice that executes before a join point, but which does not have the ability ...
- Heritrix源码分析(十四) 如何让Heritrix不间断的抓取(转)
欢迎加入Heritrix群(QQ):109148319,10447185 , Lucene/Solr群(QQ) : 118972724 本博客已迁移到本人独立博客: http://www.yun5u ...
- 集合框架null与size=0
被QA人员一眼指出来的问题,唉,好丢人 上栗子