【Spring】SSM整合

环境要求:

  • IDEA
  • MySQL 8.0 CE
  • Tomcat 9.0.41
  • Maven 3.6.3

完整的项目地址为:https://codechina.csdn.net/dreaming_coder/ssm

1. 创建数据库

/*
Navicat MySQL Data Transfer

Source Server         : ice
Source Server Version : 80021
Source Host           : localhost:3306
Source Database       : ssm

Target Server Type    : MYSQL
Target Server Version : 80021
File Encoding         : 65001

Date: 2021-01-14 21:34:07
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for books
-- ----------------------------
DROP TABLE IF EXISTS `books`;
CREATE TABLE `books` (
  `book_id` int NOT NULL AUTO_INCREMENT COMMENT '书本编号',
  `book_name` varchar(100) NOT NULL COMMENT '书名',
  `book_counts` int NOT NULL COMMENT '数量',
  `detail` varchar(200) DEFAULT NULL COMMENT '描述',
  PRIMARY KEY (`book_id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of books
-- ----------------------------
INSERT INTO `books` VALUES ('1', 'Java', '1', '从入门到放弃');
INSERT INTO `books` VALUES ('2', 'MySQL', '10', '从删库到跑路');
INSERT INTO `books` VALUES ('3', 'Linux', '5', '从进门到进牢');

2. 新建 Maven 项目

  1. 添加 web 支持

  2. 导入相关依赖

    <dependencies>
        
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.13version>
        dependency>
        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>8.0.22version>
        dependency>
        
        <dependency>
            <groupId>com.mchangegroupId>
            <artifactId>c3p0artifactId>
            <version>0.9.5.5version>
        dependency>
        
        <dependency>
            <groupId>javax.servletgroupId>
            <artifactId>servlet-apiartifactId>
            <version>2.5version>
        dependency>
        <dependency>
            <groupId>javax.servlet.jspgroupId>
            <artifactId>jsp-apiartifactId>
            <version>2.2version>
        dependency>
        <dependency>
            <groupId>javax.servletgroupId>
            <artifactId>jstlartifactId>
            <version>1.2version>
        dependency>
        
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId>
            <version>3.5.6version>
        dependency>
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatis-springartifactId>
            <version>2.0.6version>
        dependency>
        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webmvcartifactId>
            <version>5.3.2version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-jdbcartifactId>
            <version>5.3.2version>
        dependency>
        
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <version>RELEASEversion>
            <scope>compilescope>
        dependency>
    dependencies>
    
  3. Maven 设置静态资源过滤

    <build>
       <resources>
           <resource>
               <directory>src/main/javadirectory>
               <includes>
                   <include>**/*.propertiesinclude>
                   <include>**/*.xmlinclude>
               includes>
               <filtering>falsefiltering>
           resource>
           <resource>
               <directory>src/main/resourcesdirectory>
               <includes>
                   <include>**/*.propertiesinclude>
                   <include>**/*.xmlinclude>
               includes>
               <filtering>falsefiltering>
           resource>
       resources>
    build>
    
  4. 建立基本结构和配置框架

    • com.ice.pojo

    • com.ice.mapper

    • com.ice.service

    • com.ice.controller

    • mybatis-config.xml

      
      
      <configuration>
      
      configuration>
      
    • applicationContext.xml

      
      <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"
             xmlns:aop="http://www.springframework.org/schema/aop"
             xmlns:tx="http://www.springframework.org/schema/tx"
             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/aop http://www.springframework.org/schema/aop/spring-aop.xsd
                                  http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
                                  http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
      
      beans>
      

3. Mybatis 层编写

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

    jdbc.driver=com.mysql.cj.jdbc.Driver
    jdbc.url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=Asia/Shanghai&useSSL=true&useUnicode=true&characterEncoding=UTF-8
    jdbc.username=root
    jdbc.password=root
    
  2. IDEA 关联数据库

    【Spring】SSM整合_第1张图片

  3. 编写MyBatis的核心配置文件

    
    
    <configuration>
        
        <typeAliases>
            <package name="com.ice.pojo"/>
        typeAliases>
    
    configuration>
    
  4. 编写实体类

    package com.ice.pojo;
    
    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class Books {
           
        private int id;
        private String name;
        private int counts;
        private String detail;
    }
    
  5. 编写 Dao 层的 Mapper 接口

    package com.ice.mapper;
    
    import com.ice.pojo.Books;
    import org.apache.ibatis.annotations.Param;
    
    import java.util.List;
    
    public interface BookMapper {
           
    
        // 增加一本书
        int addBook(@Param("book") Books book);
    
        // 删除一本书
        int deleteBookById(@Param("id") int id);
    
        // 更新一本书
        int updateBook(@Param("book") Books book);
    
        // 根据 id 查询一本书
        Books queryBookById(@Param("id") int id);
    
        // 查询全部的书
        List<Books> queryAllBooks();
    
    }
    
  6. 编写接口对应的 Mapper.xml 文件

    
    
    
    <mapper namespace="com.ice.mapper.BookMapper">
    
        <insert id="addBook" parameterType="Books">
            insert into ssm.books (book_name, book_counts, detail)
            values (#{name}, #{counts}, #{detail});
        insert>
    
        <delete id="deleteBookById" parameterType="int">
            delete
            from ssm.books
            where book_id = #{id};
        delete>
    
        <update id="updateBook" parameterType="Books">
            update ssm.books
            set book_name   = #{name},
                book_counts = #{counts},
                detail      = #{detail}
            where book_id = #{id};
        update>
    
        <select id="queryBookById" parameterType="int" resultMap="bookMap">
            select *
            from ssm.books
            where book_id = #{id};
        select>
    
        <select id="queryAllBooks" resultMap="bookMap">
            select *
            from ssm.books;
        select>
    
        <resultMap id="bookMap" type="Books">
            <id property="id" column="book_id"/>
            <result property="name" column="book_name"/>
            <result property="counts" column="book_counts"/>
            <result property="details" column="details"/>
        resultMap>
    
    mapper>
    
  7. 编写Service层的接口和实现类

    【接口】

    package com.ice.service;
    
    import com.ice.pojo.Books;
    
    import java.util.List;
    
    public interface BookService {
           
    
        // 增加一本书
        int addBook(Books book);
    
        // 删除一本书
        int deleteBookById(int id);
    
        // 更新一本书
        int updateBook(Books book);
    
        // 根据 id 查询一本书
        Books queryBookById(int id);
    
        // 查询全部的书
        List<Books> queryAllBooks();
    
    }
    

    【实现类】

    package com.ice.service;
    
    import com.ice.mapper.BookMapper;
    import com.ice.pojo.Books;
    
    import java.util.List;
    
    public class BookServiceImpl implements BookService {
           
    
        private BookMapper bookMapper;
    
        public void setBookMapper(BookMapper bookMapper) {
           
            this.bookMapper = bookMapper;
        }
    
        @Override
        public int addBook(Books book) {
           
            return bookMapper.addBook(book);
        }
    
        @Override
        public int deleteBookById(int id) {
           
            return bookMapper.deleteBookById(id);
        }
    
        @Override
        public int updateBook(Books book) {
           
            return bookMapper.updateBook(book);
        }
    
        @Override
        public Books queryBookById(int id) {
           
            return bookMapper.queryBookById(id);
        }
    
        @Override
        public List<Books> queryAllBooks() {
           
            return bookMapper.queryAllBooks();
        }
    }
    

4. Spring 层

  1. 配置Spring整合MyBatis,我们这里数据源使用 c3p0 连接池,编写 Spring 整合 Mybatis 的相关的配置文件 spring-dao.xml

    
    <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 http://www.springframework.org/schema/context/spring-context.xsd">
        
        <context:property-placeholder location="classpath:database.properties"/>
    
        
        
        <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
            <property name="driverClass" value="${jdbc.driver}"/>
            <property name="jdbcUrl" value="${jdbc.url}"/>
            <property name="user" value="${jdbc.username}"/>
            <property name="password" value="${jdbc.password}"/>
    
            
            <property name="maxPoolSize" value="30"/>
            <property name="minPoolSize" value="10"/>
            
            <property name="autoCommitOnClose" value="false"/>
            
            <property name="checkoutTimeout" value="10000"/>
            
            <property name="acquireRetryAttempts" value="2"/>
        bean>
    
        
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource"/>
            
            <property name="configLocation" value="classpath:mybatis-config.xml"/>
        bean>
    
        
        
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            
            <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
            
            <property name="basePackage" value="com.ice.mapper"/>
        bean>
    
    beans>
    
  2. Spring 整合 service 层

    
    <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 http://www.springframework.org/schema/context/spring-context.xsd">
    
        
        <context:component-scan base-package="com.ice.service"/>
    
        
        <bean id="bookServiceImpl" class="com.ice.service.BookServiceImpl">
            <property name="bookMapper" ref="bookMapper"/>
        bean>
    
        
        <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            
            <property name="dataSource" ref="dataSource"/>
        bean>
    
    beans>
    

5. Spring MVC 层

  1. 配置 web.xml

    
    <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>SpringMVCservlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
            
            <init-param>
                <param-name>contextConfigLocationparam-name>
                <param-value>classpath:applicationContext.xmlparam-value>
            init-param>
            
            <load-on-startup>1load-on-startup>
        servlet>
        
        <servlet-mapping>
            <servlet-name>SpringMVCservlet-name>
            <url-pattern>/url-pattern>
        servlet-mapping>
    
        
        <filter>
            <filter-name>encodingfilter-name>
            <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
            <init-param>
                <param-name>encodingparam-name>
                <param-value>utf-8param-value>
            init-param>
        filter>
        <filter-mapping>
            <filter-name>encodingfilter-name>
            <url-pattern>/*url-pattern>
        filter-mapping>
        
        
        <session-config>
            <session-timeout>15session-timeout>
        session-config>
    web-app>
    
  2. 配置 spring-mvc.xml

    
    <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">
    
        
        <mvc:annotation-driven />
    
        
        <mvc:default-servlet-handler/>
        
        
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
            
            <property name="prefix" value="/WEB-INF/jsp/"/>
            
            <property name="suffix" value=".jsp"/>
        bean>
    
        
        <context:component-scan base-package="com.ice.controller"/>
    
    beans>
    
  3. Spring 配置整合文件,applicationContext.xml

    
    <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="classpath:spring-dao.xml"/>
        <import resource="classpath:spring-service.xml"/>
        <import resource="classpath:spring-mvc.xml"/>
    
    beans>
    

6. Controller 和视图层

  1. BookController 类编写

    package com.ice.controller;
    
    import com.ice.pojo.Books;
    import com.ice.service.BookService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Qualifier;
    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 java.util.List;
    
    @Controller
    @RequestMapping("/book")
    public class BookController {
           
    
        @Autowired
        @Qualifier("bookServiceImpl")
        private BookService bookService;
    
        // 查询全部书籍,并返回一个书籍展示页面
        @RequestMapping("/list")
        public String list(Model model) {
           
            List<Books> list = bookService.queryAllBooks();
            model.addAttribute("list", list);
            return "list";
        }
    
        @RequestMapping("/toAddBook")
        public String toAddBook() {
           
            return "addBook";
        }
    
        @RequestMapping("/add")
        public String add(Books book) {
           
            bookService.addBook(book);
            return "redirect:/book/list";
        }
    
        @RequestMapping("/toUpdateBook")
        public String toUpdateBook(Model model, int id) {
           
            Books book = bookService.queryBookById(id);
            model.addAttribute("book", book);
            return "updateBook";
        }
    
        @RequestMapping("/update")
        public String update(Model model, Books book) {
           
            bookService.updateBook(book);
            return "redirect:/book/list";
        }
    
        @RequestMapping("/delete/{bookId}")
        public String delete(@PathVariable("bookId") int id) {
           
            bookService.deleteBookById(id);
            return "redirect:/book/list";
        }
    
    }
    
  2. 编写首页 index.jsp

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>首页title>
        <style type="text/css">
            a {
            
                text-decoration: none;
                color: black;
                font-size: 18px;
            }
            h3 {
            
                width: 180px;
                height: 38px;
                margin: 100px auto;
                text-align: center;
                line-height: 38px;
                background: deepskyblue;
                border-radius: 4px;
            }
        style>
    head>
    <body>
    <h3><a href="${pageContext.request.contextPath}/book/list">进入书籍页面a>h3>
    body>
    html>
    
  3. 书籍列表页面 list.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">
        
        <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">
                    <h1>
                        <small>书籍列表 —— 显示所有书籍small>
                    h1>
                div>
            div>
        div>
    
        <div class="row">
            <div class="col-md-4 column">
                <a class="btn btn-primary" href="${pageContext.request.contextPath}/book/toAddBook">新增a>
            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>
                    tr>
                    thead>
    
                    <tbody>
                    <c:forEach var="book" items="${requestScope.get('list')}">
                        <tr>
                            <td>${book.getId()}td>
                            <td>${book.getName()}td>
                            <td>${book.getCounts()}td>
                            <td>${book.getDetail()}td>
                            <td>
                                <a href="${pageContext.request.contextPath}/book/toUpdateBook?id=${book.getId()}">更改a> |
                                <a href="${pageContext.request.contextPath}/book/delete/${book.getId()}">删除a>
                            td>
                        tr>
                    c:forEach>
                    tbody>
                table>
            div>
        div>
    div>
    body>
    html>
    
  4. 添加书籍页面:addBook.jsp

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>新增书籍title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        
        <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">
                    <h1>
                        <small>新增书籍small>
                    h1>
                div>
            div>
        div>
        <form action="${pageContext.request.contextPath}/book/add" method="post">
            书籍名称:<input type="text" name="name"><br><br><br>
            书籍数量:<input type="text" name="counts"><br><br><br>
            书籍详情:<input type="text" name="detail"><br><br><br>
            <input type="submit" value="添加">
        form>
    
    div>
    body>
    html>
    
  5. 修改书籍页面 updateBook.jsp

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>修改书籍title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        
        <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">
                    <h1>
                        <small>新增信息small>
                    h1>
                div>
            div>
        div>
        <form action="${pageContext.request.contextPath}/book/update" method="post">
            <input type="hidden" name="id" value="${book.getId()}"/>
            书籍名称:<input type="text" name="name" value="${book.getName()}"/>
            书籍数量:<input type="text" name="counts" value="${book.getCounts()}"/>
            书籍详情:<input type="text" name="detail" value="${book.getDetail() }"/>
            <input type="submit" value="提交"/>
        form>
    
    div>
    body>
    html>
    

7. 配置 Tomcat 运行

【Spring】SSM整合_第2张图片

8. 项目结构图

【Spring】SSM整合_第3张图片

你可能感兴趣的:(Javaweb,spring,mybatis,java,mysql)