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>

相关文章
|
23天前
|
数据采集 监控 前端开发
二级公立医院绩效考核系统源码,B/S架构,前后端分别基于Spring Boot和Avue框架
医院绩效管理系统通过与HIS系统的无缝对接,实现数据网络化采集、评价结果透明化管理及奖金分配自动化生成。系统涵盖科室和个人绩效考核、医疗质量考核、数据采集、绩效工资核算、收支核算、工作量统计、单项奖惩等功能,提升绩效评估的全面性、准确性和公正性。技术栈采用B/S架构,前后端分别基于Spring Boot和Avue框架。
|
1月前
|
Java API 数据库
构建RESTful API已经成为现代Web开发的标准做法之一。Spring Boot框架因其简洁的配置、快速的启动特性及丰富的功能集而备受开发者青睐。
【10月更文挑战第11天】本文介绍如何使用Spring Boot构建在线图书管理系统的RESTful API。通过创建Spring Boot项目,定义`Book`实体类、`BookRepository`接口和`BookService`服务类,最后实现`BookController`控制器来处理HTTP请求,展示了从基础环境搭建到API测试的完整过程。
42 4
|
1月前
|
JavaScript 安全 Java
如何使用 Spring Boot 和 Ant Design Pro Vue 实现动态路由和菜单功能,快速搭建前后端分离的应用框架
本文介绍了如何使用 Spring Boot 和 Ant Design Pro Vue 实现动态路由和菜单功能,快速搭建前后端分离的应用框架。首先,确保开发环境已安装必要的工具,然后创建并配置 Spring Boot 项目,包括添加依赖和配置 Spring Security。接着,创建后端 API 和前端项目,配置动态路由和菜单。最后,运行项目并分享实践心得,包括版本兼容性、安全性、性能调优等方面。
152 1
|
1月前
|
Java API 数据库
Spring Boot框架因其简洁的配置、快速的启动特性及丰富的功能集而备受开发者青睐
本文通过在线图书管理系统案例,详细介绍如何使用Spring Boot构建RESTful API。从项目基础环境搭建、实体类与数据访问层定义,到业务逻辑实现和控制器编写,逐步展示了Spring Boot的简洁配置和强大功能。最后,通过Postman测试API,并介绍了如何添加安全性和异常处理,确保API的稳定性和安全性。
38 0
|
27天前
|
前端开发 Java 数据库连接
Spring 框架:Java 开发者的春天
Spring 框架是一个功能强大的开源框架,主要用于简化 Java 企业级应用的开发,由被称为“Spring 之父”的 Rod Johnson 于 2002 年提出并创立,并由Pivotal团队维护。
43 1
Spring 框架:Java 开发者的春天
|
20天前
|
JavaScript 安全 Java
如何使用 Spring Boot 和 Ant Design Pro Vue 构建一个前后端分离的应用框架,实现动态路由和菜单功能
本文介绍了如何使用 Spring Boot 和 Ant Design Pro Vue 构建一个前后端分离的应用框架,实现动态路由和菜单功能。首先,确保开发环境已安装必要的工具,然后创建并配置 Spring Boot 项目,包括添加依赖和配置 Spring Security。接着,创建后端 API 和前端项目,配置动态路由和菜单。最后,运行项目并分享实践心得,帮助开发者提高开发效率和应用的可维护性。
37 2
|
19天前
|
消息中间件 NoSQL Java
springboot整合常用中间件框架案例
该项目是Spring Boot集成整合案例,涵盖多种中间件的使用示例,每个案例项目使用最小依赖,便于直接应用到自己的项目中。包括MyBatis、Redis、MongoDB、MQ、ES等的整合示例。
77 1
|
27天前
|
Java 数据库连接 开发者
Spring 框架:Java 开发者的春天
【10月更文挑战第27天】Spring 框架由 Rod Johnson 在 2002 年创建,旨在解决 Java 企业级开发中的复杂性问题。它通过控制反转(IOC)和面向切面的编程(AOP)等核心机制,提供了轻量级的容器和丰富的功能,支持 Web 开发、数据访问等领域,显著提高了开发效率和应用的可维护性。Spring 拥有强大的社区支持和丰富的生态系统,是 Java 开发不可或缺的工具。
|
1月前
|
人工智能 Java API
阿里云开源 AI 应用开发框架:Spring AI Alibaba
近期,阿里云重磅发布了首款面向 Java 开发者的开源 AI 应用开发框架:Spring AI Alibaba(项目 Github 仓库地址:alibaba/spring-ai-alibaba),Spring AI Alibaba 项目基于 Spring AI 构建,是阿里云通义系列模型及服务在 Java AI 应用开发领域的最佳实践,提供高层次的 AI API 抽象与云原生基础设施集成方案,帮助开发者快速构建 AI 应用。本文将详细介绍 Spring AI Alibaba 的核心特性,并通过「智能机票助手」的示例直观的展示 Spring AI Alibaba 开发 AI 应用的便利性。示例源
|
1月前
|
人工智能 开发框架 Java
总计 30 万奖金,Spring AI Alibaba 应用框架挑战赛开赛
Spring AI Alibaba 应用框架挑战赛邀请广大开发者参与开源项目的共建,助力项目快速发展,掌握 AI 应用开发模式。大赛分为《支持 Spring AI Alibaba 应用可视化调试与追踪本地工具》和《基于 Flow 的 AI 编排机制设计与实现》两个赛道,总计 30 万奖金。
下一篇
无影云桌面