美文网首页
springMVC数据校验 Day32 2018-12-22

springMVC数据校验 Day32 2018-12-22

作者: Ernest_Chou | 来源:发表于2018-12-22 20:52 被阅读0次

springMVC数据校验

1. spring的validation校验

Spring校验框架在org.springframework.validation包中。

LocalValidatorFactoryBean即实现了Spring的validator接口,也实现了JSr 303validator接口。只需要在Spring容器中定义一个LocalValidatorFactoryBean,即可将其注入到需要数据校验的Bean中:

<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>

<mvc:annotation-driven>会默认装配好一个LocalValidatorFactoryBean,不需手动配置。

1.1 实现Spring的Validator接口

  • UserValidator.java
//实现Spring的Validator接口
@Repository("userValidator")
public class UserValidator implements Validator {
    
    // 该校验器能够对clazz类型的对象进行校验。
    @Override
    public boolean supports(Class<?> clazz) {
        // User指定的 Class 参数所表示的类或接口是否相同,或是否是其超类或超接口
        return User.class.isAssignableFrom(clazz);
    }
    // 对目标类target进行校验,并将校验错误记录在errors当中
    @Override
    public void validate(Object target, Errors errors) {
        /**
        使用ValidationUtils中的一个静态方法rejectIfEmpty()来对loginname属性进行校验,
        假若'loginname'属性是 null 或者空字符串的话,就拒绝验证通过 。
        */
        ValidationUtils.rejectIfEmpty(errors, "loginName", null, "登录名不能为空");  
        ValidationUtils.rejectIfEmpty(errors, "password", null, "密码不能为空");  
        User user = (User)target;
        if(user.getLoginName().length() > 10){
            // 使用Errors的rejectValue方法验证
            errors.rejectValue("loginName", null, "用户名不能超过10个字符");
        }
        if(user.getPassword() != null 
                && !user.getPassword().equals("") 
                && user.getPassword().length() < 6){
            errors.rejectValue("password", null, "密码不能小于6位");
        }

    }

}

1.2 Controller层

  • UserController.java
@Controller(value="validatorUserController")
@RequestMapping(value="/validatorTest")
public class UserController {
    private static final Log logger = LogFactory.getLog(UserController.class);
     
    // 注入UserValidator对象
    @Autowired
    @Qualifier("userValidator")
    private UserValidator userValidator;
    
    @RequestMapping(value="/{formName}")
     public String loginForm(
             @PathVariable String formName,
             Model model){
        User user = new User();
        model.addAttribute("user",user);
        // 动态跳转页面
        return "validatorTest/"+formName;
    }
     
     @RequestMapping(value="/login",method=RequestMethod.POST)
     public String login(
             @ModelAttribute User user,
             Model model,
             Errors errors) {
         logger.info(user);
         model.addAttribute("user", user);
         // 调用userValidator的验证方法
         userValidator.validate(user, errors);
         // 如果验证不通过跳转到loginForm视图
         if(errors.hasErrors()){
             return "validatorTest/"+"loginForm";
         }
         return "validatorTest/"+"success";
     }
}

1.3 springmvc配置

<!-- 注意扫描范围需要把validator接口实现类扫描进去 -->
<context:component-scan base-package="com.zhougl.web" />
<mvc:annotation-driven />

1.4 jsp

1.4.1 loginForm.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib prefix= "form" uri= "http://www.springframework.org/tags/form" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>测试Validator接口验证</title>
</head>
<body>
<h3>登录页面</h3>
<!-- 绑定user -->
<form:form modelAttribute="user" method="post" action="login" >
    <table>
        <tr>
            <td>登录名:</td>
            <td><form:input path="loginName"/></td>
            <!-- 显示loginName属性的错误信息 -->
            <td><form:errors path="loginName" cssStyle= "color:red"/></td>
        </tr>
        <tr>
            <td>密码:</td>
            <td><form:input path="password"/></td>
            <!-- 显示password属性的错误信息 -->
            <td><form:errors path="password" cssStyle= "color:red"/></td>
        </tr>
        <tr>
            <td><input type="submit" value="提交"/></td>
        </tr>
    </table>
</form:form>
</body>
</html>
1.4.2 success.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>测试ConversionService</title>
</head>
<body>
登录名:${requestScope.user.loginName }<br>
登录名:${requestScope.user.password }<br>
</body>
</html>

2. Hibernate Validator校验(JSR 303校验)

  • JSR 303校验定义的注解:
注解 功能
@Null 被注释的元素必须为 null
@NotNull 被注释的元素必须不为 null
@AssertTrue 被注释的元素必须为 true
@AssertFalse 被注释的元素必须为 false
@Min(value) 被注释的元素必须是一个数字,其值必须大于等于指定的最小值
@Max(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值
@DecimalMin(value) 被注释的元素必须是一个数字,其值必须大于等于指定的最小值
@DecimalMax(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值
@Size(max=, min=) 被注释的元素的大小必须在指定的范围内
@Digits (integer, fraction) 被注释的元素必须是一个数字,其值必须在可接受的范围内
@Past 被注释的元素必须是一个过去的日期
@Future 被注释的元素必须是一个将来的日期
@Pattern(regex=,flag=) 被注释的元素必须符合指定的正则表达式
  • Hibernate Validator 附加的 constraint
注解 功能
@NotBlank(message =) 验证字符串非null,且被trim的长度必须大于0,对字符串会去掉前后空格
@Email 被注释的元素必须是电子邮箱地址
@Length(min=,max=) 被注释的字符串的大小必须在指定的范围内
@NotEmpty 被注释的字符串的必须非空(NUL、EMPTY)。用于Array、Collection、Map、String
@Range(min=,max=,message=) 被注释的元素必须在合适的范围内
@URL 验证是否是合法的url
@CreditCardNumber 验证是否是合法的信用卡号码

2.1 引入jar包

  • pom.xml
<dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>5.3.5.Final</version>
    </dependency>

2.2 注解实体类

2.2.1 User.java(含错误信息)
public class User implements Serializable {
    @NotBlank(message="登录名不能为空")
    private String loginname;
    
    @NotBlank(message="密码不能为空")
    @Length(min=6,max=8,message="密码长度必须在6位到8位之间")
    private String password;
    
    @NotBlank(message="用户名不能为空")
    private String username;
    
    @Range(min=15, max=60,message="年龄必须在15到60岁之间")
    private int age;
    
    @Email(message="必须是合法的邮箱地址")
    private String email;
    
    @DateTimeFormat(pattern="yyyy-MM-dd")
    @Past(message="生日必须是一个过去的日期")
    private Date birthday;
    
    @Pattern(regexp="^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\\d{8}$",message="无效的电话号码")
    private String phone;
    //省略get/set方法
}
2.2.2User.java(错误信息存文件,国际化)
public class User implements Serializable {
    @NotBlank
    private String loginname;
    
    @NotBlank
    @Length(min=6,max=8)
    private String password;
    
    @NotBlank
    private String username;
    
    @Range(min=15, max=60)
    private int age;
    
    @Email
    private String email;
    
    @DateTimeFormat(pattern="yyyy-MM-dd")
    @Past
    private Date birthday;
    
    @Pattern(regexp="[1][3,8][3,6,9][0-9]{8}")
    private String phone;
    //省略get/set方法
}

2.3 Controller控制层

@Controller
@RequestMapping(value="/jsrValidatorTest")
public class HibernateValidatorController {
private static final Log logger = LogFactory.getLog(UserController.class);
    
    @RequestMapping(value="/{formName}")
     public String loginForm(
             @PathVariable String formName,
             Model model){
        User user = new User();
        model.addAttribute("user",user);
        // 动态跳转页面
        return "jsrValidatorTest/"+formName;
    }
     
    // 数据校验使用@Valid,后面跟着Errors对象保存校验信息
     @RequestMapping(value="/login",method=RequestMethod.POST)
     public String login(
             @Valid @ModelAttribute  User user,
             Errors  errors,
             Model model) {
         logger.info(user);
         if(errors.hasErrors()){
             return  "jsrValidatorTest/"+"registerForm";
         }
         model.addAttribute("user", user);
         return  "jsrValidatorTest/"+"success";
     }
}

2.4 springmvc配置

  • springmvc-config.xml
<context:component-scan base-package="com.zhougl.web" />
<mvc:annotation-driven />

<!-- 国际化 -->  
    <bean id="messageSource"    class="org.springframework.context.support.ResourceBundleMessageSource"> 
        <!-- 国际化资源文件名 -->
        <property name="basenames" value="message"/>
    </bean> 

2.5 jsp

2.5.1 registerForm.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib prefix= "form" uri= "http://www.springframework.org/tags/form" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>测试JSR 303</title>
</head>
<body>
<h3>注册页面</h3>
<form:form modelAttribute="user" method="post" action="login" >
    <table>
        <tr>
            <td>登录名:</td>
            <td><form:input path="loginname"/></td>
            <td><form:errors path="loginname" cssStyle= "color:red"/></td>
        </tr>
        <tr>
            <td>密码:</td>
            <td><form:input path="password"/></td>
            <td><form:errors path="password" cssStyle= "color:red"/></td>
        </tr>
        <tr>
            <td>用户名:</td>
            <td><form:input path="username"/></td>
            <td><form:errors path="username" cssStyle= "color:red"/></td>
        </tr>
        <tr>
            <td>年龄:</td>
            <td><form:input path="age"/></td>
            <td><form:errors path="age" cssStyle= "color:red"/></td>
        </tr>
        <tr>
            <td>邮箱:</td>
            <td><form:input path="email"/></td>
            <td><form:errors path="email" cssStyle= "color:red"/></td>
        </tr>
        <tr>
            <td>生日:</td>
            <td><form:input path="birthday"/></td>
            <td><form:errors path="birthday" cssStyle= "color:red"/></td>
        </tr>
        <tr>
            <td>电话:</td>
            <td><form:input path="phone"/></td>
            <td><form:errors path="phone" cssStyle= "color:red"/></td>
        </tr>
        <tr>
            <td><input type="submit" value="提交"/></td>
        </tr>
    </table>
</form:form>
</body>
</html>
2.5.2 success.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>测试JSR 303</title>
</head>
<body>
<h3>测试JSR 303</h3>
登录名:${requestScope.user.loginname }<br>
密码:${requestScope.user.password }<br>
用户名:${requestScope.user.username }<br>
年龄:${requestScope.user.age }<br>
邮箱:${requestScope.user.email }<br>
生日:<fmt:formatDate value="${requestScope.user.birthday}" 
    pattern="yyyy年MM月dd日"/><br>
电话:${requestScope.user.phone }<br>
</body>
</html>

相关文章

网友评论

      本文标题:springMVC数据校验 Day32 2018-12-22

      本文链接:https://www.haomeiwen.com/subject/ddkbkqtx.html