注解校验依赖的是javax.validation和hibernate-validaton。

<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.0.1.Final</version>
</dependency>

激活Spring的注解驱动:

<mvc:annotation-driven />

定义数据模型:

public class Subscriber {

    @Size(min=2, max=30)
private String name; @NotEmpty @Email
private String email; @NotNull @Min(13) @Max(110)
private Integer age; @Size(min=10)
private String phone; @NotNull
private Gender gender; @DateTimeFormat(pattern="MM/dd/yyyy")
@NotNull @Past
private Date birthday; ...
}

在控制器中用@Valid定义数据模型:

@Controller
public class FormController { ... @RequestMapping(value="form", method=RequestMethod.POST)
public String submitForm(@Valid Subscriber subscriber, BindingResult result, Model m) {
if(result.hasErrors()) {
return "formPage";
} m.addAttribute("message", "Successfully saved person: " + subscriber.toString());
return "formPage";
}
}

在视图中用<form:errors>显示错误信息:

<form:form action="/form" modelattribute="subscriber">
<label for="nameInput">Name: </label>
<form:input path="name" id="nameInput"></form:input>
<form:errors path="name" cssclass="error"></form:errors>
<br /> <label for="ageInput">Age: </label>
<form:input path="age" id="ageInput"></form:input>
<form:errors path="age" cssclass="error"></form:errors>
<br /> <label for="phoneInput">Phone: </label>
<form:input path="phone" id="phoneInput"></form:input>
<form:errors path="phone" cssclass="error"></form:errors>
<br /> <label for="emailInput">Email: </label>
<form:input path="email" id="emailInput"></form:input>
<form:errors path="email" cssclass="error"></form:errors>
<br /> <label for="birthdayInput">Birthday: </label>
<form:input path="birthday" id="birthdayInput" placeholder="MM/DD/YYYY">
<form:errors path="birthday" cssclass="error"></form:errors>
<br /> <label for="genderOptions">Gender: </label>
<form:select path="gender" id="genderOptions">
<form:option value="">Select Gender</form:option>
<form:option value="MALE">Male</form:option>
<form:option value="FEMALE">Female</form:option>
</form:select>
<form:errors path="gender" cssclass="error"></form:errors>
<br /> <label for="newsletterCheckbox">Newsletter? </label>
<form:checkbox path="receiveNewsletter" id="newsletterCheckbox"></form:checkbox>
<form:errors path="receiveNewsletter" cssclass="error"></form:errors>
<br /><br />
<input type="submit" value="Submit" />
</form:input></form:form>

如何定义校验信息?最简单的方式是用message参数:

@Size(min=10, message="Phone number must be at least 10 characters")

但是这不能实现国际化文字处理。用messageSource可以实现国际化文字:

<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages"/>
</bean>

然后在src/main/resources下建立messages.properties,用下面的格式覆盖默认的校验信息:

{ValidationClass}.{modelObjectName}.{field}

例如:

Size=the {0} field must be between {2} and {1} characters long
Size.subscriber.name=Name must be between {2} and {1} characters
Size.subscriber.phone=Phone must be at least {2} characters Min.subscriber.age=You must be older than {1}
Max.subscriber.age= Sorry, you have to be younger than {1} Email=Email address not valid
Past=Date must be in the past NotEmpty=Field cannot be left blank
NotNull=Field cannot be left blank typeMismatch=Invalid format
methodInvocation.myRequest.amount=Invalid format

注意下面这段话,说明了搜索校验信息的顺序:

For example, if the age field of our “subscriber” model object fails the “NotNull” validation, the “NotNull.subscriber.age” message would be looked up. If the message isn’t found, “NotNull.subscriber” would be looked for. Finally, if not found, “NotNull” message would be looked for. If that also isn’t found, the default message (what we saw above) would be rendered. 

http://codetutr.com/2013/05/28/spring-mvc-form-validation/

Mingyang.net:用注解校验数据的更多相关文章

  1. 使用@Validated校验数据(除数据库做辅助)

    一.controller层 /** * 使用@Validated来进行校验 * @author HuangJingNa * @date 2019年12月23日 下午6:02:20 * * @param ...

  2. springmvc JSR303 Validate 注解式,校验数据

    参考:http://www.cnblogs.com/liukemng/category/578644.html 先进行配置: <!-- 默认的注解映射的支持 --> <mvc:ann ...

  3. Java 自定义注解 校验指定字段对应数据库内容重复

    一.前言 在项目中,某些情景下我们需要验证编码是否重复,账号是否重复,身份证号是否重复等... 而像验证这类代码如下: 那么有没有办法可以解决这类似的重复代码量呢? 我们可以通过自定义注解校验的方式去 ...

  4. SpringMVC使用@Valid注解进行数据验证

    SpringMVC使用@Valid注解进行数据验证   from:https://blog.csdn.net/zknxx/article/details/52426771 我们在做Form表单提交的时 ...

  5. 解放生产力:Spring Boot的注解校验

    关于对象入参的校验,我们可能第一个想到的就是在Controller层或者Service层增加很多if else的判断,如: if (user.getPassword() == "" ...

  6. struts2 校验数据的有效性 2种方式

    Struts2的数据校验: 数据的校验分为客户端校验和服务器端两种: 客户端校验:JS完成的校验.(为了提升用户体验.减少用户的输入错误) 服务器端校验:在后台的校验.(必须的.) 手动编码进行校验: ...

  7. springboot~为Money类型添加最大值和最小值的注解校验

    在spring框架里,为我们集成了很多校验注解,直接在字段上添加对应的注解即可,这些注解基本都是简单保留类型的,即int,long,float,double,String等,而如果你自己封装了新的类, ...

  8. @ConfigurationProperties注解对数据的自动封装

    @ConfigurationProperties注解对数据的自动封装 @ConfigurationProperties可以对基本数据类型实现自动封装,可以封装格式为yyyy/MM/dd的日期 测试代码 ...

  9. Struts2 校验数据问题

    我们会经常遇到一下问题,例如我在前端输入数据,把数据发送到和后台,我首先要校验这个数据, 比如说:前端必须输入一个日期类型的数据,后端才能正确接收,要是输入一个不是日期型的数据, 那么后端就要把数据打 ...

随机推荐

  1. Java C# 加密解密类库

    Bouncy Castle 是一种用于 Java 平台的开放源码的轻量级密码术包.它支持大量的密码术算法,并提供 JCE 1.2.1 的实现.因为 Bouncy Castle 被设计成轻量级的,所以从 ...

  2. Log4j 使用总结

    在实际编程时,要使Log4j真正在系统中运行事先还要对配置文件进行定义.定义步骤就是对Logger.Appender及Layout的分别使用.Log4j支持两种配置文件格式,一种是XML格式的文件,一 ...

  3. 《腾讯敏捷框架TAPD》研究

    1         框架结构 1.1         产品 TAPD采用FDD模式开发,FDD即特征驱动开发. FDD的核心是面向产品的功能点,但这个功能点是从客户角度出发的,并不是从系统角度出来的. ...

  4. MyEclipse配置Resin启动报错问题

    错误信息如下: com.caucho.config.ConfigException: -server 'default' is an unknown server in the configurati ...

  5. 将Excel数据导入Oracle中

    第一步:修改Excel 1.将Excel的表头修改为目标数据库中表的字段名 2.去重(如果有需要的话) 删除Excel表中的重复数据: 选择去重的列: 删除成功后提示: 第二步:将修改后的Excel另 ...

  6. Java连接Oracle

    Process myProcess = Runtime.getRuntime().exec("ipconfig"); InputStreamReader ir = new Inpu ...

  7. jquery.find()

    http://www.365mini.com/page/jquery-find.htm

  8. jQuery validate在没有校验通过的情况下拒绝提交

    下面通过一个简单的例子说明,这个问题,可能是很多人遇到的,验证不通过的时候,依然提交了表单. HTML <form class="survey" id="surve ...

  9. HttpSessionBindingListener和HttpSessionAttributeListener区别 - gengkunpeng的专栏 - 博客频道 - CSDN.NET

    分享到 一键分享 QQ空间 新浪微博 百度云收藏 人人网 腾讯微博 百度相册 开心网 腾讯朋友 百度贴吧 豆瓣网 搜狐微博 百度新首页 QQ好友 和讯微博 更多... 百度分享 HttpSession ...

  10. jquery radio的取值 radio的选中 radio的重置

    radio 按钮组, name=”sex”. <input type="radio" name="sex" value="Male"& ...