springmvc-实现增删改查
?
30. 尚硅谷_佟剛_SpringMVC_RESTRUL_CRUD_顯示所有員工信息.avi
現(xiàn)在需要使用restful風(fēng)格實現(xiàn)增刪改查,需要將post風(fēng)格的請求轉(zhuǎn)換成PUT 請求和DELETE 請求
1. 需要在web.xml文件中配置 HiddenHttpMethodFilter <!-- 配置 org.springframework.web.filter.HiddenHttpMethodFilter: 可以把 POST 請求轉(zhuǎn)為 DELETE 或 POST 請求 --><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>2. 需要發(fā)送 POST 請求3. 需要在發(fā)送 POST 請求時攜帶一個 name="_method" 的隱藏域, 值為 DELETE 或 PUT
我們來看下web.xml的具體配置 <?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_3_0.xsd"version="3.0" ><!-- The front controller of this Spring Web application, responsible for handling all application requests --><!-- 配置 org.springframework.web.filter.HiddenHttpMethodFilter: 可以把 POST 請求轉(zhuǎn)為 DELETE 或 POST 請求 --><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><!-- 加載spirng配置文件 --><init-param><param-name>contextConfigLocation</param-name><param-value>classpath:spring-mvc.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> </web-app>
1.3.?效果
①?通過POST?請求增加員工信息
②?通過PUT?請求修改員工信息
③?通過DELETE?請求刪除員工信息
④?通過GET?請求?獲取所有的?員工信息
注意點1;
<!-- springmvc只能使用原聲的jstl標簽,導(dǎo)入c標簽 -->
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
Table tr td th表格使用案例
<table width="300" border="1" cellspacing="0"> <tr> <th>班級</th> <th>日期</th> <th>標題</th> </tr> <tr> <td>一班</td> <td>2012-5-10</td> <td>標題1</td> </tr> <tr> <td>二班</td> <td>2012-5-20</td> <td>標題2</td> </tr> </table>?
DW軟件里截圖:
table案例教程布局截圖
我們來看整個項目的工程如下所示:
代碼如下:
DepartmentDao
package com.ibigsea.springmvc.dao;import java.util.Collection; import java.util.HashMap; import java.util.Map;import org.springframework.stereotype.Component;import com.ibigsea.springmvc.model.Department;@Component public class DepartmentDao {public static Map<Integer, Department> depts = new HashMap<Integer, Department>();/*** 初始化部門信息*/static {depts.put(101, new Department(101,"JAVA"));depts.put(102, new Department(102,".NET"));depts.put(103, new Department(103,"PHP"));depts.put(104, new Department(104,"C"));}/*** 獲取所有的部門信息* @return*/public Collection<Department> getAll(){return depts.values();}/*** 根據(jù)ID獲取部門信息* @param id* @return*/public Department getDepartmentById(Integer id){return depts.get(id);}}?
EmployeeDao
package com.ibigsea.springmvc.dao;import java.util.Collection; import java.util.HashMap; import java.util.Map;import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component;import com.ibigsea.springmvc.model.Department; import com.ibigsea.springmvc.model.Employee;@Component public class EmployeeDao {@AutowiredDepartmentDao departmentDao;private static Map<Integer,Employee> emps = new HashMap<Integer, Employee>();/*** 初始化員工信息*/static {emps.put(1001, new Employee(1001,"AA","AA@ibigsea.com",0,new Department(101, "JAVA")));emps.put(1002, new Employee(1002,"BB","BB@ibigsea.com",0,new Department(102, ".NET")));emps.put(1003, new Employee(1003,"CC","CC@ibigsea.com",1,new Department(103, "PHP")));emps.put(1004, new Employee(1004,"DD","DD@ibigsea.com",0,new Department(104, "C")));}private static int employeeId = 1005;/*** 保存員工信息* @param emp*/public void save(Employee emp){if (emp.getId() == null) {emp.setId(employeeId++);}emp.setDepartment(departmentDao.getDepartmentById(emp.getDepartment().getId()));emps.put(emp.getId(), emp);}/*** 獲取所有的員工信息* @return*/public Collection<Employee> getAll(){return emps.values();}/*** 根據(jù)ID獲取員工信息* @param id* @return*/public Employee getEmpById(Integer id){return emps.get(id);}/*** 根據(jù)ID刪除員工信息* @param id*/public void delEmpById(Integer id){emps.remove(id);}}?
??
index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html><head><base href="<%=basePath%>"><title>My JSP 'index.jsp' starting page</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">--></head><body><a href="emps">查詢所有員工的信息</a> <br></body> </html>?
?顯示所有員工信息的list.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <!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>員工信息</title> </head> <body><c:if test="${ empty employees }">沒有員工信息</c:if><c:if test="${ !empty employees }"><table border="1" bordercolor="black" cellspacing="0"><tr><td width="40px">id</td><td width="30px">name</td><td width="80px">email</td><td width="30px">sex</td><td width="30px">department</td><td width="40px">編輯</td><td width="40px">刪除</td></tr><c:forEach items="${employees }" var="emp"><tr><td>${emp.id }</tdemployees><td>${emp.name }</td><td>${emp.email }</td><td>${emp.sex == 0 ? '男' : '女'}</td><td>${emp.department.name}</td><td><a href="${pageContext.request.contextPath}/edit/${emp.id }">Edit</a></td><td><form action="${pageContext.request.contextPath}/delete/${emp.id }" method="post"><input type="hidden" name="_method" value="DELETE"><input type="submit" value="Delete"></form></td></tr></c:forEach></table></c:if><br><br><a href="${pageContext.request.contextPath}/emp">添加員工</a> </body> </html>?
??
handle處理器
package com.ibigsea.springmvc.handler;import java.util.Collection; import java.util.Map;import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod;import com.ibigsea.springmvc.dao.EmployeeDao; import com.ibigsea.springmvc.model.Employee;@Controller public class EmployeeHandler {@Autowiredprivate EmployeeDao employeeDao;/** 查詢所有的員工信息* */@RequestMapping(value="/emps",method=RequestMethod.GET)public String listAllEmployees(Map<String,Object> map){Collection<Employee> allEmployees = employeeDao.getAll();map.put("employees", allEmployees);return"list";}}?
web.xml配置文件
<?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_3_0.xsd"version="3.0" ><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><!-- 加載spirng配置文件 --><init-param><param-name>contextConfigLocation</param-name><param-value>classpath:spring-mvc.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> </web-app>?
spring-mvc.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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsdhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd"><!-- 配置自動掃描包 掃描com.ibigsea.springmvc 包下的類,后期會使用spring進行管理 --><context:component-scan base-package="com.ibigsea.springmvc"/> <!-- 配置視圖解析器 如返回helloworld 為 [/WEB-INF/pages/helloworld.jsp] --><bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"><!-- 前綴 --><property name="prefix" value="/WEB-INF/pages/"/><!-- 后綴 --><property name="suffix" value=".jsp"/></bean></beans>?
項目有幾個地方需要注意的:
1、在DepartMentdao 需要使用spring的@AutoWier功能,需要使用@Component進行注解
2、在spring-xml中需要添加自動掃描?<context:component-scan base-package="com.ibigsea.springmvc"/>
?
運行效果如下所述
?
?31. 尚硅谷_佟剛_SpringMVC_RESTRUL_CRUD_添加操作&表單標簽.avi
1、這里在添加員工的時候使用的是springmvc的表單標簽
正式介紹SpringMVC的表單標簽之前,我們需要先在JSP中聲明使用的標簽,具體做法是在JSP文件的頂部加入以下指令:
<%@taglib?uri="http://www.springframework.org/tags/form"?prefix="form"?%> ?
2、
?1.用form select標簽為例,在書寫JSP時,有時筆誤可能會寫成<form:select path="departmet"?items="departments"?itemLabel="departmentName" itemValue="id"></form:select>
這種寫法是錯誤的,應(yīng)該是
<form:select path="departmet"?items="${departments }"?itemLabel="departmentName" itemValue="id"></form:select>
3、
使用Spring的form標簽主要有兩個作用,第一是它會自動的綁定來自Model中的一個屬性值到當(dāng)前form對應(yīng)的實體對象,默認是command對象 ,這樣我們就可以在form表單體里面方便的使用該對象的屬性了;
第二是它支持我們在提交表單的時候使用除GET和POST之外的其他方法進行提交,包括DELETE和PUT等。
現(xiàn)在我們在input.jsp中
<%@page import="java.util.Map"%> <%@page import="java.util.HashMap"%> <%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%><%@taglib uri="http://www.springframework.org/tags/form" prefix="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>添加員工信息</title> </head> <body> <!-- 這里是使用springmvc的form標簽private Integer id;private String name;private String email;private int sex;private Department department;--> <form:form action="addEmp" method="post" modelAttribute="employ" >id:<form:input path="id"/><br><br> 姓名:<form:input path="name"/><br> 郵箱:<form:input path="email"/><br> <%Map<String,String> genders = new HashMap();genders.put("1", "男");genders.put("0", "女"); request.setAttribute("sexMap",genders);%>性別:<form:radiobuttons path="sex" items="${sexMap }"/> <br> department: <form:select path="department.id" itemLabel="name"items="${departments}" itemValue="id"></form:select><br> <input type="submit" value="submit"/> </form:form> </body> </html>?
??
我們需要綁定的域?qū)ο蟛辉谑悄J的command對象,二是表單標簽在不進行數(shù)據(jù)綁定是無法操作的,在運行程序的時候會報錯,因為表單標簽是依賴于數(shù)據(jù)綁定操作的。"employ" 對于的employ對象,該對象來自handle中map.put("employ", employee);對象,如果form表達中沒有對于的對象進行綁定,form表單
就會拋出異常,所以在使用springmvc 表單中即使不顯示任何數(shù)據(jù),也要創(chuàng)建下面這樣一個空的employee對象,這樣顯示表單標簽才不會異常。如果employee對象中存在name值,email值,跳轉(zhuǎn)到input.jsp頁面的時候會把對應(yīng)的值顯示出來,該功能可以用于修改聯(lián)系人,把聯(lián)系人原來的信息顯示在表單標簽中。
總結(jié):表單標簽在不進行數(shù)據(jù)綁定是無法操作的,在運行程序的時候會報錯,因為表單標簽是依賴于數(shù)據(jù)綁定操作的。綁定對象可以使用modelAttribute制定需要綁定對象的名稱,<form:form action="addEmp" method="post" modelAttribute="employ" >這個配置相當(dāng)?shù)年P(guān)鍵,指定springmvc表單和那個對象就是自動綁定,
@RequestMapping(value="/emp",method=RequestMethod.GET)public String input(Map<String,Object> map){Collection<Department> departments = departmentDao.getAll();map.put("departments", departments);Employee employee = new Employee();map.put("employ", employee);return"input";}4、在添加聯(lián)系人的頁面中,提交的部門的時候
department: <form:select path="department.id" itemLabel="name"
items="${departments}" itemValue="id"></form:select>
<br>
對于的path是department.id,對應(yīng)的是部門的id,保存的時候依據(jù)部門的id值,查詢出部門,再把部門保存到聯(lián)系人中
/*** 保存員工信息* @param emp*/public void save(Employee emp){if (emp.getId() == null) {emp.setId(employeeId++);}emp.setDepartment(departmentDao.getDepartmentById(emp.getDepartment().getId()));emps.put(emp.getId(), emp);}?
handler控制成的代碼為
package com.ibigsea.springmvc.handler;import java.util.Collection; import java.util.Map;import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam;import com.ibigsea.springmvc.dao.DepartmentDao; import com.ibigsea.springmvc.dao.EmployeeDao; import com.ibigsea.springmvc.model.Department; import com.ibigsea.springmvc.model.Employee;@Controller public class EmployeeHandler {@Autowiredprivate EmployeeDao employeeDao;@Autowiredprivate DepartmentDao departmentDao;/** 執(zhí)行添加聯(lián)系人操作,重定向到顯示所有聯(lián)系人的頁面* */@RequestMapping(value="/addEmp", method=RequestMethod.POST)public String addEmp(Employee em){employeeDao.save(em);//employeeDao.save(employ);return "redirect:/emps";}/*** 點擊添加聯(lián)系人,跳轉(zhuǎn)到添加聯(lián)系人頁面* */@RequestMapping(value="/emp",method=RequestMethod.GET)public String input(Map<String,Object> map){Collection<Department> departments = departmentDao.getAll();map.put("departments", departments);Employee employee = new Employee();map.put("employ", employee);return"input";}/** 查詢所有的員工信息* */@RequestMapping(value="/emps",method=RequestMethod.GET)public String listAllEmployees(Map<String,Object> map){Collection<Employee> allEmployees = employeeDao.getAll();map.put("employees", allEmployees);return"list";}}添加聯(lián)系人可以總結(jié)成下面的三個步驟:
第一檔點擊添加聯(lián)系人按鈕的時候,請求經(jīng)過handle處理跳轉(zhuǎn)到handle進行處理,handle返回添加聯(lián)系人的頁面
添加聯(lián)系人的頁面使用到了spring mvc的表單標簽,為了便于數(shù)據(jù)的回顯,這里設(shè)置了一個modelAttribute="employ",所以在handle中跳轉(zhuǎn)到添加聯(lián)系人界面input.jsp的時候都必須在請求域中設(shè)置一個空的employ對象,否則會拋出異常
?
map.put("departments", departments);Employee employee = new Employee();map.put("employ", employee);第三步:添加聯(lián)系人成功之后,重定向到url為emps的handle進行處理,再次查詢出數(shù)據(jù)庫中的所有數(shù)據(jù),然后跳轉(zhuǎn)到list.jsp將所有的數(shù)據(jù)顯示出來
?
?
32. 尚硅谷_佟剛_SpringMVC_RESTRUL_CRUD_刪除操作&處理靜態(tài)資源.avi
刪除操作需要使用HiddenHttpMethodFilter將post請求轉(zhuǎn)化成對應(yīng)的delete請求,其中表達中的name值必須是_method,vale值必須是DELETE
下面的這種方式
?<td><a id="sub123" href="${pageContext.request.contextPath}/delete/${emp.id }" >Delete</a></td>
對應(yīng)的是get請求,我們?nèi)绾螌et請求轉(zhuǎn)化成post請求了,可以使用下面的方式,也可以采用視頻中的方式
?
<td><form action="${pageContext.request.contextPath}/delete/${emp.id }" method="post"><input type="hidden" name="_method" value="DELETE"><input type="submit" value="Delete"></form></td>?
?
?
我們來看list.jsp的代碼
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <!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"> <!-- 因為jquery文件 --> <script type="text/javascript" src="/jquery-3.3.1.min.js"></script> <script type="text/javascript"></script> <title>員工信息</title> </head> <body><!-- 添加一個表單將post請求轉(zhuǎn)換成delete請求 name必須是_methodvalue必須是DELETE名字不能被修改--></form><c:if test="${ empty employees }">沒有員工信息</c:if><c:if test="${ !empty employees }"><table border="1" bordercolor="black" cellspacing="0"><tr><td width="40px">id</td><td width="30px">name</td><td width="80px">email</td><td width="30px">sex</td><td width="30px">department</td><td width="40px">編輯</td><td width="40px">刪除</td></tr><c:forEach items="${employees }" var="emp"><tr><td>${emp.id }</tdemployees><td>${emp.name }</td><td>${emp.email }</td><td>${emp.sex == 0 ? '男' : '女'}</td><td>${emp.department.name}</td><td><a href="${pageContext.request.contextPath}/edit/${emp.id }">Edit</a></td><td><form action="${pageContext.request.contextPath}/delete/${emp.id }" method="post"><input type="hidden" name="_method" value="DELETE"><input type="submit" value="Delete"></form></td></tr></c:forEach></table></c:if><br><br><a href="${pageContext.request.contextPath}/emp">添加員工</a> </body> </html>?
我們來看handler的代碼
package com.ibigsea.springmvc.handler;import java.util.Collection; import java.util.Map;import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; 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.ibigsea.springmvc.dao.DepartmentDao; import com.ibigsea.springmvc.dao.EmployeeDao; import com.ibigsea.springmvc.model.Department; import com.ibigsea.springmvc.model.Employee;@Controller public class EmployeeHandler {@Autowiredprivate EmployeeDao employeeDao;@Autowiredprivate DepartmentDao departmentDao;/** 執(zhí)行添加聯(lián)系人操作,重定向到顯示所有聯(lián)系人的頁面* */@RequestMapping(value="/delete/{id}", method=RequestMethod.DELETE)public String deletEmp(@PathVariable("id") Integer id ){employeeDao.delEmpById(id);//employeeDao.save(employ);return "redirect:/emps";}/** 執(zhí)行添加聯(lián)系人操作,重定向到顯示所有聯(lián)系人的頁面* */@RequestMapping(value="/addEmp", method=RequestMethod.POST)public String addEmp(Employee em){employeeDao.save(em);return "redirect:/emps";}/*** 點擊添加聯(lián)系人,跳轉(zhuǎn)到添加聯(lián)系人頁面* */@RequestMapping(value="/emp",method=RequestMethod.GET)public String input(Map<String,Object> map){Collection<Department> departments = departmentDao.getAll();map.put("departments", departments);Employee employee = new Employee();map.put("employ", employee);return"input";}/** 查詢所有的員工信息* */@RequestMapping(value="/emps",method=RequestMethod.GET)public String listAllEmployees(Map<String,Object> map){Collection<Employee> allEmployees = employeeDao.getAll();map.put("employees", allEmployees);return"list";}}?
注意點:
在web.xml中配置
<!-- 攔截所有請求 --><servlet-mapping><servlet-name>springDispatcherServlet</servlet-name><url-pattern>/</url-pattern></servlet-mapping>?
攔截所以的請求,如果訪問靜態(tài)資源文件也會被攔截。但是對于的訪問靜態(tài)資源的文件沒有在handler中進行映射處理,就會導(dǎo)出錯誤,為了能夠直接訪問靜態(tài)資源文件不會出現(xiàn)問題,需要在spring-mvc.xml文件中進行下面的配置
<!-- 配置運行可以訪問靜態(tài)資源文化 --><mvc:default-servlet-handler/><mvc:annotation-driven></mvc:annotation-driven>?
spring-mvc.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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsdhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd"><!-- 配置自動掃描包 掃描com.ibigsea.springmvc 包下的類,后期會使用spring進行管理 --><context:component-scan base-package="com.ibigsea.springmvc"/> <!-- 配置視圖解析器 如返回helloworld 為 [/WEB-INF/pages/helloworld.jsp] --><bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"><!-- 前綴 --><property name="prefix" value="/WEB-INF/pages/"/><!-- 后綴 --><property name="suffix" value=".jsp"/></bean><!-- 配置運行可以訪問靜態(tài)資源文化 --><mvc:default-servlet-handler/><mvc:annotation-driven></mvc:annotation-driven></beans>?33. 尚硅谷_佟剛_SpringMVC_RESTRUL_CRUD_修改操作.avi
修改操作
1、在修改頁面顯示需要修改的聯(lián)系人,但是聯(lián)系人的name屬性不能被修改
2、修改聯(lián)系人需要使用PUT方式提交
這里因為要在input.jsp中顯示需要修改的聯(lián)系人,需要對input.jsp做下面的修改
<!-- 注意不能寫成
<form:hidden path="_method" value="PUT"/>
1、因為傳遞參數(shù)的時候,需要封裝成javabean對象,java對象中不存在_method這個屬性,上面的path="id"在javabean對象中存在
2、并且 <form:hidden標簽中不存在value屬性
只能使用下面的這種形式傳遞,不能使用form表單的hidden屬性傳遞_method標簽
-->
?
?
<c:if test="${ employ.id != null}"><form:hidden path="id"/><input type="hidden" name="_method" value="PUT"/> </c:if>我們來看下程序的代碼
<%@page import="java.util.Map"%> <%@page import="java.util.HashMap"%> <%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%><%@taglib uri="http://www.springframework.org/tags/form" prefix="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>添加員工信息</title> </head> <body> <!-- 這里是使用springmvc的form標簽private Integer id;private String name;private String email;private int sex;private Department department;--> <form:form action="${pageContext.request.contextPath}/addEmp" method="post" modelAttribute="employ" ><!-- 判斷id的值是否存在,如果存在就是修改聯(lián)系人,不顯示id標簽 --><!-- 判斷id的值是否存在,如果存在就是修改聯(lián)系人,聯(lián)系人的name屬性不能被修改 --><c:if test="${ employ.id == null}">id:<form:input path="id"/><br><br> 姓名:<form:input path="name"/><br> </c:if><!-- 不等于null,需要將聯(lián)系人id的值重新傳遞到handle進行處理 對象中存在id屬性,可以直接傳遞,并且需要將表單的post請求轉(zhuǎn)化成put請求。我們需要傳遞一個_method屬性,對應(yīng)的value值是PUT傳遞到handle中--><c:if test="${ employ.id != null}"><form:hidden path="id"/><input type="hidden" name="_method" value="PUT"/> </c:if>郵箱:<form:input path="email"/><br> <%Map<String,String> genders = new HashMap();genders.put("1", "男");genders.put("0", "女"); request.setAttribute("sexMap",genders);%>性別:<form:radiobuttons path="sex" items="${sexMap }"/> <br> department: <form:select path="department.id" itemLabel="name"items="${departments}" itemValue="id"></form:select><br> <input type="submit" value="submit"/> </form:form> </body> </html>?
我們來看下handle層的代碼
package com.ibigsea.springmvc.handler;import java.util.Collection; import java.util.Map;import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; 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.ibigsea.springmvc.dao.DepartmentDao; import com.ibigsea.springmvc.dao.EmployeeDao; import com.ibigsea.springmvc.model.Department; import com.ibigsea.springmvc.model.Employee;@Controller public class EmployeeHandler {@Autowiredprivate EmployeeDao employeeDao;@Autowiredprivate DepartmentDao departmentDao;/*** 點擊修改聯(lián)系人,跳轉(zhuǎn)到修改聯(lián)系人頁面,顯示需要修改的聯(lián)系人信息,其中聯(lián)系人的名字不能被修改* */@RequestMapping(value="/edit/{id}",method=RequestMethod.GET)public String input(@PathVariable("id") Integer id,Map<String,Object> map){Collection<Department> departments = departmentDao.getAll();map.put("departments", departments);//通過id查找需要修改的聯(lián)系人Employee employee = employeeDao.getEmpById(id);map.put("employ", employee);return"input";}/*** 這里需要在執(zhí)行修改聯(lián)系人在保存的時候先查詢出來,否則自己保存* m is :Employee [id=1002, name=null, email=BB@ibigsea.com, sex=0, department=Department [id=101, name=null]]* 會存在聯(lián)系人名字為空的情況,修改修改聯(lián)系人頁面沒有傳遞聯(lián)系人姓名的屬性值* */@ModelAttributepublic void getEmployee(@RequestParam(value="id",required = false) Integer id ,Map<String,Object> map){if(id != null){Employee employee = employeeDao.getEmpById(id);//map.put("employ", employee)名字和@ModelAttribute("employ")中的一一對應(yīng)map.put("employ", employee);}}/**** 保存修改聯(lián)系人頁面,修改的聯(lián)系人,對應(yīng)的action是addEmp* <form:form action="addEmp" method="post" modelAttribute="employ" >* 對應(yīng)的訪問方式是對應(yīng)的訪問方式是PUT方式* <input type="hidden" name="_method" value="PUT"/> * * 注意點2:* 這里在修改修改聯(lián)系人的時候,需要被修改聯(lián)系人的name屬性不能被修改* m is :Employee [id=1002, name=null, email=BB@ibigsea.com, sex=0, department=Department [id=101, name=null]]* */@RequestMapping(value="/addEmp", method=RequestMethod.PUT)public String update(@ModelAttribute("employ")Employee em){System.out.println("em is :"+em.toString());employeeDao.save(em);return "redirect:/emps";}/** 執(zhí)行添加聯(lián)系人操作,重定向到顯示所有聯(lián)系人的頁面* */@RequestMapping(value="/delete/{id}", method=RequestMethod.DELETE)public String deletEmp(@PathVariable("id") Integer id ){employeeDao.delEmpById(id);//employeeDao.save(employ);return "redirect:/emps";}/** 執(zhí)行添加聯(lián)系人操作,重定向到顯示所有聯(lián)系人的頁面* */@RequestMapping(value="/addEmp", method=RequestMethod.POST)public String addEmp(Employee em){employeeDao.save(em);return "redirect:/emps";}/*** 點擊添加聯(lián)系人,跳轉(zhuǎn)到添加聯(lián)系人頁面* */@RequestMapping(value="/emp",method=RequestMethod.GET)public String input(Map<String,Object> map){Collection<Department> departments = departmentDao.getAll();map.put("departments", departments);Employee employee = new Employee();map.put("employ", employee);return"input";}/** 查詢所有的員工信息* */@RequestMapping(value="/emps",method=RequestMethod.GET)public String listAllEmployees(Map<String,Object> map){Collection<Employee> allEmployees = employeeDao.getAll();map.put("employees", allEmployees);return"list";}}?
整個工程的代碼下載路徑地址是:
https://pan.baidu.com/s/1vP_BYybJnAByqSsp35o3Cg
轉(zhuǎn)載于:https://www.cnblogs.com/kebibuluan/p/8855057.html
總結(jié)
以上是生活随笔為你收集整理的springmvc-实现增删改查的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 修复Jscript(IE浏览器脚本引擎)
- 下一篇: .NET MVC Scripts.Re