Spring Validation

Spring Validation模块用于表单数据验证配置,示例如下

依赖Jar包

        <dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>

Controller方法

    /**
* 添加酒店
* @param hotel
* @param bindingResult
* @return
*/
@RequestMapping(value = "/add")
// @Valid注释表示需要验证
public String addHotel(@Valid Hotel hotel,
BindingResult bindingResult,
Model model) {
if (hotel.getName() == null) {
// 显示添加页面
model.addAttribute(HOTEL, new Hotel());
return "hotel/addHotel";
} else {
// 验证失败时回到本页面并显示错误信息
if (bindingResult.hasErrors())
return "hotel/addHotel";
hotelService.addHotel(hotel);
return "redirect:/hotel/list";
}
}

需要验证的bean配置

package com.qunar.bean;

import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty; import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern; public class Hotel { private Integer id; @NotNull(message = "酒店代码不能为空")
@NotEmpty(message = "酒店代码不能为空")
@Pattern(regexp = "\\w+",
message = "酒店代码不能包含特殊字符")
@Length(max = 45, message = "酒店代码最长为45个字符")
private String code; @NotNull(message = "酒店名称不能为空")
@NotEmpty(message = "酒店名称不能为空")
@Pattern(regexp = "([\\u4e00-\\u9fa5]|\\w)+",
message = "酒店名称不能包含特殊字符")
@Length(max = 100, message = "酒店名称最长为100个字符")
private String name; public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getCode() {
return code;
} public void setCode(String code) {
this.code = code == null ? null : code.trim();
} public String getName() {
return name;
} public void setName(String name) {
this.name = name == null ? null : name.trim();
}
}

页面

<%--
Created by IntelliJ IDEA.
User: zhenwei.liu
Date: 13-7-30
Time: 上午11:50
To change this template use File | Settings | File Templates.
--%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="sf" uri="http://www.springframework.org/tags/form" %>
<%@ page contentType="text/html;charset=UTF-8" pageEncoding="utf-8" %>
<html>
<head>
<title>添加酒店</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
</head>
<body>
<sf:form action="/hotel/add" method="POST" modelAttribute="hotel">
<table>
<tr>
<td align="right">酒店代码</td>
<td><input type="text" name="code"/></td>
<td><sf:errors path="code" cssClass="error" /> </td>
</tr>
<tr>
<td align="right">酒店名称</td>
<td><input type="text" name="name"/></td>
<td><sf:errors path="name" cssClass="error" /> </td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="添加"/>
<input type="reset" value="重置"/></td>
</tr>
</table>
</sf:form>
</body>
</html>

这样当提交这个这个页面表单时,就会验证hotel的各个属性,如验证不通过则回到本页面并显示错误信息

另外,Spring支持自定义验证注解类,加入自己的验证规则,具体例子可以参考以下

http://outbottle.com/custom-annotated-validation-with-spring-3-web-mvc/

上一篇:vue项目eslint环境配置与vscode配置eslint


下一篇:kaggle之人脸特征识别