SpringMVC06:整合SSM框架

1、环境说明

  • IDEA
  • MySQL 5.7.29
  • Tomcat 9
  • Maven 3.6.3

2、数据库环境

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

CREATE DATABASE `ssm_build`;

USE `ssm_build`;

DROP TABLE IF EXISTS `book`;

CREATE TABLE `book` (
 `book_id` INT(10) primary key AUTO_INCREMENT COMMENT '书id',
 `book_name` VARCHAR(100) NOT NULL COMMENT '书名',
 `book_count` INT(11) NOT NULL COMMENT '数量',
 `detail` VARCHAR(200) NOT NULL COMMENT '描述'
) ENGINE=INNODB DEFAULT CHARSET=utf8;

INSERT  INTO `book`(`book_id`,`book_name`,`book_count`,`detail`)VALUES
(1,'Java',1,'从入门到放弃'),
(2,'MySQL',10,'从删库到跑路'),
(3,'Linux',5,'从入门到进牢');

3、基本环境搭建

1、新建一个Maven项目,SSMBuild,添加web支持

2、导入相关pom依赖

<dependencies>
    <!-- junit测试 -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>

    <!-- mysql驱动 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.23</version>
    </dependency>

    <!-- 数据库连接池:c3p0 -->
    <dependency>
        <groupId>com.mchange</groupId>
        <artifactId>c3p0</artifactId>
        <version>0.9.5.2</version>
    </dependency>

    <!-- mybatis -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.6</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>2.0.6</version>
    </dependency>

    <!-- spring -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.3.5</version>
    </dependency>
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.9.6</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.3.5</version>
    </dependency>

    <!-- web -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>javax.servlet.jsp-api</artifactId>
        <version>2.3.3</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>
</dependencies>

3、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.org.pojo

  • com.org.mapper

  • com.org.service

  • com.org.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
               https://www.springframework.org/schema/beans/spring-beans.xsd
               ">
        
        </beans>
      

4、MyBatis层

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

driver=com.mysql.cj.jdbc.Driver
# 如果使用的MySQL8.0+,需要增加一个时区配置:&serverTimezone = Asia/Shanghai
url=jdbc:mysql://localhost:3306/ssm_build?useSSL=true&useUnicode=true&characterEncoding=utf8
username=root
password=123456

2、编写实体类(使用Lombok)

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

3、配置mybatis核心配置文件(mybatis-config.xml)

<settings>
    <!-- 开启日志 -->
    <setting name="logImpl" value="STDOUT_LOGGING"/>
    <!-- 开启驼峰命名自动映射 -->
    <setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>

<!-- 别名 -->
<typeAliases>
    <package name="org.com.pojo"/>
</typeAliases>

4、编写mapper接口

public interface BookMapper {

    // 增加一本书
    int addBook(Book book);

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

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

    // 根据id查询一本书
    Book selectBookById(@Param("bookId") int Id);

    // 查询所有书
    List<Book> bookList();

}

5、编写相应的映射文件

<?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="org.com.mapper.BookMapper">

    <insert id="addBook" parameterType="book">
        insert into book (book_id, book_name, book_count, detail)
        values(#{bookId}, #{bookName}, #{bookCount}, #{detail})
    </insert>

    <delete id="deleteBookById" parameterType="_int">
        delete from book where book_id = #{bookId}
    </delete>

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

    <select id="selectBookById" resultType="book" parameterType="_int">
        select * from book where book_id = #{bookId}
    </select>

    <select id="bookList" resultType="book">
        select * from book
    </select>

</mapper>

6、编写service接口及其实现类

public interface BookService {

    // 增加一本书
    int addBook(Book book);

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

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

    // 根据id查询一本书
    Book selectBookById(int Id);

    // 查询所有书
    List<Book> bookList();
}
@Service("bookServiceImpl")
public class BookServiceImpl implements BookService {
    @Autowired
    private BookMapper bookMapper;

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

    @Override
    public int deleteBookById(int Id) {
        return bookMapper.deleteBookById(Id);
    }

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

    @Override
    public Book selectBookById(int Id) {
        return bookMapper.selectBookById(Id);
    }

    @Override
    public List<Book> bookList() {
        return bookMapper.bookList();
    }
}

OK,到此,底层需求操作编写完毕!

5、Spring层

1、编写spring-mapper.xml文件整合Spring和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
       https://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd
       ">


    <!-- 1.读取数据库配置文件
         system-properties-mode="NEVER" :防止${xxx}读取环境变量
    -->
    <context:property-placeholder location="classpath:database.properties" system-properties-mode="NEVER"/>

    <!-- 2.数据库连接池 -->
    <!-- 数据库连接池
         dbcp 半自动化操作 不能自动连接
         c3p0 自动化操作(自动的加载配置文件 并且设置到对象里面)
    -->
    <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}"/>

        <!-- 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" />
        <!-- 关联MyBatis配置文件:mybatis-config.xml -->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    </bean>

    <!-- 4.配置扫描mapper接口包,动态实现mapper接口注入到spring容器中 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 给出需要扫描mapper接口包 -->
        <property name="basePackage" value="org.com.mapper" />
        <!-- 注入sqlSessionFactory -->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    </bean>

</beans>

2、编写spring-service.xml文件整合Spirng和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"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       https://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/aop
       https://www.springframework.org/schema/aop/spring-aop.xsd
       http://www.springframework.org/schema/tx
       https://www.springframework.org/schema/tx/spring-tx.xsd
       ">

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

    <!-- 2.配置事务 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 注入数据库连接池 -->
        <property name="dataSource" ref="dataSource" />
    </bean>
    
    <!-- 配置如何管理事务 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!-- 配置事务的属性 -->
        <tx:attributes>
            <!-- 所有的方法,并不是只读 -->
            <tx:method name="*" read-only="false"/>
        </tx:attributes>
    </tx:advice>

    <!-- 配置拦截哪些方法+事务的属性 -->
    <aop:config>
        <aop:pointcut id="pointcut" expression="execution(* org.com.service.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"/>
    </aop:config>


</beans>

Spring层搞定!再次理解一下,Spring就是一个大杂烩,一个容器!对吧!

6、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">

    <!-- 1.DispatcherServlet -->
    <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>

    <!-- 2.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>

    <!-- 3.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: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
       https://www.springframework.org/schema/mvc/spring-mvc.xsd">
    
    <!-- 1.开启SpringMVC注解驱动 -->
    <mvc:annotation-driven/>
    
    <!-- 2.静态资源默认servlet配置-->
    <mvc:default-servlet-handler/>

    <!-- 3.配置jsp 显示ViewResolver视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <!-- 4.扫描web相关的bean -->
    <context:component-scan base-package="org.com.controller" />

</beans>

3、把每一层的Spring配置文件都导入applicationContext.xml总Spring配置文件

<import resource="spring-mapper.xml"/>
<import resource="spring-service.xml"/>
<import resource="spring-mvc.xml"/>
下面开始编写Controller层和视图

1、编写BookController类,方法一:查询全部书籍

@Controller
@RequestMapping("/book")
public class BookController {
    @Autowired
    @Qualifier("bookServiceImpl")
    private BookService bookService;

    @RequestMapping("bookList")
    public String bookList(Model model){
        List<Book> books = bookService.bookList();
        model.addAttribute("bookList", books);
        return "bookList";
    }

}

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/toBookList">点击进入列表页</a>
    </h3>
  </body>
</html>

3、显示书籍列表页面:bookList.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<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">
                    <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('bookList')}">
                        <tr>
                            <td>${book.getBookId()}</td>
                            <td>${book.getBookName()}</td>
                            <td>${book.getBookCount()}</td>
                            <td>${book.getDetail()}</td>
                            <td>
                                <a href="${pageContext.request.contextPath}/book/toUpdateBook?id=${book.getBookId()}">更改</a> |
                                <a href="${pageContext.request.contextPath}/book/toDeleteBook/${book.getBookId()}">删除</a>
                            </td>
                        </tr>
                    </c:forEach>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

</body>
</html>

4、方法二:添加书籍

@RequestMapping("/toAddBook")
public String toAddPaper(){
    return "addBook";
}

@RequestMapping("/addBook")
public String addPaper(Book book){
    System.out.println(book);
    bookService.addBook(book);
    return "redirect:/book/toBookList";
}

5、添加书籍页面: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">
    <!-- 引入 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>
        <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>

6、方法三:修改书籍

@RequestMapping("toUpdateBook")
public String toUpdatePaper(Model model, int id){
    Book book = bookService.selectBookById(id);
    System.out.println(book);
    model.addAttribute("book", book);
    return "updateBook";
}

@RequestMapping("/updateBook")
public String updatePaper(Model model, Book book) {
    System.out.println(book);
    bookService.updateBook(book);
    Book book2 = bookService.selectBookById(book.getBookId());
    model.addAttribute("book", book2);
    return "redirect:/book/toBookList";
}

7、修改书籍页面: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">
    <!-- 引入 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>

    <form action="${pageContext.request.contextPath}/book/updateBook" method="post">
        <input type="hidden" name="bookId" value="${book.getBookId()}"/>
        书籍名称:<input type="text" name="bookName" value="${book.getBookName()}"/>
        书籍数量:<input type="text" name="bookCount" value="${book.getBookCount()}"/>
        书籍详情:<input type="text" name="detail" value="${book.getDetail() }"/>
        <input type="submit" value="提交"/>
    </form>

</div>
</body>
</html>

8、方法四:删除书籍

@RequestMapping("/toDeleteBook/{bookId}")
public String deleteBook(@PathVariable("bookId") int id) {
    bookService.deleteBookById(id);
    return "redirect:/book/toBookList";
}

配置Tomcat,进行运行!

到目前为止,这个SSM项目整合已经完全的OK了,可以直接运行进行测试!这个练习十分的重要,大家需要保证,不看任何东西,自己也可以完整的实现出来!

项目结构图

7、小结

这个是我们的第一个SSM整合案例,一定要烂熟于心!

SSM框架的重要程度是不言而喻的,学到这里,大家已经可以进行基本网站的单独开发。但是这只是增删改查的基本操作。可以说学到这里,大家才算是真正的步入了后台开发的门。也就是能找一个后台相关工作的底线。

或许很多人,工作就做这些事情,但是对于个人的提高来说,还远远不够!

我们后面还要学习一些 SpringMVC 的知识!

  • Ajax
  • 文件上传和下载
  • 拦截器

posted @ 2021-05-15 20:07  JavaConner  阅读(104)  评论(0)    收藏  举报