整合SSM (用户的增删改查)

环境

  • IDEA
  • Mysql 8.0.15
  • Tomcat 9
  • Maven

目的

  • 为加深MySql数据库,Spring,javaWeb以及Mybatis知识,学习一些简单的前端知识

数据库环境

创建一个存放用户的数据库表

drop table if exists user1;
create table user1(
id int unsigned auto_increment key,
username varchar(20) not null unique comment '编号',
age tinyint unsigned not null default 18 comment '年龄',
sex varcahr(10) not null default '保密' comment '性别',
addr varchar(30) not null,
married tinyint(1) not null,
salary float(8,2) not null default 0 comment '薪水'
)engine=innodb charset=utf8;

insert user1 values(1,'张逢杰',23,'男','杭州',0,3000.00);
insert user1(username,age,sex,addr,married,salary) values('queen',22,'女','魔仙堡',0,2500.00);
insert user1 set username='imooc',age=21,sex='女',addr='上海',salary=40000);
insert user1 values(null,'张三',20,'男','上海',0,12999),
(null,'三',90,'男','上海',0,129),
(null,'张',89,'男','上海',0,1299),
(null,'李四',67,'男','上海',0,12999),
(null,'王五',56,'男','上海',0,1999),
(null,'赵六',45,'男','上海',0,2999),
(null,'祥子',34,'男','上海',0,12),
(null,'骆驼',23,'男','上海',0,199);

insert user1 values(null,'小小朱',22,'女','成都',0,3400),
(null,'朱零元',26,'女','杭州',0,9400),
(null,'aka小朱',22,'女','广州',0,8400),
(null,'朱财奴',20,'女','广州',0,7400),
(null,'阿朱',19,'女','魔仙堡',1,6400),
(null,'啊哲',18,'男','海盐',0,5300),
(null,'哲哥',31,'女','魔仙堡',1,6700),
(null,'怡妹妹',29,'女','魔仙堡',1,6800);

基本环境搭建

1.新建一个Maven项目,ssmbuild,添加web的支持
2.导入相关的pom依赖

<dependencies>
        <!--Junit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <!--数据库驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.17</version>
        </dependency>
        <!-- 数据库连接池 -->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.2</version>
        </dependency>

        <!--Servlet - JSP -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <!--Mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.2</version>
        </dependency>

        <!--Spring-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.8</version>
        </dependency>
    </dependencies>

3.由于maven的约定大于配置,还需要maven资源过滤设置

<build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>

4.建立基本结构和配置框架

  • com.zfj.pojo
  • com.zfj.dao
  • com.zfj.service
  • com.zfj.controller
  • mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

</configuration>
  • applicationContext.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

</beans>

MyBatis层的编写

1.数据库配置文件database.properties

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/ssmbuild?&userSSL=false&serverTimezone=UTC
username=root
password=root

2.关联数据库
3.编写MyBatis的核心配置文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <!--别名-->
    <typeAliases>
        <package name="com.zfj.pojo"/>
    </typeAliases>
    <!--映射文件-->
    <mappers>
        <mapper resource="com/zfj/dao/User1Mapper.xml"/>
    </mappers>

</configuration>

4.编写数据库对应的实体类 com.zfj.pojo.User1

public class User1 {
    private int id;
    private String username;
    private int age;
    private String sex;
    private String addr;
    private int married;
    private float salary;
    //无参,有参,getset,tostring。。。

5.编写Dao层的Mapper接口

public interface User1Mapper {

    //增加一个用户
    int addUser(User1 user1);
    //根据id删除一个用户
    int deleteUserById(int id);
    //更新用户
    int updateUser(User1 user1);
    //根据id查询,返回一个用户
    User1 queryUserById(int id);
    //查询出所有的用户,返回list集合
    List<User1> queryAllUser();
    //根据姓名查找用户
    User1 queryUserByName(String username);
}

6.编写接口对应的Mapper.xml文件。

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zfj.dao.User1Mapper">

    <!--add-->
    <insert id="addUser" parameterType="User1">
        insert into ssmbuild.user1(username, age, sex, addr, married, salary)
         VALUES (#{username},#{age},#{sex},#{addr},#{married},#{salary})
    </insert>
    <!--delete-->
    <delete id="deleteUserById" parameterType="int">
        delete  from ssmbuild.user1 where id=#{id}
    </delete>

    <update id="updateUser" parameterType="User1">
        update ssmbuild.user1
        set username=#{username},age=#{age},sex=#{sex},addr=#{addr},married=#{married},salary=#{salary}
        where id=#{id}
    </update>

    <select id="queryUserById" resultType="User1">
        select * from ssmbuild.user1 where id=#{id}
    </select>

    <select id="queryAllUser" resultType="User1">
        select * from ssmbuild.user1
    </select>

    <select id="queryUserByName" resultType="User1">
        select * from ssmbuild.user1 where username=#{username}
    </select>
</mapper>

7.编写Service层的接口和实现类

  • 接口
public interface User1Service {
    //增加一个用户
    int addUser(User1 user1);
    //根据id删除一个用户
    int deleteUserById(int id);
    //更新用户
    int updateUser(User1 user1);
    //根据id查询,返回一个用户
    User1 queryUserById(int id);
    //查询出所有的用户,返回list集合
    List<User1> queryAllUser();

    User1 queryUserByName(String username);
}
  • 实现类
public class User1ServiceImpl implements User1Service {

    private User1Mapper user1Mapper;

    public void setUser1Mapper(User1Mapper user1Mapper) {
        this.user1Mapper = user1Mapper;
    }

    public int addUser(User1 user1) {
        return user1Mapper.addUser(user1);
    }

    public int deleteUserById(int id) {
        return user1Mapper.deleteUserById(id);
    }


    public int updateUser(User1 user1) {
        return user1Mapper.updateUser(user1);
    }

    public User1 queryUserById(int id) {
        return user1Mapper.queryUserById(id);
    }

    public List<User1> queryAllUser() {
        return user1Mapper.queryAllUser();
    }

    public User1 queryUserByName(String username) {
        return user1Mapper.queryUserByName(username);
    }
}

就此,底层需求操作编写完毕

spring层

1.配置Spring整合MyBatis,可供选择的又c3p0,druid连接池;
2.编写spring整合MyBatis的相关配置文件;spring-dao.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    <!--1.关联数据库文件-->
    <context:property-placeholder location="classpath:database.properties"/>

    <!--2.数据库连接池-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${driver}"/>
        <property name="jdbcUrl" value="${url}"/>
        <property name="user" value="${username}"/>
        <property name="password" value="${password}"/>
    </bean>
    <!--3.配置sqlSessionFactory对象-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    </bean>

    <!--4.配置扫描dao包的接口-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.zfj.dao"/>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    </bean>

</beans>

3.Spring整合service层

<?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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    <!--扫描service相关的bean-->
    <context:component-scan base-package="com.zfj.service"/>

    <bean id="User1ServiceImpl" class="com.zfj.service.User1ServiceImpl">
        <property name="user1Mapper" ref="user1Mapper"/>
    </bean>

    <!--配置事务管理器-->
    <bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager" id="transactionManager">
    <!--注入数据库连接池-->
        <property name="dataSource" ref="dataSource"/>
    </bean>

</beans>

SpringMVC层

1.web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <servlet>
        <servlet-name>DispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:applicationContext.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>DispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!--encodingFilter-->
    <filter>
        <filter-name>encodingFilter</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>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!--Session过期时间-->
    <session-config>
        <session-timeout>15</session-timeout>
    </session-config>

</web-app>

2.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:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    <!--注解驱动-->
    <mvc:annotation-driven/>

    <!--静态资源默认servlet配置-->
    <mvc:default-servlet-handler/>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    <!--扫描相关的bean-->
    <context:component-scan base-package="com.zfj.controller"/>

</beans>

3.Spring配置文件整合,applicationContext.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">


    <import resource="spring-mvc.xml"/>
    <import resource="spring-service.xml"/>
    <import resource="spring-dao.xml"/>
</beans>

配置文件暂时结束,下面进行Controller和视图层编写

1.UserController类编写,

package com.zfj.controller;

import com.zfj.pojo.User1;
import com.zfj.service.User1Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author zfj
 * @create 2019/12/4 23:16
 */
//@Controller
@Controller
@RequestMapping("/user")
public class User1Controller {

    @Autowired
    private User1Service user1Service;

    //查询所有的用户
    @RequestMapping("/allUser")
    public String allUser(Model model){
        List<User1> user1s = user1Service.queryAllUser();
        model.addAttribute("list",user1s);
        return "allUser";
    }
    //点击【添加】时,跳转到添加页面
    @RequestMapping("/toAddUser")
    public String toAddUser(){
        return "addUser";
    }
    
    //添加用户
    @RequestMapping("/addUser")
    public String addUser(User1 user1){
        user1Service.addUser(user1);
        return "redirect:/user/allUser";
    }

    //点击【修改】时,跳转到修改页面
    @RequestMapping("/toUpdateUser")
    public String toUpdateUser(Model model,int id){
        User1 user1 = user1Service.queryUserById(id);
        model.addAttribute("user1",user1);
        return "updateUser";
    }
    //修改用户
    @RequestMapping("/updateUser")
    public String updateUser(User1 user1){
        user1Service.updateUser(user1);
        return "redirect:/user/allUser";
    }
    //删除
    @RequestMapping("/deleteUser/{id}")
    public String deleteUser(@PathVariable("id") int id){
        user1Service.deleteUserById(id);
        return "redirect:/user/allUser";
    }

    //根据姓名查询用户
    @RequestMapping("/queryUserByName")
    public String queryUserByName(String username,Model model){

        User1 user1 = user1Service.queryUserByName(username);
        List<User1> list=new ArrayList<User1>();
        list.add(user1);
        if(user1==null){
            list = user1Service.queryAllUser();
            model.addAttribute("error","未查到");
        }

        model.addAttribute("list",list);
        return "allUser";

    }

}

2.编写首页index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>

    <style>
      a{
        text-decoration:none;
        color: black;
        font-size: 20px;
      }
      h3{
        width: 180px;
        height: 38px;
        margin: 100px auto;
        text-align:center;
        line-height: 38px;
        background:deepskyblue;
        border-radiusz:4px;
      }

    </style>

  </head>
  <body>
  <h3>
  <a href="${pageContext.request.contextPath}/user/allUser">测试</a>
  </h3>
  </body>
</html>

在这里插入图片描述
3.用户列表页面 allUser.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>用户列表</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- 引入 Bootstrap -->
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>

<div class="container">
    <div class="row clearfix">
        <div class="col-md-12 column">
            <div class="page-header">
                <small>用户列表--显示所有用户</small>
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-md-4 column">
            <a class="btn btn-primary" href="${pageContext.request.contextPath}/user/toAddUser">新增用户</a>
            <a class="btn btn-primary" href="${pageContext.request.contextPath}/user/allUser">显示所有用户</a>
        </div>
        <div class="col-md-4 column"></div>
        <div class="col-md-4 column">
            <form class="form-inline" action="${pageContext.request.contextPath}/user/queryUserByName" method="post">
                <span style="color: red">${error}</span>
                <input type="text" name="username" placeholder="请输入要查询的用户名称" class="form-control">
                <input type="submit" class="btn btn-primary" value="查询">
            </form>
        </div>
    </div>
    <div class="row clearfix">
        <div class="col-md-12 column">
            <table class="table table-hover table-striped">
                <thead>
                    <tr>
                        <th>编号</th>
                        <th>姓名</th>
                        <th>年龄</th>
                        <th>性别</th>
                        <th>地址</th>
                        <th>婚否</th>
                        <th>薪资</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <c:forEach var="user" items="${list}">
                        <tr>
                            <td>${user.id}</td>
                            <td>${user.username}</td>
                            <td>${user.age}</td>
                            <td>${user.sex}</td>
                            <td>${user.addr}</td>
                            <td>${user.married}</td>
                            <td>${user.salary}</td>
                            <td>
                                <a href="${pageContext.request.contextPath}/user/toUpdateUser?id=${user.id}">修改</a>  &nbsp;&nbsp;|&nbsp;&nbsp;
                                <a href="${pageContext.request.contextPath}/user/deleteUser/${user.id}">删除</a>
                            </td>
                        </tr>
                    </c:forEach>
                </tbody>
            </table>
        </div>
    </div>

</div>


</body>
</html>

在这里插入图片描述
4.添加用户界面
在这里插入图片描述
5.修改用户界面
在这里插入图片描述
6.删除

7.查询用户
在这里插入图片描述
查不到的会提示,并返回所有信息
在这里插入图片描述

--------------------------------------------------------------------------------------
这是本菜鸟的第二个SSM整合的案例,感谢秦疆老师的帮助

评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值