慢时光~

请叫我:Tom-shushu

有兴趣的大佬可以移步右边我的个人博客浏览:Z-BLOG

输了不可怕,大不了从头再来,我们还年轻---周红

springMVC实现增删改查

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

 1 /*
 2 SQLyog 企业版 - MySQL GUI v8.14 
 3 MySQL - 5.1.73-community 
 4 *********************************************************************
 5 */
 6 /*!40101 SET NAMES utf8 */;
 7 
 8 create table `emp` (
 9     `empno` double ,
10     `ename` varchar (60),
11     `job` varchar (60),
12     `mgr` double ,
13     `hiredate` varchar (60),
14     `sal` float ,
15     `comm` float ,
16     `deptno` double 
17 ); 
18 insert into `emp` (`empno`, `ename`, `job`, `mgr`, `hiredate`, `sal`, `comm`, `deptno`) values('7369','SMITH','CLERK','7902','2018-10-28 10:22:37','800','0.565','10');
19 insert into `emp` (`empno`, `ename`, `job`, `mgr`, `hiredate`, `sal`, `comm`, `deptno`) values('7499','Allen','SALESMAN','7698','2018-10-28 10:22:37','1600','300','30');
20 insert into `emp` (`empno`, `ename`, `job`, `mgr`, `hiredate`, `sal`, `comm`, `deptno`) values('7521','Ward','SALESMAN','7698','2018-10-28 10:22:37','1250','500','30');
21 insert into `emp` (`empno`, `ename`, `job`, `mgr`, `hiredate`, `sal`, `comm`, `deptno`) values('7566','JONES','MANAGER','7839','2018-10-28 10:22:37','2975','0','20');
22 insert into `emp` (`empno`, `ename`, `job`, `mgr`, `hiredate`, `sal`, `comm`, `deptno`) values('7654','MARTIN','SALESMAN','7698','2018-10-28 10:22:37','1250','1400','30');
23 insert into `emp` (`empno`, `ename`, `job`, `mgr`, `hiredate`, `sal`, `comm`, `deptno`) values('7782','CLARK','MANAGER','7839','2018-10-28 10:22:37','2450',NULL,'10');
24 insert into `emp` (`empno`, `ename`, `job`, `mgr`, `hiredate`, `sal`, `comm`, `deptno`) values('7788','SCOTT','ANALYST','7566','2018-10-28 10:22:38','3000',NULL,'20');
25 insert into `emp` (`empno`, `ename`, `job`, `mgr`, `hiredate`, `sal`, `comm`, `deptno`) values('7839','KING','PRESIDENT',NULL,'2018-10-28 10:22:38','5000',NULL,'10');
26 insert into `emp` (`empno`, `ename`, `job`, `mgr`, `hiredate`, `sal`, `comm`, `deptno`) values('7844','TURNER','SALESMAN','7698','2018-10-28 10:22:38','1500','0','30');
27 insert into `emp` (`empno`, `ename`, `job`, `mgr`, `hiredate`, `sal`, `comm`, `deptno`) values('7876','ADAMS','CLERK','7788','2018-10-28 10:22:38','1100',NULL,'20');
28 insert into `emp` (`empno`, `ename`, `job`, `mgr`, `hiredate`, `sal`, `comm`, `deptno`) values('7902','FORD','ANALYST','7566','2018-10-28 10:22:38','3000',NULL,'20');

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

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

spring-jdbc,mysql
 1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 2   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
 3   <modelVersion>4.0.0</modelVersion>
 4   <groupId>web01</groupId>
 5   <artifactId>lianxicrud</artifactId>
 6   <packaging>war</packaging>
 7   <version>0.0.1-SNAPSHOT</version>
 8   <name>lianxicrud Maven Webapp</name>
 9   <url>http://maven.apache.org</url>
10   <dependencies>
11     <dependency>
12       <groupId>junit</groupId>
13       <artifactId>junit</artifactId>
14       <version>3.8.1</version>
15       <scope>test</scope>
16     </dependency>
17     <!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
18     <dependency>
19         <groupId>javax.servlet</groupId>
20         <artifactId>jstl</artifactId>
21         <version>1.2</version>
22     </dependency>
23     <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
24     <dependency>
25         <groupId>javax.servlet</groupId>
26         <artifactId>javax.servlet-api</artifactId>
27         <version>4.0.1</version>
28         <scope>provided</scope>
29     </dependency>
30     <!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
31     <dependency>
32         <groupId>org.springframework</groupId>
33         <artifactId>spring-web</artifactId>
34         <version>5.0.8.RELEASE</version>
35     </dependency>
36     <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
37     <dependency>
38         <groupId>org.springframework</groupId>
39         <artifactId>spring-webmvc</artifactId>
40         <version>5.0.8.RELEASE</version>
41     </dependency>
42     <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
43     <dependency>
44         <groupId>org.springframework</groupId>
45         <artifactId>spring-jdbc</artifactId>
46         <version>5.0.8.RELEASE</version>
47     </dependency>
48     <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
49     <dependency>
50         <groupId>mysql</groupId>
51         <artifactId>mysql-connector-java</artifactId>
52         <version>5.1.47</version>
53     </dependency>
54   </dependencies>
55   <build>
56     <finalName>lianxicrud</finalName>
57   </build>
58 </project>

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

1.springMVC-servlet.xml:主要配置数据源,视图解析器,以及注册拦截器......

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
 4     xmlns:mvc="http://www.springframework.org/schema/mvc"
 5     xsi:schemaLocation="http://www.springframework.org/schema/beans 
 6                         http://www.springframework.org/schema/beans/spring-beans.xsd 
 7                         http://www.springframework.org/schema/context 
 8                         http://www.springframework.org/schema/context/spring-context.xsd
 9                         http://www.springframework.org/schema/mvc 
10                         http://www.springframework.org/schema/mvc/spring-mvc.xsd">
11     <context:component-scan base-package="controller" />
12     <context:component-scan base-package="dao" />
13     <context:component-scan base-package="biz" />
14     <mvc:annotation-driven />
15     <!-- 配置数据源 -->
16     <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
17         <property name="url" value="jdbc:mysql://localhost:3306/test" />
18         <property name="driverClassName" value="com.mysql.jdbc.Driver" />
19         <property name="username" value="root" />
20         <property name="password" value="66668888ZH" />
21     </bean>
22     <!-- 类似于ps对象的一个内容 -->
23     <bean id="jdbcTemplate" 
24         class="org.springframework.jdbc.core.JdbcTemplate">
25         <property name="dataSource" ref="dataSource" />
26     </bean>
27     <!-- 视图解析器 -->
28     <bean id="irvr"
29         class="org.springframework.web.servlet.view.InternalResourceViewResolver">
30         <property name="suffix" value=".jsp" />
31         <property name="prefix" value="/user/" />
32     </bean>
33     <!-- 注册拦截器 -->
34     <mvc:interceptors>
35         <bean id="encode" class="interruptor.EncodeInterceptor"/>
36     </mvc:interceptors>
37     
38 </beans>

web.xml:

 1 <!DOCTYPE web-app PUBLIC
 2  "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 3  "http://java.sun.com/dtd/web-app_2_3.dtd" >
 4 
 5 <web-app>
 6   <display-name>Archetype Created Web Application</display-name>
 7   <servlet>
 8       <servlet-name>springMVC</servlet-name>
 9       <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
10   </servlet>
11   <servlet-mapping>
12       <servlet-name>springMVC</servlet-name>
13     <url-pattern>*.mvc</url-pattern>
14   </servlet-mapping>
15 </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包:

 1 package dao;
 2 
 3 import java.sql.ResultSet;
 4 import java.sql.SQLException;
 5 import java.util.List;
 6 
 7 import org.springframework.beans.factory.annotation.Autowired;
 8 import org.springframework.jdbc.core.JdbcTemplate;
 9 import org.springframework.jdbc.core.RowMapper;
10 import org.springframework.stereotype.Repository;
11 
12 import bean.EmpBean;
13 
14 @Repository
15 public class EmpDAO {
16 
17     @Autowired
18     private JdbcTemplate jt;
19     
20     public void add(EmpBean eb) {
21         String sql = "insert into emp values(null,?,?,?,?,?,?,?)";
22         jt.update(sql, eb.geteName(),eb.getJob(),eb.getMgr(),eb.getHireDate(),eb.getSal(),eb.getComm(),eb.getDeptNo());
23     } 
24     
25     public void delete(int empNo) {
26         String sql = "delete from emp where empno = ?";
27         jt.update(sql,empNo);
28     }
29     
30     public void update(EmpBean eb) {
31         String sql = "update emp set ename=?,job=?,mgr=?,hiredate=?,sal=?,comm=?,daptno=? where empno=?";
32         jt.update(sql,eb.geteName(),eb.getJob(),eb.getMgr(),eb.getHireDate(),eb.getSal(),eb.getComm(),eb.getDeptNo(),eb.getEmpNo());
33     }
34     
35     public List<EmpBean>findAll(){
36         String sql = "select * from emp";
37         return jt.query(sql, new RowMapperImpl());
38     }
39     
40     public EmpBean findById(int empNo) {
41         String sql = "select * from emp where empNo ='" + empNo +  "'";
42         return jt.query(sql, new RowMapperImpl()).get(0);
43     }
44 }
45 
46 class RowMapperImpl implements RowMapper<EmpBean>{
47     //对象关系映射(ORM),将查询出来的结果映射成类的属性
48     @Override
49     public EmpBean mapRow(ResultSet rs, int rowNum) throws SQLException {
50         EmpBean eb = new EmpBean();
51         eb.setEmpNo(rs.getInt(1));
52         eb.seteName(rs.getString(2));
53         eb.setJob(rs.getString(3));
54         eb.setMgr(rs.getInt(4));
55         eb.setHireDate(rs.getString(5));
56         eb.setSal(rs.getDouble(6));
57         eb.setComm(rs.getDouble(7));
58         eb.setDeptNo(rs.getInt(8));
59         return eb;
60     }
61 }

3.biz包:

 1 package biz;
 2 
 3 import java.util.List;
 4 
 5 import org.springframework.beans.factory.annotation.Autowired;
 6 import org.springframework.stereotype.Service;
 7 
 8 import bean.EmpBean;
 9 import dao.EmpDAO;
10 
11 @Service
12 public class EmpBiz {
13 
14     @Autowired
15     private EmpDAO edao;
16     public void add(EmpBean eb) {
17         edao.add(eb);
18     }
19     
20     public void delete(int empNo) {
21         edao.delete(empNo);
22     }
23     
24     public void update(EmpBean eb) {
25         edao.update(eb);
26     }
27     
28     public List<EmpBean>findAll(){
29         return edao.findAll();
30     }
31     
32     public EmpBean findById(int empNo) {
33         return edao.findById(empNo);
34     }
35 }
36     

4.controller包:

 1 package controller;
 2 
 3 import javax.servlet.http.HttpServletRequest;
 4 
 5 import org.springframework.beans.factory.annotation.Autowired;
 6 import org.springframework.stereotype.Controller;
 7 import org.springframework.web.bind.annotation.RequestMapping;
 8 
 9 import bean.EmpBean;
10 import biz.EmpBiz;
11 
12 @Controller
13 @RequestMapping("/emp")
14 public class EmpController {
15     @Autowired
16     private EmpBiz eb;
17     @RequestMapping("/add")
18     public String add(EmpBean emp) {
19         eb.add(emp);
20         return "redirect:../index.jsp";
21     }
22     
23     @RequestMapping("/find")
24     public String findAll(HttpServletRequest request) {
25         request.getSession().setAttribute("ALLEMP",eb.findAll());
26         return "redirect:../index.jsp";
27     }
28     
29     @RequestMapping("/delete")
30     public String delete(int empNo) {
31         eb.delete(empNo);
32         return "redirect:../index.jsp";
33     }
34     
35     @RequestMapping("/findbyid")
36     public String findById(int empNo , HttpServletRequest request) {
37         request.getSession().setAttribute("EMPBEAN", eb.findById(empNo));
38         System.out.println("11111");
39         return "redirect:../update.jsp";
40     }
41     
42     @RequestMapping("/update")
43     public String update(EmpBean emp) {
44         eb.update(emp);
45         System.out.println("22222222");
46         return "redirect:../index.jsp";
47     }
48 }

interrupt包:

 1 package interruptor;
 2 
 3 import javax.servlet.http.HttpServletRequest;
 4 import javax.servlet.http.HttpServletResponse;
 5 
 6 import org.springframework.web.servlet.HandlerInterceptor;
 7 import org.springframework.web.servlet.ModelAndView;
 8 
 9 //建立一个拦截器(类似于Filter)
10 public class EncodeInterceptor implements HandlerInterceptor{
11 
12     @Override
13     public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
14             throws Exception {
15     }
16     
17     @Override
18     public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
19             ModelAndView modelAndView) throws Exception {
20     }
21     @Override
22     public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
23             throws Exception {
24         //针对post请求的编码集操作
25         request.setCharacterEncoding("utf-8");
26         response.setCharacterEncoding("utf-8");
27         return true;
28     }
29     
30 }

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

1.index.jsp:

 1 <%@ page language="java" pageEncoding="utf-8" isELIgnored="false" %>
 2 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
 3 <html>
 4 <body>
 5     <c:if test="${empty ALLEMP}">
 6         <c:redirect url="emp/find.mvc"/>
 7     </c:if>
 8     
 9     <c:forEach var="ei" items="${ALLEMP}">
10         ${ei.empNo}  ${ei.eName}
11         <a href="emp/delete.mvc?empNo=${ei.empNo }">删除</a>
12         <a href="emp/findbyid.mvc?empNo=${ei.empNo }">修改</a>
13         <br/>
14     </c:forEach>
15 </body>
16 </html>

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

 1 <%@ page language="java" pageEncoding="utf-8" isELIgnored="false"%>
 2 <html>
 3 <head>
 4 <title>注册新员工</title>
 5 <style type="text/css">
 6     table {
 7             margin: 0 auto;
 8             border: 1px  gray solid;
 9             width: 70%;
10     }
11     td,th{
12             border: 1px gray solid;
13     }
14 </style>
15 </head>
16 <body>
17     <form action="emp/add.mvc" method="post">
18         <table>
19             <tr>
20                     <h2 align="center">公司员工注册表</h2>
21             </tr>        
22             <tr>
23                 <th>姓名</th>
24                 <td>
25                     <input type="text" name="eName"/>
26                 </td>
27             </tr>
28             <tr>
29                 <th>职位</th>
30                 <td>
31                     <input type="text" name="job"/>
32                 </td>
33             </tr>
34             <tr>
35                 <th>上司</th>
36                 <td>
37                     <input type="text" name="mgr"/>
38                 </td>
39             </tr>
40             <tr>
41                 <th>入职时间</th>
42                 <td>
43                     <input type="text" name="hireDate"/>
44                 </td>
45             </tr>
46             <tr>
47                 <th>薪资</th>
48                 <td>
49                     <input type="text" name="sal"/>
50                 </td>
51             </tr>
52             <tr>
53                 <th>奖金</th>
54                 <td>
55                     <input type="text" name="comm"/>
56                 </td>
57             </tr>
58             <tr>
59                 <th>部门</th>
60                 <td>
61                     <input type="text" name="deptNo"/>
62                 </td>
63             </tr>
64             <tr>
65                 <th colspan="1">
66                     <input type="submit" values = "注册新员工"/>
67                 </th>
68             </tr>
69         </table>
70     </form>
71 </body>
72 </html>

3.修改页面:update.jsp:

 1 <%@ page language="java"  pageEncoding="utf-8" isELIgnored="false"%>
 2 <html>
 3 <head>
 4 <title>修改员工信息</title>
 5 <style type="text/css">
 6 table {
 7     margin: 0 auto;
 8     border: 1px gray solid;
 9     width: 70%;
10 }
11 td,th{
12     border: 1px gray solid;
13 }
14 </style>
15 
16 </head>
17 <body>19     <form action="emp/update.mvc" method="post">
20         <input type="hidden" name="empNo" value="${EMPBEAN.empNo }"/>
21         <table>
22             <tr>
23                 <h2 align="center">修改员工信息</h2>
24             </tr>
25             <tr>
26                 <th>姓名</th>
27                 <td>
28                     <input type="text" name="eName" value="${EMPBEAN.eName }"/>
29                 </td>
30             </tr>
31             <tr>
32                 <th>职位</th>
33                 <td>
34                     <input type="text" name="job" value="${EMPBEAN.job }"/>
35                 </td>
36             </tr>
37             <tr>
38                 <th>上司</th>
39                 <td>
40                     <input type="text" name="mgr" value="${EMPBEAN.mgr }"/>
41                 </td>
42             </tr>
43             <tr>
44                 <th>入职时间</th>
45                 <td>
46                     <input type="text" name="hireDate" value="${EMPBEAN.hireDate }"/>
47                 </td>
48             </tr>
49             <tr>
50                 <th>薪金</th>
51                 <td>
52                     <input type="text" name="sal" value="${EMPBEAN.sal }"/>
53                 </td>
54             </tr>
55             <tr>
56                 <th>奖金</th>
57                 <td>
58                     <input type="text" name="comm" value="${EMPBEAN.comm }"/>
59                 </td>
60             </tr>
61             <tr>
62                 <th>部门</th>
63                 <td>
64                     <input type="text" name="daptNo" value="${EMPBEAN.deptNo }"/>
65                 </td>
66             </tr>
67             <tr>
68                 <th colspan="2">
69                     <input type="submit" value="提交修改信息"/>
70                 </th>
71             </tr>
72         </table>
73     </form>
74 
75 </body>
76 </html>

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

下面我们来进行测试:

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

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

点击提交:

小仙女添加进来了

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

修改完成。

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

 

删除成功。

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

 

输了不可怕,大不了从头再来,我们还年轻---周红

posted on 2018-12-23 19:33  Tom-shushu  阅读(3040)  评论(0编辑  收藏  举报

导航