Spring MVC框架:第六章:傳統(tǒng)增刪改查
傳統(tǒng)CRUD
列表頁面:
添加頁面:
編輯頁面:
刪除操作:
導入SpringMVC jar包
commons-logging-1.1.3.jar
spring-aop-4.0.0.RELEASE.jar
spring-beans-4.0.0.RELEASE.jar
spring-context-4.0.0.RELEASE.jar
spring-core-4.0.0.RELEASE.jar
spring-expression-4.0.0.RELEASE.jar
spring-web-4.0.0.RELEASE.jar
spring-webmvc-4.0.0.RELEASE.jar
taglibs-standard-impl-1.2.1.jar
taglibs-standard-spec-1.2.1.jar
創(chuàng)建SpringMVC配置文件:spring-mvc.xml
配置自動掃描的包
<!-- 包掃描 -->
<context:component-scan base-package="com.*" />
配置視圖解析器
<!-- 加前綴后綴 -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/page/" />
<property name="suffix" value=".jsp" />
</bean>
配置靜態(tài)資源訪問(如果有)
<!-- 保證常規(guī)資源可以訪問 -->
<mvc:annotation-driven></mvc:annotation-driven>
<!-- 保證靜態(tài)資源可以訪問 -->
<mvc:default-servlet-handler />
配置view-controller(如果有)這里我沒有使用
配置web.xml
DispatcherServlet
<!-- The front controller of this Spring Web application, responsible for
handling all application requests -->
<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:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Map all requests to the DispatcherServlet for handling -->
<servlet-mapping>
<servlet-name>springDispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
創(chuàng)建實體類
Employee
Department
創(chuàng)建Dao
DeptDao
EmpDao
創(chuàng)建Service
裝配EmpDao
裝配DeptDao
創(chuàng)建Handler
裝配Service
創(chuàng)建index.jsp
點一個超鏈接,到目標頁面顯示Employee的list
根據(jù)id刪除Employee
創(chuàng)建Employee
準備表單
執(zhí)行保存操作
更新Employee
回顯表單
執(zhí)行更新操作
1.實體類
Department 類
public class Department {
private String deptId;
private String deptName;
public Department() {
}
public Department(String deptId, String deptName) {
super();
this.deptId = deptId;
this.deptName = deptName;
}
public String getDeptId() {
return deptId;
}
public void setDeptId(String deptId) {
this.deptId = deptId;
}
public String getDeptName() {
return deptName;
}
public void setDeptName(String deptName) {
this.deptName = deptName;
}
@Override
public String toString() {
return "Department [deptId=" + deptId + ", deptName=" + deptName + "]";
}
}
Employee類:
public class Employee {
private String empId;
private String empName;
private String ssn;
private Department department;
public Employee(String empId, String empName, String ssn, Department department) {
super();
this.empId = empId;
this.empName = empName;
this.ssn = ssn;
this.department = department;
}
public Employee() {
}
public String getEmpId() {
return empId;
}
public void setEmpId(String empId) {
this.empId = empId;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public String getSsn() {
return ssn;
}
public void setSsn(String ssn) {
this.ssn = ssn;
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
@Override
public String toString() {
return "Employee [empId=" + empId + ", empName=" + empName + ", ssn=" + ssn + ", department=" + department
+ "]";
}
}
2.Dao
EmpDao:
package com.dao;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.springframework.stereotype.Repository;
import com.pojo.Department;
import com.pojo.Employee;
@Repository
public class EmpDao {
private static Map<String, Employee> dataMap;
static {
dataMap = new HashMap<>();
String empId = UUID.randomUUID().toString();
dataMap.put(empId, new Employee(empId, “喬峰”, “SSN001”, DeptDao.getDeptByName(“市場部”)));
empId = UUID.randomUUID().toString();
dataMap.put(empId, new Employee(empId, "虛竹", "SSN002", DeptDao.getDeptByName("市場部")));
empId = UUID.randomUUID().toString();
dataMap.put(empId, new Employee(empId, "段譽", "SSN003", DeptDao.getDeptByName("市場部")));
empId = UUID.randomUUID().toString();
dataMap.put(empId, new Employee(empId, "鳩摩智", "SSN004", DeptDao.getDeptByName("技術(shù)部")));
empId = UUID.randomUUID().toString();
dataMap.put(empId, new Employee(empId, "蕭遠山", "SSN005", DeptDao.getDeptByName("技術(shù)部")));
empId = UUID.randomUUID().toString();
dataMap.put(empId, new Employee(empId, "慕容復", "SSN006", DeptDao.getDeptByName("技術(shù)部")));
empId = UUID.randomUUID().toString();
dataMap.put(empId, new Employee(empId, "段正淳", "SSN007", DeptDao.getDeptByName("公關(guān)部")));
empId = UUID.randomUUID().toString();
dataMap.put(empId, new Employee(empId, "段延慶", "SSN008", DeptDao.getDeptByName("公關(guān)部")));
empId = UUID.randomUUID().toString();
dataMap.put(empId, new Employee(empId, "丁春秋", "SSN009", DeptDao.getDeptByName("銷售部")));
empId = UUID.randomUUID().toString();
dataMap.put(empId, new Employee(empId, "無崖子", "SSN010", DeptDao.getDeptByName("人事部")));
empId = UUID.randomUUID().toString();
dataMap.put(empId, new Employee(empId, "慕容博", "SSN011", DeptDao.getDeptByName("人事部")));
}
public void saveEmp(Employee employee) {
String empId = UUID.randomUUID().toString();
employee.setEmpId(empId);
String deptId = employee.getDepartment().getDeptId();
Department department = DeptDao.getDeptById(deptId);
employee.setDepartment(department);
dataMap.put(empId, employee);
}
public void removeEmp(String empId) {
dataMap.remove(empId);
}
public void updateEmp(Employee employee) {
String deptId = employee.getDepartment().getDeptId();
Department department = DeptDao.getDeptById(deptId);
employee.setDepartment(department);
dataMap.put(employee.getEmpId(), employee);
}
public Employee getEmpById(String empId) {
return dataMap.get(empId);
}
public List<Employee> getEmpList() {
return new ArrayList<>(dataMap.values());
}
}
DeptDao:
package com.dao;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.springframework.stereotype.Repository;
import com.pojo.Department;
@Repository
public class DeptDao {
private static Map<String, Department> dataMap;
private static Map<String, Department> namedMap;
static {
dataMap = new HashMap<>();
namedMap = new HashMap<>();
Department department = new Department(UUID.randomUUID().toString(), "市場部");
dataMap.put(department.getDeptId(), department);
namedMap.put(department.getDeptName(), department);
department = new Department(UUID.randomUUID().toString(), "銷售部");
dataMap.put(department.getDeptId(), department);
namedMap.put(department.getDeptName(), department);
department = new Department(UUID.randomUUID().toString(), "行政部");
dataMap.put(department.getDeptId(), department);
namedMap.put(department.getDeptName(), department);
department = new Department(UUID.randomUUID().toString(), "人事部");
dataMap.put(department.getDeptId(), department);
namedMap.put(department.getDeptName(), department);
department = new Department(UUID.randomUUID().toString(), "技術(shù)部");
dataMap.put(department.getDeptId(), department);
namedMap.put(department.getDeptName(), department);
department = new Department(UUID.randomUUID().toString(), "公關(guān)部");
dataMap.put(department.getDeptId(), department);
namedMap.put(department.getDeptName(), department);
}
public static Department getDeptByName(String deptName) {
return namedMap.get(deptName);
}
public static Department getDeptById(String uuid) {
return dataMap.get(uuid);
}
public List<Department> getDeptList() {
return new ArrayList<>(dataMap.values());
}
}
3.Services:
package com.services;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.dao.DeptDao;
import com.dao.EmpDao;
import com.pojo.Department;
import com.pojo.Employee;
@Service
public class Services {
@Autowired
private DeptDao deptDao;
@Autowired
private EmpDao empDao;
public List<Department> deptDaoList(){
return deptDao.getDeptList();
};
public List<Employee> empDaoList(){
return empDao.getEmpList();
}
public void saveData(Employee employee) {
empDao.saveEmp(employee);
}
public void delectData(String empId) {
empDao.removeEmp(empId);
}
public Employee emdit(String empId) {
Employee empById = empDao.getEmpById(empId);
return empById;
}
public void updateEmp(Employee employee) {
empDao.updateEmp(employee);
}
}
4.handled:
package com.handled;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.pojo.Department;
import com.pojo.Employee;
import com.services.Services;
@Controller
public class Handled {
@Autowired
private Services services;
@RequestMapping("/list")
public String list(Model model) {
List<Employee> empDaoList = services.empDaoList();
model.addAttribute("list", empDaoList);
return "dataList";
}
@RequestMapping("/addData")
public String toAdd(Model model) {
List<Department> deptDaoList = services.deptDaoList();
model.addAttribute("deptList", deptDaoList);
return "dataAdd";
}
@RequestMapping("/submitData")
public String submit(Employee employee) {
services.saveData(employee);
return "redirect:/list";
}
@RequestMapping("/removeData")
public String removeData(String empId) {
services.delectData(empId);
return "redirect:/list";
}
@RequestMapping("/emditData")
public String emditData(String empId,Model model) {
Employee emdit = services.emdit(empId);
List<Department> deptDaoList = services.deptDaoList();
model.addAttribute("emdit",emdit);
model.addAttribute("deptList",deptDaoList);
return "dataEdit";
}
@RequestMapping("/submitEmpData")
public String submitEmp(Employee employee) {
services.updateEmp(employee);
return "redirect:/list";
}
}
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.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.*" />
<!-- 加前綴后綴 -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/page/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- 保證常規(guī)資源可以訪問 -->
<mvc:annotation-driven></mvc:annotation-driven>
<!-- 保證靜態(tài)資源可以訪問 -->
<mvc:default-servlet-handler />
</beans>
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_2_5.xsd"
id="WebApp_ID" version="2.5">
<!-- The front controller of this Spring Web application, responsible for
handling all application requests -->
<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:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Map all requests to the DispatcherServlet for handling -->
<servlet-mapping>
<servlet-name>springDispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<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>
</web-app>
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>
<a href="${pageContext.request.contextPath }/list">去列表</a>
</body>
</html>
dataList.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>Insert title here</title>
<script type="text/javascript" src="${pageContext.request.contextPath }/script/jquery-1.7.2.js"></script>
<script type="text/javascript">
$(function(){
$(".remove").click(function(){
var data = $(this).parents("tr").children("td:eq(1)").text();
var confirm = window.confirm("你確定要"+data+"刪除嗎?");
if(!confirm){
return false;
}
});
});
</script>
</head>
<body>
<center>
<table>
<c:if test="${empty requestScope.list }">
<tr>
<td>沒有查詢到數(shù)據(jù)</td>
</tr>
</c:if>
<c:if test="${!empty requestScope.list }">
<tr>
<td>ID</td>
<td>姓名</td>
<td>SSN</td>
<td>部門名稱</td>
<td colspan="2">操作</td>
</tr>
<c:forEach items="${requestScope.list }" var="list">
<tr>
<td>${list.empId}</td>
<td>${list.empName}</td>
<td>${list.ssn }</td>
<td>${list.department.deptName }</td>
<td><a href="${pageContext.request.contextPath }/removeData?empId=${list.empId }" class="remove">刪除</a></td>
<td><a href="${pageContext.request.contextPath }/emditData?empId=${list.empId}">編輯</a></td>
</tr>
</c:forEach>
</c:if>
<tr>
<td colspan="6" align="center">
<a href="${pageContext.request.contextPath }/addData">添加</a></td>
</tr>
</table>
</center>
</body>
</html>
dataAdd.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>Insert title here</title>
</head>
<body>
<form action="${pageContext.request.contextPath }/submitData" method="post">
<table>
<tr>
<td>姓名</td>
<td>
<input type="text" name="empName"/>
</td>
</tr>
<tr>
<td>SSN</td>
<td>
<input type="text" name="ssn"/>
</td>
</tr>
<tr>
<td>所在部門</td>
<td>
<select name="department.deptId">
<c:if test="${empty deptList }">
<option>部門數(shù)據(jù)查詢失敗?。?!</option>
</c:if>
<c:if test="${!empty deptList }">
<c:forEach items="${requestScope.deptList}" var="dept">
<option value="${dept.deptId }">${dept.deptName }</option>
</c:forEach>
</c:if>
</select>
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="保存"/>
</td>
</tr>
</table>
</form>
</body>
</html>
dataEdit.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>Insert title here</title>
</head>
<body>
<form action="${pageContext.request.contextPath }/submitEmpData"
method="post">
<input type="hidden" name="empId" value="${requestScope.emdit.empId }"/>
<table>
<tr>
<td>姓名</td>
<td><input type="text" name="empName" value="${emdit.empName }" />
</td>
</tr>
<tr>
<td>SSN</td>
<td><input type="text" name="ssn" value="${emdit.ssn }" /></td>
</tr>
<tr>
<td>所在部門</td>
<td><select name="department.deptId">
<c:if test="${!empty deptList }">
<c:forEach items="${requestScope.deptList}" var="dept">
<c:if test="${dept.deptId==requestScope.emdit.department.deptId }">
<option value="${dept.deptId }" selected="selected">${dept.deptName }</option>
</c:if>
<option value="${dept.deptId }" selected="selected">${dept.deptName }</option>
</c:forEach>
</c:if>
</select></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="保存" /></td>
</tr>
</table>
</form>
</body>
</html>