Mingyang.net:用注解校验数据
注解校验依赖的是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:用注解校验数据的更多相关文章
- 使用@Validated校验数据(除数据库做辅助)
一.controller层 /** * 使用@Validated来进行校验 * @author HuangJingNa * @date 2019年12月23日 下午6:02:20 * * @param ...
- springmvc JSR303 Validate 注解式,校验数据
参考:http://www.cnblogs.com/liukemng/category/578644.html 先进行配置: <!-- 默认的注解映射的支持 --> <mvc:ann ...
- Java 自定义注解 校验指定字段对应数据库内容重复
一.前言 在项目中,某些情景下我们需要验证编码是否重复,账号是否重复,身份证号是否重复等... 而像验证这类代码如下: 那么有没有办法可以解决这类似的重复代码量呢? 我们可以通过自定义注解校验的方式去 ...
- SpringMVC使用@Valid注解进行数据验证
SpringMVC使用@Valid注解进行数据验证 from:https://blog.csdn.net/zknxx/article/details/52426771 我们在做Form表单提交的时 ...
- 解放生产力:Spring Boot的注解校验
关于对象入参的校验,我们可能第一个想到的就是在Controller层或者Service层增加很多if else的判断,如: if (user.getPassword() == "" ...
- struts2 校验数据的有效性 2种方式
Struts2的数据校验: 数据的校验分为客户端校验和服务器端两种: 客户端校验:JS完成的校验.(为了提升用户体验.减少用户的输入错误) 服务器端校验:在后台的校验.(必须的.) 手动编码进行校验: ...
- springboot~为Money类型添加最大值和最小值的注解校验
在spring框架里,为我们集成了很多校验注解,直接在字段上添加对应的注解即可,这些注解基本都是简单保留类型的,即int,long,float,double,String等,而如果你自己封装了新的类, ...
- @ConfigurationProperties注解对数据的自动封装
@ConfigurationProperties注解对数据的自动封装 @ConfigurationProperties可以对基本数据类型实现自动封装,可以封装格式为yyyy/MM/dd的日期 测试代码 ...
- Struts2 校验数据问题
我们会经常遇到一下问题,例如我在前端输入数据,把数据发送到和后台,我首先要校验这个数据, 比如说:前端必须输入一个日期类型的数据,后端才能正确接收,要是输入一个不是日期型的数据, 那么后端就要把数据打 ...
随机推荐
- 【转】C# 重写WndProc 拦截 发送 系统消息 + windows消息常量值(1)
C# 重写WndProc 拦截 发送 系统消息 + windows消息常量值(1) #region 截获消息 /// 截获消息 处理XP不能关机问题 protected ...
- PYTHON错误代码及解决办法
(1)用sklearn进行逻辑回归时,建立完模型,由于要预测的数据量很大,无法一次全部预测,只能每次预测一个样本数据, 在每次以列表形式输入数据进行预测时出现: /Users/donganlan/an ...
- ASP.NET 将数据生成PDF (二)
可以下载itextsharp(https://sourceforge.net/projects/itextsharp)下载,然后在工程中引用该控件,举例子如下 1 datatable 的内容转换为P ...
- [navicat] Navicat for Oracle Cannot load OCI DLL
1. 本地安装的是64位的Oracle,但由于Navicat仅支持32位的,因此我们还需下载一个32位的客户端. 2.
- Python中的日志管理Logging模块
1.基本的用法 import logging logging.debug('This is debug message') logging.info('This is info message') l ...
- 深入了解iPad上的MouseEvent【转】
iPad上没有鼠标,所以手指在触发触摸事件(TouchEvent)的时候,系统也会产生出模拟的鼠标事件(MouseEvent). 这对于普通网页的浏览需求而言,基本可以做到与PC端浏览器无明显 ...
- zend studio一些常用配置
zend studio 常用 配置 1.zend中添加注释是ctrl+slash,这个slash在哪里?如何来取消注释 slash是斜杠'/'那个键,就是在,.之后的那个. 进行注释是 ctrl+'/ ...
- Navicat 11使用技巧
入门 Navicat 是一个可多重连接的数据库管理工具,它可让你连接到 MySQL.Oracle.PostgreSQL.SQLite.SQL Server 和/或 MariaDB 数据库,让管理不同类 ...
- PL/SQL中查看列注释、列属性
- 两分钟彻底让你明白Android Activity生命周期(图文)!
大家好,今天给大家详解一下Android中Activity的生命周期,我在前面也曾经讲过这方面的内容,但是像网上大多数文章一样,基本都是翻译Android API,过于笼统,相信大家看了,会有一点点的 ...