spring MVC JSR303校验


pom.xml:

<!--jsr 303 验证-->
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-validator</artifactId>
      <version>5.4.1.Final</version>
    </dependency>


springmvc.xml:

 <!-- 装配自定义的类型转换器 -->
      <mvc:annotation-driven conversion-service="conversionService"/>

      <!-- 自定义的类型转换器 -->
      <bean id="conversionService"
            class="org.springframework.context.support.ConversionServiceFactoryBean">
            <property name="converters">
                  <list>
                        <bean class="util.StringToDate"
                              p:datePattern="yyyy-MM-dd"></bean>
                  </list>
            </property>
      </bean>


pojo:

package model;

import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotBlank;
import org.springframework.format.annotation.DateTimeFormat;

import javax.validation.constraints.Pattern;
import java.io.Serializable;
import java.util.Date;

public class User implements Serializable{

    @NotBlank(message = "登录名不能为空")
    private String loginName;

    @NotBlank(message = "密码不能为空")
    @Length(min=6,max = 8,message = "密码在6到8之间")
    private String password;

    private String userName;

    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date birthday;

    @Pattern(regexp = "[1][3,5-8][3,6,9][0-9]{8}",message = "无效电话")
    private String tel;

    @Email(message = "必须是合法的邮箱")
    private String email;

    public String getLoginName(){
        return loginName;
    }
    public void setLoginName(String loginName){
        this.loginName = loginName;
    }

    public String getPassword(){
        return password;
    }
    public void setPassword(String password){
        this.password = password;
    }

    public String getUserName(){
        return userName;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String getTel() {
        return tel;
    }

    public void setTel(String tel) {
        this.tel = tel;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public void setUserName(String userName){
        this.userName = userName;
    }
    public User(){}
    public User(String loginName , String password , String userName){
        this.password = password;
        this.loginName = loginName;
        this.userName = userName;
    }
    public User(String loginName , String password , String userName,Date birthday){
        this.password = password;
        this.loginName = loginName;
        this.userName = userName;
        this.birthday = birthday;
    }

    public User(String loginName,String password,String userName , Date birthday ,String tel , String email){
        this.loginName = loginName;
        this.password = password;
        this.userName = userName;
        this.birthday = birthday;
        this.tel = tel;
        this.email = email;
    }
}

自定义转换器:

package util;

import org.springframework.core.convert.converter.Converter;

import java.text.SimpleDateFormat;
import java.util.Date;

public class StringToDate  implements Converter<String,Date>{
    private String datePattern;
    public void setDatePattern(String datePattern){
        this.datePattern = datePattern;
    }
    //实现Converter后必须实现的方法
    public Date convert(String date) {
        try{
            SimpleDateFormat simpleDateFormat =  new SimpleDateFormat(this.datePattern);
            return simpleDateFormat.parse(date);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
}

控制层:

package controller;

import model.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;


@Controller
public class UserController {

    @RequestMapping(value="/{formName}")
    public String loginForm(
            @PathVariable String formName,
            Model model){
        User user = new User();
        model.addAttribute("user",user); //在request中一定要有user
        // 动态跳转页面
        return formName;
    }

    // 数据校验使用@Valid,后面跟着Errors对象保存校验信息
    @RequestMapping(value="/login",method=RequestMethod.POST)
    public String login(
            @Valid @ModelAttribute  User user,
            Errors  errors,
            Model model) {
        if(errors.hasErrors()){
            return "registForm";
        }
        model.addAttribute("user", user);
        return "successValid";
    }


}

成功页面:

<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2017/12/19 0019
  Time: 19:51
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>JSR303测试</title>
</head>
<body>
<h3>JSR303测试</h3>
登录名:${requestScope.user.loginName}<br>
密码:${requestScope.user.password}<br>
邮箱:${requestScope.user.email}<br>
手机:${requestScope.user.tel}<br>
生日:<fmt:formatDate value="${requestScope.user.birthday}" pattern="yyyy年MM月dd日"></fmt:formatDate><br>
</body>
</html>



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值