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 校验数据问题
我们会经常遇到一下问题,例如我在前端输入数据,把数据发送到和后台,我首先要校验这个数据, 比如说:前端必须输入一个日期类型的数据,后端才能正确接收,要是输入一个不是日期型的数据, 那么后端就要把数据打 ...
随机推荐
- JavaScript闭包演示
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8" /> <title&g ...
- java.sql.SQLException: Io 异常: Connection reset
当数据库连接池中的连接被创建而长时间不使用的情况下,该连接会自动回收并失效,但客户端并不知道,在进行数据库操作时仍然使用的是无效的数据库连接,这样,就导致客户端程序报“ java.sql.SQLExc ...
- hadoop(四): 本地 hbase 集群配置 Azure Blob Storage
基于 HDP2.4安装(五):集群及组件安装 创建的hadoop集群,修改默认配置,将hbase 存储配置为 Azure Blob Storage 目录: 简述 配置 验证 FAQ 简述: hadoo ...
- CSS命名规则
头:header 内容:content/container 尾:footer 导航:nav 侧栏:sidebar 栏目:column 页面外围控制整体布局宽度:wrapper 左右中:le ...
- [原]在Fedora 20环境下安装系统内核源代码
1.安装Kernel Headers(头文件) 通过安装kernel-devel RPM包就可以得到Kernel Headers,但默认情况下没有被Fedora 20安装.通过DVD ISO 或者 y ...
- [转]Java获取当前路径
1.利用System.getProperty()函数获取当前路径:System.out.println(System.getProperty("user.dir"));//user ...
- 轻量级开源内存数据库SQLite性能测试
[IT168 专稿]SQLite是一款轻型的数据库,它占用资源非常的低,同时能够跟很多程序语言相结合,但是支持的SQL语句不会逊色于其他开源数据库.它的设计目标是嵌入式的,而且目前已经在很多嵌入式产品 ...
- 51nod 1314 定位系统
一个国家有N个城市(标号为0~N-1),这N个城市恰好由N-1条道路连接在一起(即N个城市正好构成一个树状结构).这个国家的所有道路的长度都是1个长度单位.定义:两个城市间的距离是两个城市间的最短路的 ...
- 静态库不要strip 太厉害
根据strip的功能表示,strip经常用来去除目标文件中的一些符号表.调试符号表信息,减少包的大小.我自己做了一函数库,同样的代码生成了一个mylib.so和一个mylib.a文件,之后使用了 st ...
- 实现web数据同步的四种方式
http://www.admin10000.com/document/6067.html 实现web数据同步的四种方式 1.nfs实现web数据共享 2.rsync +inotify实现web数据同步 ...