概述

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. How to: Write Object Data to an XML File

    This example writes the object from a class to an XML file using the XmlSerializer class. Namespace: ...

  2. cdoj 1342 郭大侠与甲铁城 树状数组+离线

    郭大侠与甲铁城 Time Limit: 1500/800MS (Java/Others)     Memory Limit: 65535/65535KB (Java/Others) Submit St ...

  3. gulp使用外部配置文件

    这很有好处,因为它使得任务很干净,并且 config.json 可以被其他的任务运行器(例如grunt)重复利用. config.json { "desktop" : { &quo ...

  4. jsonp获取服务器数据的方式

    jsonp获取服务器的数据,有两种 一,跨域 二,不跨域 如果跨域 js的写法有两种 1, <script type="text/javascript"> $(func ...

  5. EF5&MVC4 学习1、创建新的Contoso University Application,并创建Model Class 生成对应的database

    参考:http://www.asp.net/mvc/tutorials/getting-started-with-ef-5-using-mvc-4/creating-an-entity-framewo ...

  6. 编译安装apache+php(加常见问题解决)

    [编译apache]./configure --prefix=/usr/local/lamp/httpd -with-apr=/usr/local/apr -with-apr-util=/usr/lo ...

  7. 简单使用Junit

    不需要配置,导入相应jar,然后在测试的方法上面加入注解@Test 执行的时候选择junit即可.

  8. id to load is required for loading----id被要求加载exception

    表示id主键 没有找到,可能是数据库中的主键设置了not null 而你没有给予主键 还有就是没有传递主键到 数据库中

  9. valueOf intValue parsetInt区别

    1.int intValue() 以 int 类型返回该 Integer 的值. Long l = 123; l.intValue() ---->int : 123 2.static int p ...

  10. dede 首页调用单页->栏目内容

    {dede:sql sql='Select content from dede_arctype where id=47'} [field:content/] {/dede:sql}