springMVC实现增删改查
首先需要准备好一张数据库表我这里用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实现增删改查的更多相关文章
- SpringMvc学习-增删改查
本节主要介绍SpringMVC简单的增删改查功能. 1.查询 dao中的代码 public List<WeatherPojo> getAllWeather(){ String sql=&q ...
- springMVC之增删改查
一.核心原理 1. 用于发送请求给server: /home.htm 2. 请求被DispatchServlet拦截到 3. DispatchServlet通过HandleMapping检查url有没 ...
- 基于SpringMVC的增删改查
废话不多说,直接开始步骤! 1.创建一个Dynamic Web Project 2.在WEB-INF包下的lib文件夹中引入相关jar commons-logging-.jar jstl.jar sp ...
- 【SpringBoot】11-1.Springboot整合Springmvc+Mybatis增删改查操作(下)
整合过程:https://www.isdxh.com/68.html 一.增--增加用户 1.创建实体类 package com.dxh.pojo; public class Users { priv ...
- SpringMVC框架下数据的增删改查,数据类型转换,数据格式化,数据校验,错误输入的消息回显
在eclipse中javaEE环境下: 这儿并没有连接数据库,而是将数据存放在map集合中: 将各种架包导入lib下... web.xml文件配置为 <?xml version="1. ...
- springMVC操作mongoDB增删改查
下面是mongoDb简单的增删改查(新闻类) 附:query.addCriteria(Criteria.where("modelId").ne("").ne(n ...
- SpringMVC,MyBatis商品的增删改查
一.需求 商品的增删改查 二.工程结构 三.代码 1.Mapper层 (1) ItemsMapperCustom.java package com.tony.ssm.mapper; import ja ...
- SSM框架搭建(Spring+SpringMVC+MyBatis)与easyui集成并实现增删改查实现
一.用myEclipse初始化Web项目 新建一个web project: 二.创建包 controller //控制类 service //服务接口 service.impl //服务 ...
- SpringMVC之简单的增删改查示例(SSM整合)
本篇文章主要介绍了SpringMVC之简单的增删改查示例(SSM整合),这个例子是基于SpringMVC+Spring+Mybatis实现的.有兴趣的可以了解一下. 虽然已经在做关于SpringMVC ...
随机推荐
- Vue 进阶之路(六)
上篇文章我们分析了一下 vue 中的条件渲染,本篇我们说一下 vue 中的列表渲染和 set 方法. <!DOCTYPE html> <html lang="en" ...
- Docker最全教程之Python爬网实战(二十一)
Python目前是流行度增长最快的主流编程语言,也是第二大最受开发者喜爱的语言(参考Stack Overflow 2019开发者调查报告发布).笔者建议.NET.Java开发人员可以将Python发展 ...
- 联发科Helio P90(mt6779),P70(mt6775),P60(MT6771),P35,P22(MT6762)芯片参数规格
Helio P90(mt6779)是一款人工智能处理平台,集成了超级强大的AI专核APU 2.0,具有超强的AI性能和一系列基于人工智能的成像升级.该芯片将重新定义消费者对智能手机AI功能的体验.He ...
- mssql sqlserver isnull coalesce函数用法区别说明
摘要: 下文讲述isnull及coalesce空值替换函数的区别 isnull.coalesce函数区别:1.isnull 只能接受两个参数,而coalesce函数可以接受大于等于两个以上参数2.is ...
- Windows系统配置OutLook邮箱教程一
本示例演示Windows系统中OutLook邮箱设置 1.打开控制面板->类型选择小图标->找到Mail(Microsoft OutLook 2016). 2.鼠标左键双击Mail. 3. ...
- 使用 certbot 申请泛域名https证书
使用 certbot 申请泛域名https证书 Intro Certbot 是一个基于 Let's Encrypt 的自动化申请证书的工具,支持的系统和web server也很多,详见 Certbot ...
- 基于python语言的tensorflow的‘端到端’的字符型验证码识别源码整理(github源码分享)
基于python语言的tensorflow的‘端到端’的字符型验证码识别 1 Abstract 验证码(CAPTCHA)的诞生本身是为了自动区分 自然人 和 机器人 的一套公开方法, 但是近几年的 ...
- 【死磕 Spring】—– IOC 之解析Bean:解析 import 标签
原文出自:http://cmsblogs.com 在博客[死磕Spring]----- IOC 之 注册 BeanDefinition中分析到,Spring 中有两种解析 Bean 的方式.如果根节点 ...
- MySQL性能优化总结___本文乃《MySQL性能调优与架构设计》读书笔记!
一.MySQL的主要适用场景 1.Web网站系统 2.日志记录系统 3.数据仓库系统 4.嵌入式系统 二.MySQL架构图: 三.MySQL存储引擎概述 1)MyISAM存储引擎 MyISAM存储引擎 ...
- Pytorch系列教程
介绍 不久前Pytorch发布了1.0版本,官网的doc页也更新了.这里说下官网的教程很实用,边学pytorch搭网络边学NLP-图像等领域的先进技术. 官网的教程都是英文的,本人就用这个系列博客做个 ...