整合SSM(Spring+SpringMVC+Mybatis)

10 篇文章 0 订阅
9 篇文章 0 订阅

环境要求

环境

  • IDEA-2020.2
  • mysql-5.7.35
  • tomcat-9.0.52
  • maven 3.8.2

数据库环境

创建一个存放书籍的数据库表

CREATE DATABASE `ssmbuild`;

USE `ssmbuild`;

DROP TABLE IF EXISTS `books`;

CREATE TABLE `books`(
    `bookId` INT(10) NOT NULL AUTO_INCREMENT COMMENT '书Id',
    `bookName` VARCHAR(100) NOT NULL COMMENT '书名',
    `bookCount` INT(11) NOT NULL COMMENT '数量',
    `detail` VARCHAR(200) NOT NULL COMMENT '描述',
    PRIMARY KEY(`bookId`)
)ENGINE=INNODB DEFAULT CHARSET = utf8;

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

基本环境搭建

1. 新建一个空的Maven项目,添加web依赖
2.导包

<!--导入:junit,数据库驱动,连接池(c3p0),servlet,jsp,jstl,mybatis,mybatis-spring,springmvc,spring-jdbc,lombok-->
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.2</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.3.3</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.7</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.6</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.12</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.12</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.22</version>
        </dependency>
    </dependencies>

3. 解决maven静态资源过虑问题

    <!--Maven静态资源无法导出问题-->
    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>

4.建立基本的项目结构

-com.feng.controller
-com.feng.mapper
-com.feng.pojo
-com.feng.service
-mybatis-config.xml
-applicationContext.xml

Mybatis层编写

1.编写数据库配置文件db.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssmbuild? useUnicode=true&characterEncoding=utf8&useSSL=false
jdbc.username=root
jdbc.password=123456

注意jdbc.username处不能直接写username,写username则会报错:报错:java.sql.SQLException: Access denied for user ‘?°?é??’@‘localhost’ (using password: YES)

2.IDEA关联数据库配置
3.编写Mybatis核心配置文件,即mybatis-config.xml

<?xml version="1.0" encoding="GBK" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <typeAliases>
        <package name="com.feng.pojo"/>
    </typeAliases>

    <mappers>
        <mapper class="com.feng.mapper.BookMapper"/>
    </mappers>

</configuration>

4.编写数据库对应的实体类(使用lombok插件)

package com.feng.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Book {
    private int bookId;
    private String bookName;
    private int bookCount;
    private String detail;
}

5.mapper层编写对应的接口:BookMapper

package com.feng.mapper;

import com.feng.pojo.Book;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface BookMapper {
    //增加一本书
    int addBook(Book book);

    //删除一本书
    int deleteBookById(@Param("bookId") int id);

    //修改一本书
    int updateBook(Book book);

    //查找一本书
    Book queryBookById(@Param("bookId") int id);

    //查找所有书
    List<Book> queryAllBook();

    //根据名字查询书籍
    List<Book> queryBookByName(@Param("bookName") String queryName);
}

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

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

    <insert id="addBook" parameterType="book">
        insert into books (bookName,bookCount,detail) values (#{bookName},#{bookCount},#{detail});
    </insert>

    <delete id="deleteBookById">
        delete from books where bookId = #{bookId}
    </delete>

    <update id="updateBook" parameterType="book">
        update books set  bookName = #{bookName},bookCount = #{bookCount},detail = #{detail}  where bookId = #{bookId};
    </update>

    <select id="queryBookById" resultType="book">
        select * from books where bookId = #{bookId}
    </select>

    <select id="queryAllBook" resultType="book">
        select * from books
    </select>

    <select id="queryBookByName" resultType="book">
        select * from books where bookName like "%"#{bookName}"%"
    </select>

</mapper>

**7.编写service层的接口:BookService **

package com.feng.service;

import com.feng.pojo.Book;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface BookService {
    //增加一本书
    int addBook(Book book);

    //删除一本书
    int deleteBookById(int id);

    //修改一本书
    int updateBook(Book book);

    //查找一本书
    Book queryBookById(int id);

    //查找所有书
    List<Book> queryAllBook();

    //根据名字查询书籍
    List<Book> queryBookByName(String queryName);
}

**8.编写service接口对应的实现:BookServiceImpl **

package com.feng.service;

import com.feng.mapper.BookMapper;
import com.feng.pojo.Book;

import java.util.List;

public class BookServiceImpl implements BookService{

    private BookMapper bookMapper;

    public void setBookMapper(BookMapper bookMapper) {
        this.bookMapper = bookMapper;
    }

    public int addBook(Book book) {
        return bookMapper.addBook(book);
    }

    public int deleteBookById(int id) {
        return bookMapper.deleteBookById(id);
    }

    public int updateBook(Book book) {
        return bookMapper.updateBook(book);
    }

    public Book queryBookById(int id) {
        return bookMapper.queryBookById(id);
    }

    public List<Book> queryAllBook() {
        return bookMapper.queryAllBook();
    }

    public List<Book> queryBookByName(String queryName) {
        return bookMapper.queryBookByName(queryName);
    }


}

Spring层编写

1.Spring整合Mybatis,编写spring-dao.xml

<?xml version="1.0" encoding="GBK"?>
<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:dp.properties"/>

    <!--2.配置数据源-->
    <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}"/>
        <!-- c3p0连接池的私有属性 -->
        <property name="maxPoolSize" value="30"/>
        <property name="minPoolSize" value="10"/>
        <!-- 关闭连接后不自动commit -->
        <property name="autoCommitOnClose" value="false"/>
        <!-- 获取连接超时时间 -->
        <property name="checkoutTimeout" value="10000"/>
        <!-- 当获取连接失败重试次数 -->
        <property name="acquireRetryAttempts" value="2"/>
    </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接口包,动态实现Dao接口注入到spring容器中 -->
    <!--解释 : https://www.cnblogs.com/jpfss/p/7799806.html-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 注入sqlSessionFactory -->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <!-- 给出需要扫描Dao接口包 -->
        <property name="basePackage" value="com.feng.mapper"/>
    </bean>

</beans>

2.spring整合service,编写spring-service.xml

<?xml version="1.0" encoding="GBK"?>
<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">

    <context:component-scan base-package="com.feng.service"/>

    <!--注册BookServiceImpl-->
    <bean id="BookServiceImpl" class="com.feng.service.BookServiceImpl">
        <property name="bookMapper" ref="bookMapper"/>
    </bean>

    <!--配置事务管理-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <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>SpringMVC</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>SpringMVC</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!--过滤器-->
    <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-config>
        <session-timeout>15</session-timeout>
    </session-config>
</web-app>

2.spring-mvc.xml

<?xml version="1.0" encoding="GBK"?>
<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
       https://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       https://www.springframework.org/schema/mvc/spring-mvc.xsd">


    <context:component-scan base-package="com.feng.controller"/>
    <!--开启SpringMVC注解驱动-->
    <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>
</beans>

3.整合三个文件(spring-dao,spring-service,spring-mvc),将其导入appcationContext.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="classpath:spring-dao.xml"/>
    <import resource="classpath:spring-service.xml"/>
    <import resource="classpath:spring-mvc.xml"/>
</beans>

Controller

编写controller

package com.feng.controller;

import com.feng.pojo.Book;
import com.feng.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("/allBook")
    public String AllBook(Model model){
        List<Book> books = bookService.queryAllBook();
        model.addAttribute("list",books);
        return "allBook";
    }

    //跳转增添书籍页面
    @RequestMapping("/toAddBook")
    public String toAddBook(){
        return "addBook";
    }

    //增添书籍
    @RequestMapping("/addBook")
    public String addBook(Book book){
        bookService.addBook(book);
        System.out.println(book);
        return "redirect:/book/allBook";
    }

    //跳转修改页面
    @RequestMapping("/toUpdateBook/{id}")
    public String toUpdateBook(@PathVariable int id,Model model){
        Book book = bookService.queryBookById(id);
        model.addAttribute("UBook",book);
        return "updateBook";
    }

    //修改书籍
    @RequestMapping("/updateBook")
    public String updateBook(Book book){
        bookService.updateBook(book);
        return "redirect:/book/allBook";
    }

    //删除图书
    @RequestMapping("/delete/{id}")
    public String deleteBook(@PathVariable int id){
        bookService.deleteBookById(id);
        return "redirect:/book/allBook";
    }

    //根据名字查询书籍
    @RequestMapping("/queryName")
    public String queryName(String queryName,Model model){
        List<Book> books = bookService.queryBookByName(queryName);
        System.out.println(books);
        model.addAttribute("list",books);
        return "allBook";
    }
}

视图

1.编写首页,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: 340px auto;
        text-align: center;
        line-height: 38px;
        background-color: deepskyblue;
        border-radius: 5px;
      }

    </style>
  </head>
  <body>

  <h3>
    <a href="${pageContext.request.contextPath}/book/allBook">点击进入书籍管理系统</a>
  </h3>
  </body>
</html>

2.在web/WEB-INF下新建jsp目录下,新建allBook.jsp,addBook.jsp,updateBook.jsp
3.allBook.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>
    <!-- 引入 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">
            <h1>
                <small>书籍列表------显示所有书籍</small>
            </h1>
        </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 class="col-md-4 column"></div>

        <div class="col-md-4 column">
            <form class="form-inline" action="${pageContext.request.contextPath}/book/queryName" method="post">
                <input type="text" class="form-control" name="queryName" placeholder="请输入需要书籍名称">
                <input class="btn btn-primary" type="submit">
            </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>
                </tr>
                </thead>

                <tbody>
                <c:forEach var="book" items="${requestScope.get('list')}">
                    <tr>
                        <td>${book.getBookId()}</td>
                        <td>${book.getBookName()}</td>
                        <td>${book.getBookCount()}</td>
                        <td>${book.getDetail()}</td>
                        <td>
                            <a class="btn btn-primary" href="${pageContext.request.contextPath}/book/toUpdateBook/${book.getBookId()}">修改</a>
                            <a class="btn btn-primary" href="${pageContext.request.contextPath}/book/delete/${book.getBookId()}">删除</a>
                        </td>
                    </tr>
                </c:forEach>
                </tbody>
            </table>
        </div>
    </div>
</div>
</body>
</html>

4.addBook.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>
    <!-- 引入 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">
            <h1>
                <small>新增书籍列表------添加书籍</small>
            </h1>
        </div>
    </div>

    <form action="${pageContext.request.contextPath}/book/addBook" method="post">
        书籍名称:<input type="text" name="bookName"><br><br><br>
        书籍数量:<input type="text" name="bookCount"><br><br><br>
        书籍描述:<input type="text" name="detail"><br><br><br>
        <input type="submit" value="添加">
    </form>
</div>
</body>
</html>

5.updateBook.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>
    <!-- 引入 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">
            <h1>
                <small>新增书籍列表------添加书籍</small>
            </h1>
        </div>
    </div>

    <form action="${pageContext.request.contextPath}/book/updateBook" method="post">
        <input type="hidden" name="bookId" value="${UBook.bookId}">
        书籍名称:<input type="text" name="bookName" value="${UBook.bookName}"><br><br><br>
        书籍数量:<input type="text" name="bookCount" value="${UBook.bookCount}"><br><br><br>
        书籍描述:<input type="text" name="detail" value="${UBook.detail}"><br><br><br>
        <input type="submit" value="添加">
    </form>
</div>
</body>
</html>

效果如下:

首页
在这里插入图片描述

书籍列表
在这里插入图片描述

增添书籍
在这里插入图片描述

修改书籍
在这里插入图片描述

查询书籍
在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值