Spring框架中@DateTimeFormat和@NumberFormat的用法

    @DateTimeFormat是用来验证输入的日期格式;@NumberFormat是用来验证输入的数字格式。有时候,因为输入习惯或某些要求必须改变格式的时候,它们就该上场了。

1. 搭建练习环境

   1.1 搭建SpringMVC环境,配置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 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;

    private Date birthday;

    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", "[email protected]", 1, new Department(101, "D-AA")));
      employees.put(1002, new Employee(1002, "E-BB", "[email protected]", 1, new Department(102, "D-BB")));
      employees.put(1003, new Employee(1003, "E-CC", "[email protected]", 0, new Department(103, "D-CC")));
      employees.put(1004, new Employee(1004, "E-DD", "[email protected]", 0, new Department(104, "D-DD")));
      employees.put(1005, new Employee(1005, "E-EE", "[email protected]", 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.点击【添加】,此时会报400错误。此时是因为格式转换异常

5.退到添加员工的页面,重新输入新的格式

6.此时会发现通过了添加,并显示了列表页面。说明框架默认日期格式为yyyy/MM/dd;数字格式默认除了点,不能有其他特殊符号

7.但是我想输入的日期格式为"yyyy-MM-dd",输入的数字格式以逗号分隔,比如“222333.55”,分隔为"222,333.55"。那么就要用到@DateTimeFormat(pattern="yyyy-MM-dd")和NumberFormat(pattern="###,###.###"),在Employee.java中加入

8.再次添加员工信息,按照指定的格式输入

9.此时就会通过了,完美!

发布了12 篇原创文章 · 获赞 12 · 访问量 5506

猜你喜欢

转载自blog.csdn.net/qq_30426943/article/details/79520277