概述

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;
}
}

代码

在github中查看完整代码

参考

Bean Validation 技术规范特性概述

Validation, Data Binding, and Type Conversion

在Spring MVC中使用注解的方式校验RequestParams的更多相关文章

  1. Spring MVC 中采用注解方式 Action中跳转到另一个Action的写法

    Spring MVC 中采用注解方式 Action中跳转到另一个Action的写法 在Action中方法的返回值都是字符串行,一般情况是返回某个JSP,如: return "xx" ...

  2. Spring MVC 中 @ModelAttribute 注解的妙用

    Spring MVC 中 @ModelAttribute 注解的妙用 Spring MVC 提供的这种基于注释的编程模型,极大的简化了 web 应用的开发.其中 @Controller 和 @Rest ...

  3. spring 以及 spring mvc 中常用注解整理

    spring 以及 spring mvc 中常用注解整理 @RequestMapping(映射路径) @Autowired(注入 bean 对象) 例如: @Autowired private Bas ...

  4. Spring MVC中基于注解的 Controller

         终于来到了基于注解的 Spring MVC 了.之前我们所讲到的 handler,需要根据 url 并通过 HandlerMapping 来映射出相应的 handler 并调用相应的方法以响 ...

  5. 0001 - Spring MVC中的注解

    1.概述 Spring MVC框架提供了功能强大的注解,大大简化了代码开发的同时也提升了程序的可扩展性 2.注解 2.1.@RequestMapping Spring MVC通过@RequestMap ...

  6. Spring MVC中@RequestMapping注解使用技巧(转)

    @RequestMapping是Spring Web应用程序中最常被用到的注解之一.这个注解会将HTTP请求映射到MVC和REST控制器的处理方法上. 在这篇文章中,你将会看到@RequestMapp ...

  7. Spring MVC中@ControllerAdvice注解实现全局异常拦截

    在网上很多都把Advice翻译成增强器,其实从翻译工具上看到,这个单词翻译是忠告,通知的意思. 首先这个注解实在Spring Web包下,而Spring MVC离不开Spring Web的依赖,所以经 ...

  8. spring mvc中的注解说明

    注解扫描 context:component-scan 包扫描 <context:component-scan base-package="org.bdp"> < ...

  9. Spring Mvc如何通过注解的方式设置视图解析器的优先级

    <bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalRes ...

随机推荐

  1. 每天一个小算法(Shell Sort2)

    希尔排序: 伪代码: input: an array a of length n with array elements numbered 0 to n − 1 inc ← round(n/2) wh ...

  2. NDK(10)Android.mk各属性简介,Android.mk 常用模板

    参考 : http://blog.csdn.net/hudashi/article/details/7059006 本文内容: Android.mk简介, 各属性表, 常用Android.mk模板 1 ...

  3. 《OD大数据实战》HBase环境搭建

    一.环境搭建 1. 下载 hbase-0.98.6-cdh5.3.6.tar.gz 2. 解压 tar -zxvf hbase-0.98.6-cdh5.3.6.tar.gz -C /opt/modul ...

  4. How to install ruby on mac/ change ruby source in china

    his one is tailor made for the Basix users among you. If you've been itching to try out Ruby and/or ...

  5. [ ] 字符组(Character Classes) (转)

    []能够匹配所包含的一系列字符中的任意一个.需要注意的是,[]虽然能匹配其中的任意一个字符,但匹配的结果只能是一个字符,不是多个. 例如[abc]表示字符“a”或“b”或“c”. []支持用连字符“- ...

  6. 每天一个Linux命令(7): cp

    cp命令         该命令的功能是将给出的文件或目录拷贝到另一文件或目录中,同MSDOS下的copy命令一样,功能十分强大.         语法: cp [选项] 源文件或目录 目标文件或目录 ...

  7. 【转】Linux高级字符设备之Poll操作

    原文网址:http://www.cnblogs.com/geneil/archive/2011/12/04/2275559.html 在用户程序中,select()和poll()也是与设备阻塞与非阻塞 ...

  8. ArcGlobe点击IGlobeServerLayer图层读取信息

    ArcGISServer将点图层发布成Globe服务,AE开发中自定义识别工具,读取点数据信息. 1) 通过Locate方法获取图层对象,图层对象中的SearchOID就是你点中的要素Objectid ...

  9. 如何在MySql中记录SQL日志

    SQL server有一个sql profiler可以实时跟踪服务器执行的SQL语句,这在很多时候调试错误非常有用.例如:别人写的复杂代码.生产系统.无调试环境.无原代码... ...   查了一下资 ...

  10. Android服务之Service

    android中服务是运行在后台的东西,级别与activity差不多.既然说service是运行在后台的服务,那么它就是不可见的,没有界面的东西.你可以启动一个服务Service来播放音乐,或者记录你 ...