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

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

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

相关文章
|
4月前
|
安全 Java Ruby
我尝试了所有后端框架 — — 这就是为什么只有 Spring Boot 幸存下来
作者回顾后端开发历程,指出多数框架在生产环境中难堪重负。相比之下,Spring Boot凭借内置安全、稳定扩展、完善生态和企业级支持,成为构建高可用系统的首选,真正经受住了时间与规模的考验。
354 2
|
3月前
|
安全 前端开发 Java
《深入理解Spring》:现代Java开发的核心框架
Spring自2003年诞生以来,已成为Java企业级开发的基石,凭借IoC、AOP、声明式编程等核心特性,极大简化了开发复杂度。本系列将深入解析Spring框架核心原理及Spring Boot、Cloud、Security等生态组件,助力开发者构建高效、可扩展的应用体系。(238字)
|
5月前
|
XML JSON Java
Spring框架中常见注解的使用规则与最佳实践
本文介绍了Spring框架中常见注解的使用规则与最佳实践,重点对比了URL参数与表单参数的区别,并详细说明了@RequestParam、@PathVariable、@RequestBody等注解的应用场景。同时通过表格和案例分析,帮助开发者正确选择参数绑定方式,避免常见误区,提升代码的可读性与安全性。
|
6月前
|
Java Spring
聊聊你对SpringBoot框架的理解 ?
SpringBoot是Spring家族中流行的子项目,旨在简化Spring框架开发的繁琐配置。它主要提供三大功能:starter起步依赖简化依赖管理,自动配置根据条件创建Bean,以及内嵌Web服务器支持Jar包运行,极大提升了开发效率。
197 0
|
3月前
|
前端开发 Java 微服务
《深入理解Spring》:Spring、Spring MVC与Spring Boot的深度解析
Spring Framework是Java生态的基石,提供IoC、AOP等核心功能;Spring MVC基于其构建,实现Web层MVC架构;Spring Boot则通过自动配置和内嵌服务器,极大简化了开发与部署。三者层层演进,Spring Boot并非替代,而是对前者的高效封装与增强,适用于微服务与快速开发,而深入理解Spring Framework有助于更好驾驭整体技术栈。
|
3月前
|
消息中间件 缓存 Java
Spring框架优化:提高Java应用的性能与适应性
以上方法均旨在综合考虑Java Spring 应该程序设计原则, 数据库交互, 编码实践和系统架构布局等多角度因素, 旨在达到高效稳定运转目标同时也易于未来扩展.
172 8
|
4月前
|
监控 Kubernetes Cloud Native
Spring Batch 批处理框架技术详解与实践指南
本文档全面介绍 Spring Batch 批处理框架的核心架构、关键组件和实际应用场景。作为 Spring 生态系统中专门处理大规模数据批处理的框架,Spring Batch 为企业级批处理作业提供了可靠的解决方案。本文将深入探讨其作业流程、组件模型、错误处理机制、性能优化策略以及与现代云原生环境的集成方式,帮助开发者构建高效、稳定的批处理系统。
534 1
|
6月前
|
安全 Java 微服务
Java 最新技术和框架实操:涵盖 JDK 21 新特性与 Spring Security 6.x 安全框架搭建
本文系统整理了Java最新技术与主流框架实操内容,涵盖Java 17+新特性(如模式匹配、文本块、记录类)、Spring Boot 3微服务开发、响应式编程(WebFlux)、容器化部署(Docker+K8s)、测试与CI/CD实践,附完整代码示例和学习资源推荐,助你构建现代Java全栈开发能力。
717 0
|
5月前
|
Cloud Native Java API
Java Spring框架技术栈选和最新版本及发展史详解(截至2025年8月)-优雅草卓伊凡
Java Spring框架技术栈选和最新版本及发展史详解(截至2025年8月)-优雅草卓伊凡
1115 0
|
6月前
|
NoSQL Java 数据库连接
SpringBoot框架
Spring Boot 是 Spring 家族中最流行的框架,旨在简化 Spring 应用的初始搭建与开发。它通过自动配置、起步依赖和内嵌服务器三大核心功能,大幅减少配置复杂度,提升开发效率。开发者可快速构建独立运行的 Web 应用,并支持多种数据访问技术和第三方集成。