使用Spring form标签进行服务器上的数据校验,可以防止用户通过禁用JavaScript来跳过表单校验直接访问后台,提高了系统的安全性
工具包下载:https://wws.lanzous.com/iNlnGilbzte
然后导入包
在校验的字段上利用注解编写校验条件
User.java
import java.util.Date;
import org.hibernate.validator.constraints.Length;
import org.springframework.format.annotation.DateTimeFormat;
import com.sun.istack.internal.NotNull;
public class User {
private Integer id;
private String userName;
private String password;
private String repassword;
private String height;
private String email;
private Date birth;
@Override
public String toString() {
return "User [id=" + id + ", userName=" + userName + ", password=" + password + ", repassword=" + repassword
+ ", height=" + height + ", email=" + email + ", birth=" + birth + "]";
}
@DateTimeFormat(pattern="yyyy-MM-dd")
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
public User() {
super();
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@NotNull //不为空
@Length(min=4,max=16) //长度
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRepassword() {
return repassword;
}
public void setRepassword(String repassword) {
this.repassword = repassword;
}
public String getHeight() {
return height;
}
public void setHeight(String height) {
this.height = height;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
在控制器中使用@Valid注解
import java.util.List;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import com.gd.cn.dao.entity.User;
@Controller
public class ValidatorContorller {
///@Valid 想要输出校验不符合条件的错误信息就要加上这个注解
@RequestMapping("/testvalidator/validate")
public String validated(@Valid User user,Errors errors) {
//从前端接到的数据,用包含了这些字段的对象封装起来
System.out.println(user);
//获取不匹配的结果 用集合装着
List<FieldError> fieldErrors = errors.getFieldErrors();
//遍历不匹配的错误结果
if (errors.hasErrors()) {
for (FieldError fieldError : fieldErrors) {
//在控制台输出出错误
System.out.println(fieldError.getDefaultMessage());
}
return "testvalidator1";
}
//校验正确不会进入循环,跳转到相应的界面
return "pv";
}
}
我们还可以用spring mvc的form标签输出错误到页面上
引入文件,在想要显示的页面头部添加前缀
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
修改标签
选择输出错误的位置