zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Spring MVC框架:第六章:传统增删改查

Spring框架MVC 传统 增删 改查 第六章
2023-06-13 09:13:27 时间

传统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

创建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>
    配置静态资源访问(如果有)
    <!-- 保证常规资源可以访问 -->
<mvc:annotation-driven></mvc:annotation-driven>
<!-- 保证静态资源可以访问 -->
<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>

创建实体类
    Employee
    Department

创建Dao
    DeptDao
    EmpDao

创建Service
    装配EmpDao
    装配DeptDao

创建Handler
    装配Service

创建index.jsp
    点一个超链接,到目标页面显示Employee的list

根据id删除Employee

创建Employee
    准备表单
    执行保存操作

更新Employee
    回显表单
    执行更新操作

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("技术部")));
        
        empId = UUID.randomUUID().toString();
        dataMap.put(empId, new Employee(empId, "萧远山", "SSN005", DeptDao.getDeptByName("技术部")));
        
        empId = UUID.randomUUID().toString();
        dataMap.put(empId, new Employee(empId, "慕容复", "SSN006", DeptDao.getDeptByName("技术部")));
        
        empId = UUID.randomUUID().toString();
        dataMap.put(empId, new Employee(empId, "段正淳", "SSN007", DeptDao.getDeptByName("公关部")));
        
        empId = UUID.randomUUID().toString();
        dataMap.put(empId, new Employee(empId, "段延庆", "SSN008", DeptDao.getDeptByName("公关部")));
        
        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(), "技术部");
        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);

    }

    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>
    <!-- 保证常规资源可以访问 -->
    <mvc:annotation-driven></mvc:annotation-driven>
    <!-- 保证静态资源可以访问 -->
    <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>没有查询到数据</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>部门数据查询失败!!!</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>