SpringMVC中实现数据的格式化

2025-10-31 18:50:20

1、在表单提交页面加入一个日期字段。

<%@page import="java.util.HashMap"%>

<%@page import="java.util.Map"%>

<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

    

<!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>

        <!--  

                1. WHY 使用 form 标签呢 ?

                可以更快速的开发出表单页面, 而且可以更方便的进行表单值的回显

                2. 注意:

                可以通过 modelAttribute 属性指定绑定的模型属性,

                若没有指定该属性,则默认从 request 域对象中读取 command 的表单 bean

                如果该属性值也不存在,则会发生错误。

        -->

        <form:form action="${pageContext.request.contextPath }/emp" method="POST" 

                modelAttribute="employee">

                

                <br>

                

                <c:if test="${employee.id == null }">

                        <!-- path 属性对应 html 表单标签的 name 属性值 -->

                        LastName: <form:input path="lastName"/>

                </c:if>

                <c:if test="${employee.id != null }">

                        <form:hidden path="id"/>

                        <input type="hidden" name="_method" value="PUT"/>

                        <%-- 对于 _method 不能使用 form:hidden 标签, 因为 modelAttribute 对应的 bean 中没有 _method 这个属性 --%>

                        <%-- 

                        <form:hidden path="_method" value="PUT"/>

                        --%>

                </c:if>

                

                

                <br>

                Email: <form:input path="email"/>

                <br>

                <% 

                        Map<String, String> genders = new HashMap();

                        genders.put("1", "Male");

                        genders.put("0", "Female");

                        

                        request.setAttribute("genders", genders);

                %>

                Gender: 

                <br>

                <form:radiobuttons path="gender" items="${genders }" delimiter="<br>"/>

                <br>

                Department: <form:select path="department.id" 

                        items="${departments }" itemLabel="departmentName" itemValue="id"></form:select>

                <br>

                

                Birth: <form:input path="birth"/>

                <br>

                Salary: <form:input path="salary"/>

                <br>

                <input type="submit" value="Submit"/>

        </form:form>

        

</body>

</html>

SpringMVC中实现数据的格式化

2、在SpringMVC控制层实现数据保存方法,并且打印employee。

package com.gwolf.springmvc.handlers;

import java.util.Map;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;

import org.springframework.validation.Errors;

import org.springframework.validation.FieldError;

import org.springframework.web.bind.WebDataBinder;

import org.springframework.web.bind.annotation.InitBinder;

import org.springframework.web.bind.annotation.ModelAttribute;

import org.springframework.web.bind.annotation.PathVariable;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.RequestParam;

import com.gwolf.springmvc.dao.DepartmentDao;

import com.gwolf.springmvc.dao.EmployeeDao;

import com.gwolf.springmvc.domain.Employee;

@Controller

public class EmployeeHandler {

        @Autowired

        private EmployeeDao employeeDao;

        

        @Autowired

        private DepartmentDao departmentDao;

        

        

        

        @RequestMapping(value="/emp", method=RequestMethod.POST)

        public String save(Employee employee){

                System.out.println("save: " + employee);

                

                employeeDao.save(employee);

                return "redirect:/emps";

        }

}

SpringMVC中实现数据的格式化

3、在我们页面执行表单提交。

当我们提交数据的时候,程序出现了一个400的错误,这是因为SpringMVC进行日期转化的时候没有告诉日期格式怎么转化。

SpringMVC中实现数据的格式化

SpringMVC中实现数据的格式化

4、修改实体类对象,给日期字段加上@DateTimeFormat注解说明。

package com.gwolf.springmvc.domain;

import java.util.Date;

import javax.validation.constraints.Past;

import org.hibernate.validator.constraints.Email;

import org.hibernate.validator.constraints.NotEmpty;

import org.springframework.format.annotation.DateTimeFormat;

import org.springframework.format.annotation.NumberFormat;

public class Employee {

        private Integer id;

        @NotEmpty

        private String lastName;

        @Email

        private String email;

        //1 male, 0 female

        private Integer gender;

        

        private Department department;

        

        @Past

        @DateTimeFormat(pattern="yyyy-MM-dd")

        private Date birth;

        

        @NumberFormat(pattern="#,###,###.#")

        private Float salary;

        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 Date getBirth() {

                return birth;

        }

        public void setBirth(Date birth) {

                this.birth = birth;

        }

        public Float getSalary() {

                return salary;

        }

        public void setSalary(Float salary) {

                this.salary = salary;

        }

        @Override

        public String toString() {

                return "Employee [id=" + id + ", lastName=" + lastName + ", email="

                                + email + ", gender=" + gender + ", department=" + department

                                + ", birth=" + birth + ", salary=" + salary + "]";

        }

        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;

        }

        public Employee() {

                // TODO Auto-generated constructor stub

        }

}

SpringMVC中实现数据的格式化

5、在SpringMVC中加上如下配置,这两个配置一定要按顺序配置,不然可能会有问题。

<mvc:default-servlet-handler/>

<mvc:annotation-driven></mvc:annotation-driven>

SpringMVC中实现数据的格式化

6、再次提交表单数据,查看我们的日期是否能够正确转化。

SpringMVC中实现数据的格式化

7、当类型转化出现异常的时候,我们可以通过BindingResult得到错误结果。

SpringMVC中实现数据的格式化

SpringMVC中实现数据的格式化

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢