SSM整合-简单的书籍管理系统

1、环境搭建

1.1 数据库环境

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

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 '书名',
`bookCounts` INT(11) NOT NULL COMMENT '数量',
`detail` VARCHAR(200) NOT NULL COMMENT '描述',
KEY `bookID` (`bookID`)
) ENGINE=INNODB DEFAULT CHARSET=utf8

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

1.2 基本环境

1.21 Maven
<dependencies>
   <!--Junit-->
   <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>

   <!--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>
    <!--Lombok-->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.12</version>
    </dependency>
    <!--事务-->
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.8.13</version>
    </dependency>
</dependencies>
1.22 资源导出
    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <excludes>
                    <exclude>**/*.properties</exclude>
                    <exclude>**/*.xml</exclude>
                </excludes>
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>
1.23 IDEA 连接数据库
1.24 建立项目目录

image-20210401165119782.png

设置MySql自动补全

image-20210402082308785.png

image-20210402082349367.png

1.241 applicationContext
<?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>
1.242 mybatis-config
<?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>

2、Mybatis

2.1 database.properties

jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/ssmbuild?useSSL=true&characterEncoding=utf8&useUnicode=true
jdbc.username = root
jdbc.password = **********
  • #如果使用的是Mysql8.0以上版本,需要增加一个时区配置 serverTimezone=Asia/Shanghai

2.2 mybatis-config

    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>

	<typeAliases>
        <package name="com.henjie.pojo"/>
    </typeAliases>
  • 数据源的配置交给Spring去做
  • 扫描实体类的包,它的默认别名就为这个类的类名

2.3 pojo 创建实体类

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Books {
    private int bookID;
    private String bookName;
    private int bookCounts;
    private String detail;
}

2.4 DAO 创建接口

public interface BooksMapper {
    //增加一本书
    int addBooks(Books books);

    //删除一本书
    int deleteBooksByID(@Param("bookID") int bookID);

    //更新一本书
    int updateBooks(Books books);

    //根据BookID查询一本书
    Books queryBooksByID(@Param("bookID") int bookID);

    //查询全本的书
    List<Books> queryAllBooks();
}

2.5 DAO BooksMapper.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.henjie.dao.BooksMapper">

</mapper>

CRUD

    <insert id="addBooks" parameterType="Books">
        INSERT INTO ssmbuild.books(bookName,bookCounts,detail)
        values (#{bookName},#{bookCounts},#{detail})
    </insert>
    <delete id="deleteBooksByID" parameterType="int">
        delete from ssmbuild.books
        where bookID = #{bookID}
    </delete>
    <update id="updateBooks" parameterType="Books">
        update ssmbuild.books
        set bookName=#{bookName},bookCounts=#{bookCounts},detail=#{detail}
        where bookID = #{bookID}
    </update>
    <select id="queryBooksByID" parameterType="Books" resultType="Books">
        select *
        from ssmbuild.books
        where bookID = #{bookID}
    </select>
    <select id="queryAllBooks" resultType="Books">
        select * from ssmbuild.books
    </select>

2.6 注册mapper

mybatis-config.xml

    <!--sql语句完成后,立即注册mapper-->
    <mappers>
        <package name="com.henjie.dao"/>
    </mappers>

2.7 Service

BooksService&BooksServiceImpl

    //Service层调用DAO层
    private BooksMapper booksMapper;

    //设置set方法,spring便可进行DL的set注入,进行托管。
    public void setBooksMapper(BooksMapper booksMapper) {
        this.booksMapper = booksMapper;
    }

    public int addBooks(Books books) {
        return booksMapper.addBooks(books);
    }

    public int deleteBooksByID(int id) {
        return booksMapper.deleteBooksByID(id);
    }

    public int updateBooks(Books books) {
        return booksMapper.updateBooks(books);
    }

    public Books queryBooksByID(int id) {
        return booksMapper.queryBooksByID(id);
    }

    public List<Books> queryAllBooks() {
        return booksMapper.queryAllBooks();
    }

2、Spring

2.1 Spring整合DAO

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、数据库连接池
        dbcp:半自动化操作,不能自动连接
        c3po:自动化操作(自动化加载配置文件,并且可以自动的设置到对象中)
        druid:kikari
    -->
    <bean id="datasourse" 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="datasourse"/>
        <!--绑定Mybatis的核心配置文件 -->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    </bean>

    <!--4、获取SqlSession,利用配置DAO接口扫描包的方式,动态的实现DAO接口可以注入到Spring(代替原来的DAO层的实现类)-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--注入 sqlSessionFactory-->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <!--要扫描的DAO包-->
        <property name="basePackage" value="com.henjie.dao"/>
    </bean>
</beans>

2.2 Spring整合Service

spring-service.xml

    <!--1、扫描service下的包-->
    <context:component-scan base-package="com.henjie.service"/>

    <!--2、将所有业务类注入到Spring,可以通过配置或注解实现-->
<!--    <bean id="BooksServiceImpl" class="com.henjie.service.BooksServiceImpl">-->
<!--        &lt;!&ndash;利用set注入&ndash;&gt;-->
<!--        <property name="booksMapper" ref="booksMapper"/>-->
<!--    </bean>-->

    <!--3、声明式事务 增删改自动提交-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--注入数据源-->
        <property name="dataSource" ref="datasourse"/>
    </bean>

    <!--4、(可选)aop事务支持-->
  • 完成步骤3时,spring已经有了事务的基本功能
  • 只是没有4时,没有指定具体横切到哪里
  • 只有3时,只要是没有事务的情况下都会默认创建事务
2.21 业务的两种注入方式
2.211 bean注入

spring-service.xml

    <!--2、将所有业务类注入到Spring,可以通过配置或注解实现-->
    <bean id="BooksServiceImpl" class="com.henjie.service.BooksServiceImpl">
        <!--利用set注入-->
        <property name="booksMapper" ref="booksMapper"/>
    </bean>
2.212 注解注入

spring-service.xml

    <!--1、扫描service下的包-->
    <context:component-scan base-package="com.henjie.service"/>

BooksServiceImpl

@Service    //注册为bean
public class BooksServiceImpl implements BooksService{
    //Service层调用DAO层
    @Autowired  //利用set实现自动注入
    private BooksMapper booksMapper;
	……
}

2.3 总结

Spring层主要负责整合DAO和Service层

3、SpringMVC

3.1 附加Web框架

image-20210404110943639.png

3.2 配置web.xml

    <!--1、DispatcherServlet-->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <!--此处不能单绑定spring-mvc.xml的配置文件,这样找不到service层的bean-->
            <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>

    <!--2、乱码过滤-->
    <filter>
        <filter-name>springEncodingFilter</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>springEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!--3、设置session过期时间-->
    <session-config>
        <session-timeout>15</session-timeout>
    </session-config>
  • /表示处理除了页面文件(jsp)外的所有文件,/*表示过滤包括页面文件(jsp)的所有文件。
  • session过滤时间默认单位为分钟(15分钟)

3.3 配置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
       http://www.springframework.org/schema/mvc/spring-mvc.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd">

</beans>
  • 注:添加的约束需要将cache改成mvc(解决mvc相关标签无法找到的问题)
    <!--1、注解驱动(用注解代替处理器映射器和处理器适配器)-->
    <mvc:annotation-driven/>
    <!--2、静态资源过滤(html,css,js等静态资源不执行mvc)-->
    <mvc:default-servlet-handler/>
    <!--3、扫描包(扫描适配Controller)-->
    <context:component-scan base-package="com.henjie.controller"/>

    <!--4、视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
  • 注:根据视图解析器,不要忘记建立响应的文件夹(WEB-INF/jsp)

3.4 总结

至此SSM整合已经完成,剩下的就是写具体的业务逻辑代码

4、Controller&视图层

4.1 Controller

BooksController

@Controller //注册为bean,标记并适配为Controller
@RequestMapping("/book")    //提供浏览器请求的接口
public class BooksController {
    //Controller层调service层
    @Autowired  //自动装配,将service层的类通过set自动注入进来
    @Qualifier("BooksServiceImpl")  //service层如果有多个实现类,利用此注解指定具体需要注入进来的service层实现类
    private BooksService booksService;

    //为spring进行set的DL(依赖注入)提供方法
    public void setBooksService(BooksService booksService) {
        this.booksService = booksService;
    }
}

4.2 查询全部书籍

查询全部书籍,并且返回到一个书籍展示页面

4.21 BooksController
    @RequestMapping("/allbook")
    public String list(Model model){
        List<Books> booksList = booksService.queryAllBooks();
        model.addAttribute("msg",booksList);
        return "allBook";
    }
4.22 index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>首页</title>
    <style>
      a{
        text-decoration: none;
        color: black;
        font-size: 18px;
      }
      h3{
        width: 180px;
        height: 38px;
        margin: 100px 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>
4.23 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">
            <div class="page-header">
                <h1>
                    <small>书籍列表 ------ 显示所有书籍</small>
                </h1>
            </div>
        </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>
                    </tr>
                </thead>
                <%--书籍从数据库中查询出来的,从msg中遍历出来--%>
                <tbody>
                    <c:forEach var="book" items="${msg}">
                        <tr>
                            <td>${book.bookID}</td>
                            <td>${book.bookName}</td>
                            <td>${book.bookCounts}</td>
                            <td>${book.detail}</td>
                        </tr>
                    </c:forEach>
                </tbody>
            </table>
        </div>
    </div>
</div>
</body>
</html>

4.3 新增书籍

4.31 allBook.jsp
<div class="row">
    <div class="col-md-4 column">
        <!--toaddbook-->
        <a class="btn btn-primary" href="${pageContext.request.contextPath}/book/toaddbook">新增书籍</a>
    </div>
</div>
4.31 addBook.jsp
    <form action="${pageContext.request.contextPath}/book/addbook" method="post">
        <div class="form-group">
            <label>书籍名称</label>
            <input type="text" class="form-control" name="bookName" required>
        </div>
        <div class="form-group">
            <label>书籍数量</label>
            <input type="text" class="form-control" name="bookCounts" required>
        </div>
        <div class="form-group">
            <label>书籍描述</label>
            <input type="text" class="form-control" name="detail" required>
        </div>
        <div class="form-group">
            <input type="submit" class="form-control" value="添加">
        </div>
    </form>
4.32 BooksController
    //新增书籍
    //跳转的新增书籍页面
    @RequestMapping("/toaddbook")
    public String toAddPaper(){
        return "addBook";
    }
    //添加书籍请求
    @RequestMapping("/addbook")
    public String toAddBooks(Books books){
        System.out.println("addBook="+books);
        booksService.addBooks(books);
        return "redirect:/book/allbook";    //重定向给/book/allbook请求
    }

4.4 修改书籍

4.41 allBook.jsp
<td>
    <a href="${pageContext.request.contextPath}/book/toupdatebook?id=${book.bookID}">修改</a>
    &nbsp;|&nbsp;
    <a href="">删除</a>
</td>
4.42 BooksController
    //更新书籍
    //跳转的修改页面
    @RequestMapping("/toupdatebook")
    public String toUpdatePaper(int id,Model model){
        Books books = booksService.queryBooksByID(id);
        model.addAttribute("Qbook",books);
        return "updateBook";
    }
    //修改请求
    @RequestMapping("/updatebook")
    public String updateBook(Books books){
        System.out.println("updateBooks="+books);
        booksService.updateBooks(books);
        return "redirect:/book/allbook";
    }
4.43 updateBook.jsp
<form action="${pageContext.request.contextPath}/book/updatebook" method="post">
    <%--前端需要传递隐藏域 bookID,否则SQL语句条件不符,会执行失败--%>
    <input type="hidden" name="bookID" value="${Qbook.bookID}">
    <div class="form-group">
        <label>书籍名称</label>
        <input type="text" class="form-control" name="bookName" value=${Qbook.bookName} required>
    </div>
    <div class="form-group">
        <label>书籍数量</label>
        <input type="text" class="form-control" name="bookCounts" value=${Qbook.bookCounts} required>
    </div>
    <div class="form-group">
        <label>书籍描述</label>
        <input type="text" class="form-control" name="detail" value=${Qbook.detail} required>
    </div>
    <div class="form-group">
        <input type="submit" class="form-control" value="修改">
    </div>
</form>

4.5 删除书籍(Restful)

4.51 allBook.jsp
<a href="${pageContext.request.contextPath}/book/deletebook/${book.bookID}">删除</a>
4.52 BooksController
//删除请求 复习Restful
@RequestMapping("/deletebook/{BID}")
public String deletebook(@PathVariable("BID") int id){
    booksService.deleteBooksByID(id);
    return "redirect:/book/allbook";
}

4.6 小结

至此,该项目已经实现了基本的增删改查操作,实际变化的就是dao层的CRUD、Controller的交互业务以及显示层的JSP。

4.7 附加:搜索功能

做到业务层的实现类

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值