在eclipse中javaEE環境下:javascript
這兒並無鏈接數據庫,而是將數據存放在map集合中;html
將各類架包導入lib下。。。java
web.xml文件配置爲jquery
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <!-- 配置SpringMVC的DispatcherServlet --> <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.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> <!-- 配置 HiddenHttpMethodFilter: 把 POST 請求轉爲 DELETE、PUT 請求 --> <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> </web-app>
spring的bean配置文件:springmvc.xml:分別配置,自動掃描的包及其自包,視圖解析器,自定義類型轉化器須要的配置,國際化資源文件web
<?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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd 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-4.0.xsd"> <!-- 配置自動掃描的包 --> <context:component-scan base-package="com.atguigu.springmvc"></context:component-scan> <!-- 配置視圖解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/"></property> <property name="suffix" value=".jsp"></property> </bean> <!-- default-servlet-handler 將在 SpringMVC 上下文中定義一個 DefaultServletHttpRequestHandler, 它會對進入 DispatcherServlet 的請求進行篩查, 若是發現是沒有通過映射的請求, 就將該請求交由 WEB 應用服務器默認的 Servlet 處理. 若是不是靜態資源的請求,才由 DispatcherServlet 繼續處理 通常 WEB 應用服務器默認的 Servlet 的名稱都是 default. 若所使用的 WEB 服務器的默認 Servlet 名稱不是 default,則須要經過 default-servlet-name 屬性顯式指定 --> <mvc:default-servlet-handler/> <!-- 通常都會配置這個 <mvc:annotation-driven ></mvc:annotation-driven>, 因爲。。。requestmapping請求實現不了,使用這個,會使requestmapping請求必定實現 --> <mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven> <!-- 配置 ConversionService ,自定義類型轉換器,bean配置--> <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <property name="converters"> <set> <!-- bean。。。爲自定義類型轉換器的類名,其中,首字母小寫 --> <ref bean="employeeConverter"/> </set> </property> </bean> <!-- 配置國際化資源文件 --> <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> <property name="basename" value="i18n"></property> </bean> </beans>
數據分裝的兩個類,是一對多的級聯關係spring
數據的分裝類:Department數據庫
package com.atguigu.springmvc.crud.entities; public class Department { private Integer id; private String departmentName; public Department() { super(); // TODO Auto-generated constructor stub } public Department(Integer id, String departmentName) { super(); this.id = id; this.departmentName = departmentName; } 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 + "]"; } }
數據的分裝類:Employee,對此類中的屬性,作了註解,能夠實現表單驗證apache
package com.atguigu.springmvc.crud.entities; 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; /* * 在封裝類的屬性上面添加註解,是爲了實現類型樣式的轉換: * 步驟: * 1>.在封裝類的屬性上面添加各類註解 * 2>.在springmvc.xml的配置中添加標配<mvc:annotation-driven></mvc:annotation-driven>, * 無論怎樣都不影響註解 * * */ 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註解的做用是:輸入是此時間以前的時間,不然拋出錯誤 @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 } }
兩個DAO方法,有兩個分裝類數據的增刪改查方法;api
DepartmentDAO:spring-mvc
package com.atguigu.springmvc.crud.dao; import java.util.Collection; import java.util.HashMap; import java.util.Map; import org.springframework.stereotype.Repository; import com.atguigu.springmvc.crud.entities.Department; @Repository//標識持久層組件 public class DepartmentDao { private static Map<Integer, Department> departments=null; static{ departments=new HashMap<Integer, Department>(); departments.put(1001, new Department(1001,"D-AA")); departments.put(1002, new Department(1002,"D-BB")); departments.put(1003, new Department(1003,"D-CC")); departments.put(1004, new Department(1004,"D-DD")); departments.put(1005, new Department(1005,"D-EE")); } //獲取map集合中的全部值 public Collection<Department> getDepartments(){ return departments.values(); } //經過id值,獲取map集合中的一個值 public Department getDepartment(Integer id){ return departments.get(id); } }
EmployeeDAO:
package com.atguigu.springmvc.crud.dao; import java.util.Collection; import java.util.HashMap; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.atguigu.springmvc.crud.entities.Department; import com.atguigu.springmvc.crud.entities.Employee; @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 save(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 getEmployee(Integer id){ return employees.get(id); } //刪除集合中的一個數據 public void delect(Integer id){ employees.remove(id); } }
EmployeeHandler類,基於註解的實現方法,便於頁面之間的跳轉:
package com.atguigu.springmvc.crud.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.BindingResult; 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.atguigu.springmvc.crud.dao.DepartmentDao; import com.atguigu.springmvc.crud.dao.EmployeeDao; import com.atguigu.springmvc.crud.entities.Employee; @Controller //標識表現層組件 public class EmployeeHandler { @Autowired private DepartmentDao departmentDao; @Autowired private EmployeeDao employeeDao; //自定義類型轉換器,使用這個請求 //<!-- lastname-email-gender-department.id 例如: GG-gg@atguigu.com-0-105 --> @RequestMapping("/testConversionServiceConverer") public String testConverter(@RequestParam("employee") Employee employee){ employeeDao.save(employee); System.out.println("save: " + employee); return "redirect:/emps"; } /* * 在方法定義上使用@ModelAttribute註解:Spring MVC在調用目標處理方法前, * 會先逐個調用在方法上標註了@ModelAttribute的方法;即每一個方法會先調用 方法上標註的@ModelAttribute的方法 * * @ModelAttribute做用是:能夠從隱含對象中獲取隱含的模型數據中獲取對象,(就是能夠獲取jsp中隱含屬性的變量值), * 在將請求參數綁定到對象中,再傳入 入參,將方法入參對象,添加到模型中; * */ @ModelAttribute public void getEmployee(@RequestParam(value="id",required=false) Integer id, Map<String, Object> map){ if(id!=null){ map.put("employee", employeeDao.getEmployee(id)); } } //修改操做,將修改好的信息重定向到emps請求 @RequestMapping(value="/emp", method=RequestMethod.PUT) public String update(Employee employee){ employeeDao.save(employee); return "redirect:/emps"; } //修改操做,將要修改的信息顯示在input.jsp頁面上 @RequestMapping(value="/emp/{id}", method=RequestMethod.GET) public String input(@PathVariable("id") Integer id,Map<String, Object> map){ map.put("employee", employeeDao.getEmployee(id)); map.put("departments", departmentDao.getDepartments()); return "input"; } //刪除操做,而後重定向到/emps請求,即在list.jsp頁面顯示 @RequestMapping(value="/emp/{id}", method=RequestMethod.DELETE) public String delete(@PathVariable("id") Integer id){ employeeDao.delect(id); return "redirect:/emps"; } //@Valid註解,表單驗證時使用; 表單驗證時對架包的處理:將 //hibernate-validator-5.0.0.CR2-dist\hibernate-validator-5.0.0.CR2\dist\lib\required //下的三個架包:el-api-2.2,javax.el-2.2.4,javax.el-api-2.2.4 //複製到 apache-tomcat-6.0.16\apache-tomcat-6.0.16\lib 目錄下 而且完全粉碎apache-tomcat包 lib中的el架包,這樣才能夠實現表單的驗證 //添加信息操做,若是添加信息的格式正確,而後重定向到/emps請求,即到list.jsp頁面; //若是添加信息的格式不正確,則跳轉到本頁面(input.jsp),顯示錯誤的信息,須要在input.jsp頁面加入標籤 //<form:errors path="*"></form:errors>,將全部的錯誤都顯示在一塊,錯誤信息的顯示, //也能夠分開寫,格式爲<form:errors path="lastName"></form:errors>,path值爲屬性值,分別寫在屬性值的下邊, 顯示在 輸入錯誤的文本框下邊 @RequestMapping(value="/emp", method=RequestMethod.POST) public String save(@Valid Employee employee, Errors result,Map<String, Object> map){ System.out.println("save"+employee); if(result.getErrorCount()>0){ System.out.println("出錯了"); //將全部錯誤都輸出 for(FieldError error:result.getFieldErrors()){ System.out.println(error.getField()+":"+error.getDefaultMessage()); } //若驗證出錯, 則轉向定製的頁面 map.put("departments", departmentDao.getDepartments()); return "input"; } employeeDao.save(employee); return "redirect:/emps"; } //添加員工的信息,將一個空的employee和非空的department放入到map集合中, //經過視圖解析器,轉發到input頁面,能夠添加信息,是一個GET請求 @RequestMapping(value="/emp",method=RequestMethod.GET) public String input(Map<String, Object> map){ map.put("departments", departmentDao.getDepartments()); map.put("employee", new Employee()); return "input"; } //顯示employee的所有的信息 @RequestMapping("/emps") public String list(Map<String, Object> map){ map.put("employees", employeeDao.getAll()); return "list"; } //測試方法 @RequestMapping("/test") public String testTT(){ return "test"; } /*由@InitBinder標識的方法,能夠對WebDataBinder初始化, * WebDataBinder是DataBinder的子類,用於完成由表單字段到javaBean屬性的綁定 * * @InitBinder註解的方法不能有返回值,它必須聲明爲void; * 方法的參數一般是WebDataBinder; * * @InitBinder註解的方法的做用是使該屬性在jsp頁面上沒有值,例如lastName屬性在input.jsp頁面上沒有值 * */ // @InitBinder // private void initBinder(WebDataBinder binder) { // binder.setDisallowedFields("lastName"); // // } }
表單驗證的國際化資源文件:其實基於註解的 每個值書寫順序爲 屬性上邊的註解. 表單要輸入的屬性值的集合(即map集合的key值).屬性名=輸入錯誤時,要回顯得語句
文件名爲:i18n.properties;要映射上次資源文件,要到springmvc.xml文件中配置國際化資源文件
NotEmpty.employee.lastName=^^LastName\u4E0D\u80FD\u4E3A\u7A7A. Email.employee.email=Email\u5730\u5740\u4E0D\u5408\u6CD5 Past.employee.birth=Birth\u4E0D\u80FD\u662F\u4E00\u4E2A\u5C06\u6765\u7684\u65F6\u95F4. typeMismatch.employee.birth=Birth\u4E0D\u662F\u4E00\u4E2A\u65E5\u671F.
自定義類型轉換器:能夠將字符串GG-gg@atguigu.com-0-105,轉換爲四個屬性的值,放在map集合中,這兒仍是要在springmvc.xml配置文件中進行配置;
package com.atguigu.springmvc.crud.converters; import org.springframework.core.convert.converter.Converter; import org.springframework.stereotype.Component; import com.atguigu.springmvc.crud.entities.Department; import com.atguigu.springmvc.crud.entities.Employee; @Component public class EmployeeConverter implements Converter<String, Employee>{ @Override //自定義類型轉換器 public Employee convert(String source) { if(source!=null){ //GG-gg@atguigu.com-0-105 String [] vals=source.split("-"); if(vals!=null && vals.length==4){ String lastName = vals[0]; String email = vals[1]; Integer gender = Integer.parseInt(vals[2]); Department department = new Department(); department.setId(Integer.parseInt(vals[3])); Employee employee = new Employee(null, lastName, email, gender, department); System.out.println(source + "--convert--" + employee); return employee; } } return null; } }
index.jsp頁面,只有一個超連接,實現頁面的跳轉;
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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>
<center>
<a href="emps">List All Employees</a>
<br><br>
<a href="test">TTTTTTT</a>
</center>
</body>
</html>
list.jsp頁面,顯示employee的所有信息,有增長,刪除,修改信息的超連接,實現。。。
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ 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> <!-- SpringMVC 處理靜態資源: 1. 爲何會有這樣的問題: 優雅的 REST 風格的資源URL 不但願帶 .html 或 .do 等後綴 若將 DispatcherServlet 請求映射配置爲 /, 則 Spring MVC 將捕獲 WEB 容器的全部請求, 包括靜態資源的請求, SpringMVC 會將他們當成一個普通請求處理, 因找不到對應處理器將致使錯誤。 2. 解決: 在 SpringMVC 的配置文件中配置 <mvc:default-servlet-handler/> 和 <mvc:annotation-driven></mvc:annotation-driven>, --> <script type="text/javascript" src="scripts/jquery-1.9.1.min.js"></script> <script type="text/javascript"> $(function(){ $(".delete").click(function(){ var href=$(this).attr("href"); $("form").attr("action",href).submit(); return false; }); }) </script> </head> <body> <!-- 一個超連接是一個get請求,用jQuery方法和影藏的表單的方法, 將get請求轉化爲post請求,再將post請求轉換爲delete請求(web.xml文件中進行了配置) --> <form action="" method="post"> <input type="hidden" name="_method" value="DELETE"/> </form> <center> <c:if test="${empty requestScope.employees }"> 沒有任何員工信息!!! </c:if> <br><br> <c:if test="${!empty requestScope.employees }"> <table border="1" cellpadding="10" cellspacing="0"> <tr> <th>ID</th> <th>ListName</th> <th>Email</th> <th>Gender</th> <th>Department</th> <th>Edit</th> <th>Delete</th> </tr> <c:forEach items="${requestScope.employees }" var="emp"> <tr> <td>${emp.id }</td> <td>${emp.lastName }</td> <td>${emp.email }</td> <td>${emp.gender==0 ? 'Female' : 'Male' }</td> <td>${emp.department.departmentName }</td> <td> <a href="emp/${emp.id }">Edit</a> </td> <td> <a class="delete" href="emp/${emp.id }">Delete</a> </td> </tr> </c:forEach> </table> </c:if> <br><br> <a href="emp">And New Employee</a> </center> </body> </html>
input.jsp頁面,employee信息添加的頁面,此頁面能夠實現數據類型轉換,數據格式化,數據校驗,能夠將校驗值,顯示在輸入框下;
<%@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> <form action="testConversionServiceConverer" method="post"> <!-- lastname-email-gender-department.id 例如: GG-gg@atguigu.com-0-105 --> Employee:<input type="text" name="employee"/> <input type="submit" value="Submit"/> </form> <br> <!-- 1. WHY 使用 form 標籤呢 ? 能夠更快速的開發出表單頁面, 並且能夠更方便的進行表單值的回顯 2. 注意: 能夠經過 modelAttribute 屬性指定綁定的模型屬性, 若沒有指定該屬性,則默認從 request 域對象中讀取 command 的表單 bean 若是該屬性值也不存在,則會發生錯誤。 --> <!-- 添加員工的信息的jsp --> <form:form action="${pageContext.request.contextPath }/emp" method="post" modelAttribute="employee"> <!-- path 屬性對應 html 表單標籤的 name 屬性值 --> <form:errors path="*"></form:errors>//全部的校驗信息顯示在一塊 <br><br> <c:if test="${employee.id==null }"> lastName:<form:input path="lastName"/> <form:errors path="lastName"></form:errors>//分別顯示校驗信息 </c:if> <c:if test="${employee.id!=null }"> <form:hidden path="id"/> <!-- 將post請求轉換爲put請求,put請求即爲更改 --> <input type="hidden" name="_method" value="PUT"/> <%-- 對於 _method 不能使用 form:hidden 標籤, 由於 modelAttribute 對應的 bean 中沒有 _method 這個屬性 --%> <%-- <form:hidden path="_method" value="PUT"/> --%> </c:if> <br><br> Email:<form:input path="email"/> <form:errors path="email"></form:errors> <br><br> <% Map<String, String> genders=new HashMap<String, String>(); genders.put("1", "Male"); genders.put("0", "Female"); request.setAttribute("genders", genders); %> Gender: <br> <form:radiobuttons path="gender" items="${genders }" delimiter="<br>"/> <br><br> Department:<form:select path="department.id" items="${departments }" itemLabel="departmentName" itemValue="id"></form:select> <br><br> <!-- 1. 數據類型轉換 2. 數據類型格式化 3. 數據校驗. 1). 如何校驗 ? 註解 ? ①. 使用 JSR 303 驗證標準 ②. 加入 hibernate validator 驗證框架的 jar 包 ③. 在 SpringMVC 配置文件中添加 <mvc:annotation-driven /> ④. 須要在 bean 的屬性上添加對應的註解 ⑤. 在目標方法 bean 類型的前面添加 @Valid 註解 2). 驗證出錯轉向到哪個頁面 ? 注意: 需校驗的 Bean 對象和其綁定結果對象或錯誤對象時成對出現的,它們之間不容許聲明其餘的入參 3). 錯誤消息 ? 如何顯示, 如何把錯誤消息進行國際化 --> Birth: <form:input path="birth"/> <form:errors path="birth"></form:errors> <br><br> Salary: <form:input path="salary"/> <form:errors path="salary"></form:errors> <br><br> <input type="submit" value="Submit"/> </form:form> </body> </html>