SpringMVC SSM整合

SpringMVC SSM整合

本篇主要将mybatis,javaEE web,SpringMVC框架整合,并进行了简单的书籍CRUD示例,仅做参考,后续spring-boot会简化此篇的配置

基础环境

mysql

CREATE DATABASE ssmbuild;
USE ssmbuild;
CREATE TABLE `books`(
`bookID` INT NOT NULL AUTO_INCREMENT COMMENT '书id',
`bookName` VARCHAR(100) NOT NULL COMMENT '书名',
`bookCounts` INT NOT NULL COMMENT '数量',
`detail` VARCHAR(200) NOT NULL COMMENT '描述',
KEY `bookID`(`bookID`)
)ENGINE=INNODB DEFAULT CHARSET=utf;
INSERT INTO `books`(`bookID`,`bookName`,`bookCounts`,`detail`)VALUES
(1,'Java',1,'从入门到放弃'),
(2,'MySQL',10,'从删库到跑路'),
(3,'Linux',5,'从进门到进牢');

pom

  • 分为control dao pojo service四层

  • 所用pom依赖包括junit mysql-connector-java c3p0 servlet-api jstl jsp-api mybatis myabtis-spring spring-jdbc lombok 注意:c3p0下载0.9.5以上版本,groupid为com.mchange

  • 处理识别resources的路径

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

配置文件

  • 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="classpath:spring-dao.xml"/>
        <import resource="classpath:spring-service.xml"/>
        <import resource="classpath:spring-mvc.xml"/>
    </beans>
    
  • 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>
        <typeAliases>
            <typeAlias type="com.pojo.Books" alias="Books"/>
            <package name="com.pojo"/>
        </typeAliases>
    </configuration>
    
  • database.properties

    jdbc.driver = com.mysql.cj.jdbc.Driver
    jdbc.url = jdbc:mysql://localhost:3306/ssmbuild?serverTimezone=UTC&useSSL=false
    jdbc.username = root
    jdbc.password = 123456
    
  • mapper.xml(dao层)

    <?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">
    <!--命名空间,类似包的概念: namespace:绑定一个对应的Dao/Mapper接口-->
    <mapper namespace="com.dao.BookMapper">
        <insert id="addBook" parameterType="Books">
            insert into ssmbuild.books (bookName,bookCounts,detail)
            values (#{bookName},#{bookCounts},#{detail})
        </insert>
        <delete id="deleteBookById" parameterType="int">
            delete from ssmbuild.books where bookID=#{bookId}
        </delete>
        <update id="updateBook" parameterType="Books">
            update ssmbuild.books set bookName=#{bookName},bookCounts=#{bookCounts},detail=#{detail} where bookID=#{bookID};
        </update>
        <select id="queryBookById" resultType="Books">
            select * from ssmbuild.books where bookID = #{bookId}
        </select>
        <select id="queryAllBook" resultType="Books">
            select * from ssmbuild.books
        </select>
    </mapper>
    

spring整合mybatis配置文件

  • spring-dao.xml 用于配置数据库连接池(之前是直接在mybatis中配置)

    <?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">
        <!--关联数据库配置文件 -->
        <context:property-placeholder location="classpath:database.properties" />
        <!--连接池 dbcp:半自动化操作,不能自动连接
        c3p0:自动化操作,自动化加载配置文件,可以自动设置到对象中
        druid:
          hikari-->
        <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>
        <!-- sqlSessionFactory -->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource"/>
            <property name="configLocation" value="classpath:mybatis-config.xml"/>
        </bean>
           <!--配置dao接口扫描,dao接口自动注册 -->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
            <property name="basePackage" value="com.dao"/>
        </bean>
    </beans>
    
  • spring-service.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">
        <!--扫描service下的包 -->
        <context:component-scan base-package="com.service"/>
        <!--将所有业务类注入到spring -->
        <bean id="BookServiceImpl" class="com.service.BookServiceImpl">
            <property name="bookMapper" ref="bookMapper"/>
        </bean>
        <!--声明式事务配置 -->
        <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <property name="dataSource" ref="dataSource"/>
        </bean>
    </beans>
    

web配置(jsp)

  • 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">
        <!-- dispatchServlet -->
        <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:spring-mvc.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>
    
  • spring-mvc(整合jsp与spring)

    <?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/>
        <!--静态资源过滤 -->
        <mvc:default-servlet-handler/>
        <!--扫描包controller -->
        <context:component-scan base-package="com.controller"/>
        <!--视图解析器 -->
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/jsp/"/>
            <property name="suffix" value=".jsp"/>
        </bean>
    </beans>
    

java代码

package com.dao;
import com.pojo.Books;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface BookMapper {
    //CRUD
    int addBook(Books books);
    int deleteBookById(@Param("bookId") int id);
    int updateBooks(Books books);
    Books queryBookById(@Param("bookId") int id);
    List<Books> queryAllBook();
}

service层接口此类除@Param注解外完全相同

@Data
@AllArgsConstructor
@Service
public class BookServiceImpl implements BookService {
    @Autowired
    private BookMapper bookMapper;
    public int addBook(Books books) {
        return bookMapper.addBook(books);
    }
    public int deleteBookById(int id) {
        return bookMapper.deleteBookById(id);
    }
    public int updateBooks(Books books) {
        return bookMapper.updateBooks(books);
    }
    public Books queryBookById(int id) {
        return bookMapper.queryBookById(id);
    }
    public List<Books> queryAllBook() {
        return bookMapper.queryAllBook();
    }
}

summary

  1. 整体思路为:整合mybatis,spring与mvc;

    1. mybatis整合需要mybatis-config.xml,其中包括对pojo的重命名以及所需扫描对应mapper的句柄
    2. spring为最大容器,首先需要建立applicationContext.xml利用import导入所有配置文件;然后使用spring-dao.xml进行dao层与mybatis 的sqlSession的相关配置;再次使用spring-service.xml进行扫描包与IOC事务的配置;最后使用spring-mvc.xml进行与mvc的集成配置
    3. mvc为web容器,主要集成servlet
  2. mybatis-config.xml:typeAlias声明pojo类,mappers扫描dao层的mapper.xml文件

  3. spring-dao.xml:为mybatis-spring的相关配置文件

    bean-dataSource建立数据源(读取database.properties)=>context:property-placeholder location

    bean-sqlSessionFactory 并配置sao层接口的扫描(此处的扫描为mybatis扫描)

  4. springt-service.xml:为本身spring IOC容器的配置文件

    扫描service的包,注入业务类(扫描包情况下为自动注入,也可手动指定)

    声明式事务配置

  5. spring-mvc.xml:为mvc-servlet的相关配置文件

    配置mvc注解驱动,静态资源过滤,扫描包(扫描web-controller),视图解析器

前端代码

index

<%@ 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: deepskyblue;border-radius: 5px;
      }
    </style>
  </head>
  <body>
  <h3>
    <a href="${pageContext.request.contextPath}/book/allbook">进入书籍展示页面</a>
  </h3>
  </body>
</html>

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>
    <%--    bootstrp美化页面--%>
    <link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<%--<h3 style="text-align: center">书籍展示页面</h3>--%>
<div class="container">
    <div class="row_clearfix">
        <div class="col-md-12 column">
            <div class="page-header">
                <h1 style="text-align: center"><small>书籍列表——显示所有书籍</small></h1>
            </div>
        </div>
        <div class="row">
            <div class="col-md-5 column">
                <a class="btn btn-primary" href="${pageContext.request.contextPath}/book/toAddBook" style="float: left">新增书籍</a>
                <form action="${pageContext.request.contextPath}/book/queryBook" method="post" style="float: right" class="form-inline">
                    <input type="text" name="bookName" class="form-control" placeholder="请输入要查询的名称">
                    <input type="submit" value="查询" class="btn btn-primary">
                    <a class="btn btn-primary" href="${pageContext.request.contextPath}/book/allbook">重置</a>
                </form>

            </div>
        </div>
    </div>
    <div class="row_clearfix">
        <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="${list}">
                <tr>
                    <td>${book.bookId}</td>
                    <td>${book.bookName}</td>
                    <td>${book.bookCounts}</td>
                    <td>${book.detail}</td>
                    <td>
                        <a href="${pageContext.request.contextPath}/book/toUpdateBook?id=${book.bookId}">修改</a>
                        &nbsp; | &nbsp;
                        <a href="${pageContext.request.contextPath}/book/deleteBook/${book.bookId}">删除</a>
                    </td>
                </tr>
            </c:forEach>
            </tbody>
        </table>
    </div>
</div>
</body>
</html>
posted @ 2021-05-17 22:10  WheelCode  阅读(78)  评论(0)    收藏  举报