Spring框架中的数据校验和表单错误消息提示

1.搭建练习环境

1.1引入jar包,配置web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">

    <!-- 配置字符编码过滤器 -->
    <filter>
        <filter-name>characterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!-- 处理PUT和DELETE等的请求 -->
    <filter>
        <filter-name>hiddenHttpMethodFilter</filter-name>
        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>hiddenHttpMethodFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!-- 核心控制器:作用,分发请求 -->
    <servlet>
        <servlet-name>springDispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:/springmvc-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>springDispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

​​​​1.2配置springmvc-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!-- 配置要扫描的包 -->
    <context:component-scan base-package="com.bestgo.springmvc"/>

    <!-- 视图解析器,默认为转发 -->
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <!-- 国际化 -->
    <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basename" value="i18n"/>
    </bean>

    <!-- 处理静态资源 -->
    <mvc:default-servlet-handler default-servlet-name="default"/>
    <mvc:annotation-driven/>
</beans>

1.3 新建Employee.java

package com.bestgo.springmvc.bean;

import com.bestgo.springmvc.bean.Department;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.format.annotation.NumberFormat;

import java.util.Date;

public class Employee {

    private Integer id;
    private String lastName;

    private String email;
    //1 male, 0 female
    private Integer gender;

    private Department department;

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

    @NumberFormat(pattern = "###,###.###")
    private double salary;

    public Employee() {
    }

    public Employee(Integer id, String lastName, String email, Integer gender, Department department, Date birthday, double salary) {
        this.id = id;
        this.lastName = lastName;
        this.email = email;
        this.gender = gender;
        this.department = department;
        this.birthday = birthday;
        this.salary = salary;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }

    public Date getBirthday() {
        return birthday;
    }

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

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

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

    public Integer getGender() {
        return gender;
    }

    public void setGender(Integer gender) {
        this.gender = gender;
    }

    public Department getDepartment() {
        return department;
    }

    public void setDepartment(Department department) {
        this.department = department;
    }

    public Employee(Integer id, String lastName, String email, Integer gender,
                    Department department) {
        super();
        this.id = id;
        this.lastName = lastName;
        this.email = email;
        this.gender = gender;
        this.department = department;
    }


    @Override
    public String toString() {
        return "Employee{" +
                "id=" + id +
                ", lastName='" + lastName + '\'' +
                ", email='" + email + '\'' +
                ", gender=" + gender +
                ", department=" + department +
                ", birthday=" + birthday +
                ", salary=" + salary +
                '}';
    }
}

1.4 新建Department.java

package com.bestgo.springmvc.bean;

public class Department {

    private Integer id;
    private String departmentName;

    public Department() {
    }

    public Department(int i, String string) {
        this.id = i;
        this.departmentName = string;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getDepartmentName() {
        return departmentName;
    }

    public void setDepartmentName(String departmentName) {
        this.departmentName = departmentName;
    }

    @Override
    public String toString() {
        return "Department [id=" + id + ", departmentName=" + departmentName
                + "]";
    }

}

1.5  新建EmployeeDao.java

package com.bestgo.springmvc.dao;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import com.bestgo.springmvc.bean.Department;
import com.bestgo.springmvc.bean.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public class EmployeeDao {

   private static Map<Integer, Employee> employees = null;

   @Autowired
   private DepartmentDao departmentDao;

   static{
      employees = new HashMap<Integer, Employee>();
      //只是为了测试,这里充当从数据库查询的数据
      employees.put(1001, new Employee(1001, "E-AA", "aa@163.com", 1, new Department(101, "D-AA")));
      employees.put(1002, new Employee(1002, "E-BB", "bb@163.com", 1, new Department(102, "D-BB")));
      employees.put(1003, new Employee(1003, "E-CC", "cc@163.com", 0, new Department(103, "D-CC")));
      employees.put(1004, new Employee(1004, "E-DD", "dd@163.com", 0, new Department(104, "D-DD")));
      employees.put(1005, new Employee(1005, "E-EE", "ee@163.com", 1, new Department(105, "D-EE")));
   }

   private static Integer initId = 1006;

   public void saveOrUpdate(Employee employee){
      if(employee.getId() == null){
         employee.setId(initId++);
      }

      employee.setDepartment(departmentDao.getDepartment(employee.getDepartment().getId()));
      employees.put(employee.getId(), employee);
   }

   public Collection<Employee> getAll(){
      return employees.values();
   }

   public Employee get(Integer id){
      return employees.get(id);
   }

   public void delete(Integer id){
      employees.remove(id);
   }
}

1.6 新建DepartmentDao.java

package com.bestgo.springmvc.dao;

import com.bestgo.springmvc.bean.Department;
import org.springframework.stereotype.Repository;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

@Repository
public class DepartmentDao {

    private static Map<Integer, Department> departments = null;

    static{
        departments = new HashMap<Integer, Department>();
        //只是为了测试,这里充当从数据库查询的数据
        departments.put(101, new Department(101, "D-AA"));
        departments.put(102, new Department(102, "D-BB"));
        departments.put(103, new Department(103, "D-CC"));
        departments.put(104, new Department(104, "D-DD"));
        departments.put(105, new Department(105, "D-EE"));
    }

    public Collection<Department> getDepartments(){
        return departments.values();
    }

    public Department getDepartment(Integer id){
        return departments.get(id);
    }

}

1.7  新建EmployeeHandler.java

package com.bestgo.springmvc.handler;

import com.bestgo.springmvc.bean.Department;
import com.bestgo.springmvc.bean.Employee;
import com.bestgo.springmvc.dao.DepartmentDao;
import com.bestgo.springmvc.dao.EmployeeDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;
import java.util.Map;

@Controller
@RequestMapping("/employee")
public class EmployeeHandler {

    @Autowired
    private EmployeeDao employeeDao;

    @Autowired
    private DepartmentDao departmentDao;

    @RequestMapping(value = "/get_employee_list",method = RequestMethod.GET)
    public String getEmployeeList(Map map){
        Collection<Employee> empList = employeeDao.getAll();
        map.put("empList",empList);
        return "list";
    }

    @RequestMapping("/to_add_emp")
    public String toAddEmp(Map map){
        Collection<Department> departments = departmentDao.getDepartments();
        map.put("deptList",departments);
        map.put("command",new Employee());
        return "add";
    }

    @RequestMapping("/do_add_emp")
    public String doAddEmp(Employee employee){
        System.out.println("要添加的员工对象--》"+employee);
        employeeDao.saveOrUpdate(employee);
        return  "redirect:get_employee_list";
    }

    @RequestMapping(value = "/delete_emp/{id}",method = RequestMethod.DELETE)
    public String deleteEmp(@PathVariable("id") Integer id){
        employeeDao.delete(id);
        return  "redirect:/employee/get_employee_list";
    }

    @RequestMapping(value = "/to_update_emp/{id}",method = RequestMethod.GET)
    public String toUpdateEmp(@PathVariable("id") Integer id,Map map){
        Employee employee = employeeDao.get(id);
        map.put("employee",employee);
        Collection<Department> departments = departmentDao.getDepartments();
        map.put("departments",departments);
        return  "update";
    }

    @RequestMapping(value = "/do_update_emp",method = RequestMethod.PUT)
    public String doUpdateEmp(Employee employee){
        employeeDao.saveOrUpdate(employee);
        return  "redirect:/employee/get_employee_list";
    }

    @ModelAttribute
    public void getEmployee(@RequestParam(value = "id",required = false)Integer id,Map map){
        if(id != null){
            Employee employee = employeeDao.get(id);
            map.put("employee",employee);
        }

    }
}

1.8 新建web/index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
       <a href="${pageContext.request.contextPath}/employee/get_employee_list">getEmployeeList</a>
  </body>
</html>

1.9 新建web/WEB-INF/views/list.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ 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>Insert title here</title>
    <script type="application/javascript" src="${pageContext.request.contextPath}/scripts/jquery-1.9.1.min.js"></script>
    <script type="application/javascript">
        $(function(){
            $(".deleteEmp").click(function(){
                var href = this.href;
                $("#deleteEmpForm").attr("action",href).submit();
                return false;
            });
        });
    </script>
</head>
<body>

员工列表:<a href="${pageContext.request.contextPath }/employee/to_add_emp">添加员工</a>
<hr>
    <table width="80%" border="1">
        <tr>
            <th>员工编号</th>
            <th>员工名称</th>
            <th>邮件地址</th>
            <th>性别</th>
            <th>部门名称</th>
            <th></th>
            <th></th>
        </tr>
        <form id="deleteEmpForm" action="" method="post">
            <input type="hidden" name="_method" value="delete">
        </form>
        <c:forEach items="${empList}" var="emp">
            <tr>
                <td>${emp.id }</td>
                <td>${emp.lastName }</td>
                <td>${emp.email }</td>
                <td>${emp.gender==1?"男":"女" }</td>
                <td>${emp.department.departmentName }</td>
                <td><a href="${pageContext.request.contextPath}/employee/to_update_emp/${emp.id}">修改</a></td>
                <td><a class="deleteEmp" href="${pageContext.request.contextPath}/employee/delete_emp/${emp.id}">删除</a></td>
            </tr>
        </c:forEach>

    </table>
</body>
</html>

1.10 新建web/WEB-INF/add.jsp

<%@ page import="java.util.Map" %>
<%@ page import="java.util.HashMap" %>
<%@ 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>Insert title here</title>
</head>
<body>
    <%
        Map map = new HashMap();
        map.put("1","男");
        map.put("0","女");
        request.setAttribute("genders",map);
    %>
    <form:form action="${pageContext.request.contextPath}/employee/do_add_emp">
        员工名称:<form:input path="lastName"/><br>
        邮件地址:<form:input path="email"/><br>
        性别:<form:radiobuttons path="gender" items="${genders}"/><br>
        部门:<form:select path="department.id" items="${deptList}" itemLabel="departmentName" itemValue="id"/><br>
        生日:<form:input path="birthday"/><br>
        工资:<form:input path="salary"/><br>
        <input type="submit" value="添加">
    </form:form>
</body>
</html>

 

2.点击运行,开始。。然后进入员工列表页面

3.点击【添加员工】,进入添加员工页面,并输入信息

4.点击【添加】,成功后,跳入到列表页面

5.但是如果输入错误,会报400的错误,页面会显得不是很友好,也没有回到添加页面,这时就需要数据校验、回显和错误消息提示

6. 首先修改EmployeeHandler.java

@RequestMapping("/to_add_emp")
public String toAddEmp(Map map){
   Collection<Department> departments = departmentDao.getDepartments();
   map.put("deptList",departments);
   map.put("employee",new Employee());
   return "add";
}

@RequestMapping("/do_add_emp")
public String doAddEmp(Employee employee, BindingResult bindingResult, Map map){
   if(bindingResult.getErrorCount() > 0){
      System.out.println("类型转换错误!");
      List<FieldError> fieldErrors = bindingResult.getFieldErrors();
      for(FieldError fieldError : fieldErrors){
         System.out.println(fieldError.getField() + "-" + fieldError.getDefaultMessage());
      }
      Collection<Department> departments = departmentDao.getDepartments();
      map.put("deptList",departments);
      return "add";
   }
   employeeDao.saveOrUpdate(employee);
   return  "redirect:get_employee_list";
}

7.  然后修改add.jsp的form表单

<form:form action="${pageContext.request.contextPath}/employee/do_add_emp" modelAttribute="employee">
   员工名称:<form:input path="lastName"/><br>
   邮件地址:<form:input path="email"/><br>
   性别:<form:radiobuttons path="gender" items="${genders}"/><br>
   部门:<form:select path="department.id" items="${deptList}" itemLabel="departmentName" itemValue="id"/><br>
   生日:<form:input path="birthday"/><br>
   工资:<form:input path="salary"/><br>
   <input type="submit" value="添加">
</form:form>

 

8. 此时再次验证,后台报错,可以回显了。但是注册用户不知道发生了什么。。。这时就需要显示错误提示

 

9.在Employee.java里面添加注解@NotEmpty,不为空;@Email,验证是否为邮箱格式;@Past,必须是一个过去的时间

10.在EmployeeHandler.java里面要校验的类上,加上@Vaild注解

11.测试,会有如下显示

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

朱梦君

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值