springMVC实现增删改查

时间:2023-03-08 16:02:52

首先需要准备好一张数据库表我这里用emp这张表:具体代码:

 /*
SQLyog 企业版 - MySQL GUI v8.14
MySQL - 5.1.73-community
*********************************************************************
*/
/*!40101 SET NAMES utf8 */; create table `emp` (
`empno` double ,
`ename` varchar (60),
`job` varchar (60),
`mgr` double ,
`hiredate` varchar (60),
`sal` float ,
`comm` float ,
`deptno` double
);
insert into `emp` (`empno`, `ename`, `job`, `mgr`, `hiredate`, `sal`, `comm`, `deptno`) values('','SMITH','CLERK','','2018-10-28 10:22:37','','0.565','');
insert into `emp` (`empno`, `ename`, `job`, `mgr`, `hiredate`, `sal`, `comm`, `deptno`) values('','Allen','SALESMAN','','2018-10-28 10:22:37','','','');
insert into `emp` (`empno`, `ename`, `job`, `mgr`, `hiredate`, `sal`, `comm`, `deptno`) values('','Ward','SALESMAN','','2018-10-28 10:22:37','','','');
insert into `emp` (`empno`, `ename`, `job`, `mgr`, `hiredate`, `sal`, `comm`, `deptno`) values('','JONES','MANAGER','','2018-10-28 10:22:37','','','');
insert into `emp` (`empno`, `ename`, `job`, `mgr`, `hiredate`, `sal`, `comm`, `deptno`) values('','MARTIN','SALESMAN','','2018-10-28 10:22:37','','','');
insert into `emp` (`empno`, `ename`, `job`, `mgr`, `hiredate`, `sal`, `comm`, `deptno`) values('','CLARK','MANAGER','','2018-10-28 10:22:37','',NULL,'');
insert into `emp` (`empno`, `ename`, `job`, `mgr`, `hiredate`, `sal`, `comm`, `deptno`) values('','SCOTT','ANALYST','','2018-10-28 10:22:38','',NULL,'');
insert into `emp` (`empno`, `ename`, `job`, `mgr`, `hiredate`, `sal`, `comm`, `deptno`) values('','KING','PRESIDENT',NULL,'2018-10-28 10:22:38','',NULL,'');
insert into `emp` (`empno`, `ename`, `job`, `mgr`, `hiredate`, `sal`, `comm`, `deptno`) values('','TURNER','SALESMAN','','2018-10-28 10:22:38','','','');
insert into `emp` (`empno`, `ename`, `job`, `mgr`, `hiredate`, `sal`, `comm`, `deptno`) values('','ADAMS','CLERK','','2018-10-28 10:22:38','',NULL,'');
insert into `emp` (`empno`, `ename`, `job`, `mgr`, `hiredate`, `sal`, `comm`, `deptno`) values('','FORD','ANALYST','','2018-10-28 10:22:38','',NULL,'');

然后开始我们的增删改查工作:

第一步:建立一个Maven项目,我们这里命名为"lianxicrud",然后配置pom.xml:需要的jar包有:jstl,javax.servlet-api,spring-web,spring-webmvc,

spring-jdbc,mysql
 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>web01</groupId>
<artifactId>lianxicrud</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>lianxicrud Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
</dependencies>
<build>
<finalName>lianxicrud</finalName>
</build>
</project>

第二步:在WEB-INF下:建立springMVC-servlet.xml文件。配置springMVC-servlet.xml和WEB-INF下的web.xml

1.springMVC-servlet.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/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="controller" />
<context:component-scan base-package="dao" />
<context:component-scan base-package="biz" />
<mvc:annotation-driven />
<!-- 配置数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="url" value="jdbc:mysql://localhost:3306/test" />
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="username" value="root" />
<property name="password" value="66668888ZH" />
</bean>
<!-- 类似于ps对象的一个内容 -->
<bean id="jdbcTemplate"
class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 视图解析器 -->
<bean id="irvr"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="suffix" value=".jsp" />
<property name="prefix" value="/user/" />
</bean>
<!-- 注册拦截器 -->
<mvc:interceptors>
<bean id="encode" class="interruptor.EncodeInterceptor"/>
</mvc:interceptors> </beans>

web.xml:

 <!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>*.mvc</url-pattern>
</servlet-mapping>
</web-app>

第三步:编写bean,dao,biz,controller,以及处理字符编码集的interrupt

1.bean包:

package bean;

public class EmpBean {

    private Integer empNo;
private String eName;
private String job;
private Integer mgr;
private String hireDate;
private Double sal;
private Double comm;
private Integer deptNo;
public EmpBean() {
// TODO Auto-generated constructor stub
}
public Integer getEmpNo() {
return empNo;
}
public void setEmpNo(Integer empNo) {
this.empNo = empNo;
}
public String geteName() {
return eName;
}
public void seteName(String eName) {
this.eName = eName;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public Integer getMgr() {
return mgr;
}
public void setMgr(Integer mgr) {
this.mgr = mgr;
}
public String getHireDate() {
return hireDate;
}
public void setHireDate(String hireDate) {
this.hireDate = hireDate;
}
public Double getSal() {
return sal;
}
public void setSal(Double sal) {
this.sal = sal;
}
public Double getComm() {
return comm;
}
public void setComm(Double comm) {
this.comm = comm;
}
public Integer getDeptNo() {
return deptNo;
}
public void setDeptNo(Integer deptNo) {
this.deptNo = deptNo;
}
@Override
public String toString() {
return "EmpBean [empNo=" + empNo + ", eName=" + eName + ", job=" + job + ", mgr=" + mgr + ", hireDate="
+ hireDate + ", sal=" + sal + ", comm=" + comm + ", deptNo=" + deptNo + "]";
} }

2.dao包:

 package dao;

 import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository; import bean.EmpBean; @Repository
public class EmpDAO { @Autowired
private JdbcTemplate jt; public void add(EmpBean eb) {
String sql = "insert into emp values(null,?,?,?,?,?,?,?)";
jt.update(sql, eb.geteName(),eb.getJob(),eb.getMgr(),eb.getHireDate(),eb.getSal(),eb.getComm(),eb.getDeptNo());
} public void delete(int empNo) {
String sql = "delete from emp where empno = ?";
jt.update(sql,empNo);
} public void update(EmpBean eb) {
String sql = "update emp set ename=?,job=?,mgr=?,hiredate=?,sal=?,comm=?,daptno=? where empno=?";
jt.update(sql,eb.geteName(),eb.getJob(),eb.getMgr(),eb.getHireDate(),eb.getSal(),eb.getComm(),eb.getDeptNo(),eb.getEmpNo());
} public List<EmpBean>findAll(){
String sql = "select * from emp";
return jt.query(sql, new RowMapperImpl());
} public EmpBean findById(int empNo) {
String sql = "select * from emp where empNo ='" + empNo + "'";
return jt.query(sql, new RowMapperImpl()).get(0);
}
} class RowMapperImpl implements RowMapper<EmpBean>{
//对象关系映射(ORM),将查询出来的结果映射成类的属性
@Override
public EmpBean mapRow(ResultSet rs, int rowNum) throws SQLException {
EmpBean eb = new EmpBean();
eb.setEmpNo(rs.getInt(1));
eb.seteName(rs.getString(2));
eb.setJob(rs.getString(3));
eb.setMgr(rs.getInt(4));
eb.setHireDate(rs.getString(5));
eb.setSal(rs.getDouble(6));
eb.setComm(rs.getDouble(7));
eb.setDeptNo(rs.getInt(8));
return eb;
}
}

3.biz包:

 package biz;

 import java.util.List;

 import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import bean.EmpBean;
import dao.EmpDAO; @Service
public class EmpBiz { @Autowired
private EmpDAO edao;
public void add(EmpBean eb) {
edao.add(eb);
} public void delete(int empNo) {
edao.delete(empNo);
} public void update(EmpBean eb) {
edao.update(eb);
} public List<EmpBean>findAll(){
return edao.findAll();
} public EmpBean findById(int empNo) {
return edao.findById(empNo);
}
}

4.controller包:

 package controller;

 import javax.servlet.http.HttpServletRequest;

 import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping; import bean.EmpBean;
import biz.EmpBiz; @Controller
@RequestMapping("/emp")
public class EmpController {
@Autowired
private EmpBiz eb;
@RequestMapping("/add")
public String add(EmpBean emp) {
eb.add(emp);
return "redirect:../index.jsp";
} @RequestMapping("/find")
public String findAll(HttpServletRequest request) {
request.getSession().setAttribute("ALLEMP",eb.findAll());
return "redirect:../index.jsp";
} @RequestMapping("/delete")
public String delete(int empNo) {
eb.delete(empNo);
return "redirect:../index.jsp";
} @RequestMapping("/findbyid")
public String findById(int empNo , HttpServletRequest request) {
request.getSession().setAttribute("EMPBEAN", eb.findById(empNo));
System.out.println("11111");
return "redirect:../update.jsp";
} @RequestMapping("/update")
public String update(EmpBean emp) {
eb.update(emp);
System.out.println("22222222");
return "redirect:../index.jsp";
}
}

interrupt包:

 package interruptor;

 import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView; //建立一个拦截器(类似于Filter)
public class EncodeInterceptor implements HandlerInterceptor{ @Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
} @Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
//针对post请求的编码集操作
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
return true;
} }

第四步:页面处理(为了方便index.jsp只查了这张表的姓名和员工编号,如果想显示更多可以进行查询,方法雷同)这里一定要注意加上isELIgnored="false",不然查不出来,下午找了一下午错误,原来忘了加这句话,哈哈

1.index.jsp:

 <%@ page language="java" pageEncoding="utf-8" isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<body>
<c:if test="${empty ALLEMP}">
<c:redirect url="emp/find.mvc"/>
</c:if> <c:forEach var="ei" items="${ALLEMP}">
${ei.empNo} ${ei.eName}
<a href="emp/delete.mvc?empNo=${ei.empNo }">删除</a>
<a href="emp/findbyid.mvc?empNo=${ei.empNo }">修改</a>
<br/>
</c:forEach>
</body>
</html>

2.注册新员工页面:add.jsp:

 <%@ page language="java" pageEncoding="utf-8" isELIgnored="false"%>
<html>
<head>
<title>注册新员工</title>
<style type="text/css">
table {
margin: 0 auto;
border: 1px gray solid;
width: 70%;
}
td,th{
border: 1px gray solid;
}
</style>
</head>
<body>
<form action="emp/add.mvc" method="post">
<table>
<tr>
<h2 align="center">公司员工注册表</h2>
</tr>
<tr>
<th>姓名</th>
<td>
<input type="text" name="eName"/>
</td>
</tr>
<tr>
<th>职位</th>
<td>
<input type="text" name="job"/>
</td>
</tr>
<tr>
<th>上司</th>
<td>
<input type="text" name="mgr"/>
</td>
</tr>
<tr>
<th>入职时间</th>
<td>
<input type="text" name="hireDate"/>
</td>
</tr>
<tr>
<th>薪资</th>
<td>
<input type="text" name="sal"/>
</td>
</tr>
<tr>
<th>奖金</th>
<td>
<input type="text" name="comm"/>
</td>
</tr>
<tr>
<th>部门</th>
<td>
<input type="text" name="deptNo"/>
</td>
</tr>
<tr>
<th colspan="1">
<input type="submit" values = "注册新员工"/>
</th>
</tr>
</table>
</form>
</body>
</html>

3.修改页面:update.jsp:

 <%@ page language="java"  pageEncoding="utf-8" isELIgnored="false"%>
<html>
<head>
<title>修改员工信息</title>
<style type="text/css">
table {
margin: 0 auto;
border: 1px gray solid;
width: 70%;
}
td,th{
border: 1px gray solid;
}
</style> </head>
<body> <form action="emp/update.mvc" method="post">
<input type="hidden" name="empNo" value="${EMPBEAN.empNo }"/>
<table>
<tr>
<h2 align="center">修改员工信息</h2>
</tr>
<tr>
<th>姓名</th>
<td>
<input type="text" name="eName" value="${EMPBEAN.eName }"/>
</td>
</tr>
<tr>
<th>职位</th>
<td>
<input type="text" name="job" value="${EMPBEAN.job }"/>
</td>
</tr>
<tr>
<th>上司</th>
<td>
<input type="text" name="mgr" value="${EMPBEAN.mgr }"/>
</td>
</tr>
<tr>
<th>入职时间</th>
<td>
<input type="text" name="hireDate" value="${EMPBEAN.hireDate }"/>
</td>
</tr>
<tr>
<th>薪金</th>
<td>
<input type="text" name="sal" value="${EMPBEAN.sal }"/>
</td>
</tr>
<tr>
<th>奖金</th>
<td>
<input type="text" name="comm" value="${EMPBEAN.comm }"/>
</td>
</tr>
<tr>
<th>部门</th>
<td>
<input type="text" name="daptNo" value="${EMPBEAN.deptNo }"/>
</td>
</tr>
<tr>
<th colspan="2">
<input type="submit" value="提交修改信息"/>
</th>
</tr>
</table>
</form> </body>
</html>

以上四大步就是SpringMVC实现增删改查的具体操作。

下面我们来进行测试:

1.首先我们启动我们的服务器,然后访问我们的index.jsp页面(查找测试):

springMVC实现增删改查

2.访问add.jsp:并且填入新员工的信息(增加测试):springMVC实现增删改查

点击提交:

springMVC实现增删改查

小仙女添加进来了

然后点击修改进行修改测试:我们把小仙女改成老仙女

springMVC实现增删改查

修改完成。

然后点击老仙女的删除(删除测试)

springMVC实现增删改查

删除成功。

其实这个还可以加入BootStrap将页面进行美化操作