Spring框架中@DateTimeFormat和@NumberFormat的用法
@DateTimeFormat是用來驗證輸入的日期格式;@NumberFormat是用來驗證輸入的數字格式。有時候,因為輸入習慣或某些要求必須改變格式的時候,它們就該上場了。
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>
(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>(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 + '}'; } }
(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 + "]"; } }(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); } }
(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); } }
(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); } } }
(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>
(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>
(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.此時就會通過了,完美!
相關推薦
Spring框架中@DateTimeFormat和@NumberFormat的用法
@DateTimeFormat是用來驗證輸入的日期格式;@NumberFormat是用來驗證輸入的數字格式。有時候,因為輸入習慣或某些要求必須改變格式的時候,它們就該上場了。1.搭建練習環境(1)搭建SpringMVC環境,配置web.xml<?xml vers
詳解Java的Spring框架中的註解的用法
控制 extends 進行 -i 場景 1.7 遞歸 ins 規範 轉載:http://www.jb51.net/article/75460.htm 1. 使用Spring註解來註入屬性 1.1. 使用註解以前我們是怎樣註入屬性的 類的實現: class UserMa
第四課:通過配置文件獲取對象(Spring框架中的IOC和DI的底層就是基於這樣的機制)
ted const dex generate stat clas name 必須 nbsp 首先在D盤創建一個文件hero.txt,內容為:com.hero.Hero(此處必須是Hero的完整路徑) 接下來是Hero類 package com.hero; publi
Spring框架中的aop操作 及aspectjweaver.jar與aopalliance-1.0.jar下載地址 包含beans 註解context 和aop的約束
包括 aspect component cts base aid 核心 lease express (aspect oriented programming面向切面編程) 首先在原有的jar包: 需Spring壓縮包中的四個核心JAR包 beans 、contex
Spring5源碼解析-Spring框架中的事件和監聽器
事件處理 junit ise 機制 zab ext.get process mil handle 事件和平時所用的回調思想在與GUI(JavaScript,Swing)相關的技術中非常流行。而在Web應用程序的服務器端,我們很少去直接使用。但這並不意味著我們無法在服務端去實
spring框架中工廠方法的建立和銷燬
1.編寫介面UserSerivce: public interface UserService { public void sayHello(); } 2.編寫實實現介面的方法,在該方法中除了要實現介面中的方法,還定義了inti和destory方法: public class
spring框架中工廠方法的創建和銷毀
color this alt ima 實現 close col out err 1.編寫接口UserSerivce: public interface UserService { public void sayHello(); } 2.編寫實實現接口的方法,在
Spring框架中的IOC和DI
IOC(Inversion of Control):其思想是反轉資源獲取的方向.傳統的資源查詢方式要求元件向容器發起請求查詢資源,作為迴應,容器適時的返回資源。而應用了IOC之後,則是容器主動的將資源推送給它所管理的元件,元件所要做的僅是選擇一種合適的方式來接受資源。這種行為也被稱為查詢的被動形式。
Spring框架中IOC控制反轉和DI依賴注入區別
IOC控制反轉:說的是建立物件例項的控制權從程式碼控制剝離到IOC容器控制,實際就是你在xml檔案控制,側重於原理。 DI依賴注入:說的是建立物件例項時,為這個物件注入屬性值或其它物件例項,側重於實現。 它們是spring核心思想的不同方面的描述。 DI 和 IO
odoo系統中name_search和name_get用法
打印 per sequence not 添加 product xpath ret 領料單 自動帶出工序和工序序號,兩個條件都能搜索,並且兩個都帶出來顯示在前端: # 輸入工序序號會自動帶出工序名// def name_search(self, cr,user,name=
JAVA異常基本知識及異常在Spring框架中的整體解決方案
我們 程序 details 編譯錯誤 htm 及其 arch extends exception 異常的頂級父類是Throwable,下面有兩個子類Exception和Error。 Error錯誤一般是虛擬機相關的問題,如系統崩潰,虛擬機錯誤等,應用程序無法處理,直接導致
SQLServer中exists和except用法
sqlserver sql 一、exists1.1 說明EXISTS(包括 NOT EXISTS)子句的返回值是一個BOOL值。EXISTS內部有一個子查詢語句(SELECT ... FROM...),我將其稱為EXIST的內查詢語句。其內查詢語句返回一個結果集。EXISTS子句根據其內查詢語句的結果
Spring框架—— IOC容器和Bean的配置
單引號 framework 將不 配置信息 init 字符串連接 生命 release exp 1 IOC和DI ①IOC(Inversion of Control):反轉控制。 在應用程序中的組件需要獲取資源時,傳統的方式是組件主動的從容器中獲取所需要的資源,在這樣的模
spring框架中ModelAndView、Model、ModelMap區別
實現類 java類 lan esp 測試 public googl user ram 轉載來源:http://www.cnblogs.com/google4y/p/3421017.html 註意:如果方法聲明了註解@ResponseBody ,則會直接將返回值輸出到頁面
Spring 框架中註釋驅動的事件監聽器詳解
publisher 情況下 對象 nal bool class 事件類型 drive super 事件交互已經成為很多應用程序不可或缺的一部分,Spring框架提供了一個完整的基礎設施來處理瞬時事件。下面我們來看看Spring 4.2框架中基於註釋驅動的事件監聽器。 1
Spring框架中InitializingBean執行順序
ans .com 構造函數 tar start bean 復制代碼 init auth 本文轉自:https://www.cnblogs.com/yql1986/p/4084888.html package org.test.InitializingBean; 2
描述一下Spring框架的作用和優點?
選擇 第三方框架 方案 16px clas style 方框 spring 簡化 Spring框架的作用和優點如下: 1.Spring是一個開源的輕量級的應用開發框架,其目的是用於簡化企業級應用程序開發,減少侵入; 2.Spring提供的IOC和AOP應用,可以
JAVA中this和super用法
出現 子句 package code rgs lean 眼睛 都是 java對象 參考網上資料和自行理解總結java中this和super中各自用法及其差異 <一>. this的用法 構造方法是創建java對象的重要途徑,通過new關鍵字調用構造器
spring框架中定時器的配置及應用
首先我們來簡單瞭解下定時器: 1. 定時器的作用 在實際的開發中,如果專案中需要定時執行或者需要重複執行一定的工作,定時器
Spring 事務——事務介紹以及事務在Spring框架中的基本實現
事務介紹 事務一般發生在和持久層打交道的地方,比如資料庫。 假設一個工作由兩件事共同組成,那麼這兩件事要麼全部完成,這個工作才算完成。要麼全部回退到初始狀態。不存在只完成一件,還有一件事沒完成的。這項工作可稱為一個事務。常用的場景就是銀行轉賬。A向B轉賬100元這項工作由兩件事組成:A帳