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 校验数据问题
我们会经常遇到一下问题,例如我在前端输入数据,把数据发送到和后台,我首先要校验这个数据, 比如说:前端必须输入一个日期类型的数据,后端才能正确接收,要是输入一个不是日期型的数据, 那么后端就要把数据打 ...
随机推荐
- nedb nodejs 数据库学习
// Type 1: In-memory only datastore (no need to load the database) var Datastore = require('nedb') ...
- 【转】PHP error_reporting() 错误控制函数功能详解
定义和用法: error_reporting() 设置 PHP 的报错级别并返回当前级别. 函数语法: error_reporting(report_level) 如果参数 level 未指定 ...
- JavaScript对象就是一组属性(方法)的集合
在JavaScript中,每个对象可以看作是多个属性(方法)的集合,引用一个属性(方法) 很简单,即: 对象名.属性(方法)名 除此之外,还可以用方括号的形式来引用: 对象名[“属性(方法)名”] 注 ...
- 找不到所需要的ndbm.h头文件
具体描述: 通过deb包安装gdbm之后,发现找不到所需要的ndbm.h头文件.但是你会发现一个叫gdbm-ndbm.h的文件,你只需要把文件名改成ndbm.h就可以了,当然需要一定权限. sudo ...
- 数字根(digital root)
来源:LeetCode 258 Add Dights Question:Given a non-negative integer num , repeatedly add all its digi ...
- mysql 10进制与35进制之间的转换 注意Power处理bigint的问题
35进制的目的是防止0和O造成的视觉误差 BEGIN DECLARE m_StrHex35 VARCHAR(100); -- 返回35进制表示的结果 DECLARE m_Remainder B ...
- 转:java日志组件介绍(common-logging,log4j,slf4j,logback )
原网址:http://www.blogjava.net/daiyongzhi/archive/2014/04/13/412364.html common-logging common-logging是 ...
- [jquery] jQuery jsTree V3.2.1 基础Demo
引入对应的文件: <link rel="stylesheet" href="../dist/themes/default/style.min.css" / ...
- @GeneratedValue - fancychendong的专栏 - 博客频道 - CSDN.NET
登录|注册 收藏成功 确定 收藏失败,请重新收藏 确定 标题 标题不能为空 网址 标签 摘要 公开 取消收藏 分享资讯 传PPT/文档 提问题 写博客 传资源 创建项目 创建代码片 设置昵称编辑自我介 ...
- [摘]Hibernate查询事务必要性
背景: 添加事务与否都不影响Hibernate的查询操作. 问题: 查询操作是否有必要添加事务? 答案1: Hibernate官方手册上建议任何操作(增删改查)都需要添加事务. 答案2: robbin ...