首先需要准备好一张数据库表我这里用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页面(查找测试):

2.访问add.jsp:并且填入新员工的信息(增加测试):

点击提交:

小仙女添加进来了

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

修改完成。

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

删除成功。

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

springMVC实现增删改查的更多相关文章

  1. SpringMvc学习-增删改查

    本节主要介绍SpringMVC简单的增删改查功能. 1.查询 dao中的代码 public List<WeatherPojo> getAllWeather(){ String sql=&q ...

  2. springMVC之增删改查

    一.核心原理 1. 用于发送请求给server: /home.htm 2. 请求被DispatchServlet拦截到 3. DispatchServlet通过HandleMapping检查url有没 ...

  3. 基于SpringMVC的增删改查

    废话不多说,直接开始步骤! 1.创建一个Dynamic Web Project 2.在WEB-INF包下的lib文件夹中引入相关jar commons-logging-.jar jstl.jar sp ...

  4. 【SpringBoot】11-1.Springboot整合Springmvc+Mybatis增删改查操作(下)

    整合过程:https://www.isdxh.com/68.html 一.增--增加用户 1.创建实体类 package com.dxh.pojo; public class Users { priv ...

  5. SpringMVC框架下数据的增删改查,数据类型转换,数据格式化,数据校验,错误输入的消息回显

    在eclipse中javaEE环境下: 这儿并没有连接数据库,而是将数据存放在map集合中: 将各种架包导入lib下... web.xml文件配置为 <?xml version="1. ...

  6. springMVC操作mongoDB增删改查

    下面是mongoDb简单的增删改查(新闻类) 附:query.addCriteria(Criteria.where("modelId").ne("").ne(n ...

  7. SpringMVC,MyBatis商品的增删改查

    一.需求 商品的增删改查 二.工程结构 三.代码 1.Mapper层 (1) ItemsMapperCustom.java package com.tony.ssm.mapper; import ja ...

  8. SSM框架搭建(Spring+SpringMVC+MyBatis)与easyui集成并实现增删改查实现

    一.用myEclipse初始化Web项目 新建一个web project: 二.创建包 controller        //控制类 service //服务接口 service.impl //服务 ...

  9. SpringMVC之简单的增删改查示例(SSM整合)

    本篇文章主要介绍了SpringMVC之简单的增删改查示例(SSM整合),这个例子是基于SpringMVC+Spring+Mybatis实现的.有兴趣的可以了解一下. 虽然已经在做关于SpringMVC ...

随机推荐

  1. Spring Boot入门(一):使用IDEA创建Spring Boot项目并使用yaml配置文件

    由于公司最近在做技术转型(从.Net转Java),因此自己也开启了学习Java之路.学习Java怎么能不学习这几年这么火的Spring Boot框架,由于自己有总结的习惯,因此会把学习的过程以博客的形 ...

  2. Android之Fragment详解

    文章大纲 一. 什么是Fragment二. Fragment生命周期三. Fragment简单实例四.Fragment实战五.项目源码下载六.参考文章   一. 什么是Fragment Fragmen ...

  3. iTop软件功能分析以及优缺点比较

    iTop软件功能分析以及优缺点比较 iTop对标文档 1. 概述 2. CMDB 3. 主要功能模块 3.1 配置管理(Configuration Managment) 3.2 用户请求管理(Help ...

  4. mysql7笔记----遍历节点所有子节点

    mysql遍历节点的所有子节点 DELIMITER // CREATE FUNCTION `getChildrenList`(rootId INT) ) BEGIN ); ); SET sTemp = ...

  5. Sublime中文乱码解决方案

    1.首先按下ctrl+shift+P按键,将会出现输入框,其中输入install package. 一般情况下会在安装完成后直接出现输入框,输入ConvertToUtf8即可: 2.若未直接出现输入框 ...

  6. 如何快速掌握DDT数据驱动测试?

    1.前言 (网盗概念^-^)相同的测试脚本使用不同的测试数据来执行,测试数据和测试行为完全分离, 这样的测试脚本设计模式称为数据驱动.(网盗结束)当我们测试某个网站的登录功能时,我们往往会使用不同的用 ...

  7. pytest进阶之fixture

    前言 学pytest就不得不说fixture,fixture是pytest的精髓所在,就像unittest中的setup和teardown一样,如果不学fixture那么使用pytest和使用unit ...

  8. php实现中文字符串无乱码截取

    在PHP开发中会经常用到字符串截取,有的时候字符串截取会出现乱码的情况,那么怎么解决这个问题呢,其实也很容易 首先我们要了解关于中英文占多少字节的问题. ASCII码:一个中文汉字占两个字节的空间. ...

  9. ansible基础-Jinja2模版 | 过滤器

    Jinja2模版介绍 注:本文demo使用ansible2.7稳定版 在ansible基础-变量的「8.2 模版使用变量」章节中关于模版与变量也有所提及,有兴趣的同学可以去回顾一下. ansible通 ...

  10. Yii框架基础增删查改

    返回一条数据 Country::find()->one(); 返回所有数据 Country::find()->all(); 返回记录的数量 $country =Country::find( ...