ssm框架整合详细过程

最近又被push打工,框架整合拖拖拉拉看了好久,完成了书籍的增删改查,记录一下整个框架整合流程,也当作是复习巩固了。

1.0 环境要求

  • IDEA
  • MySQL 5.7.19
  • Tomcat 9
  • Maven 3.6

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. 新建一Maven项目!ssmbuild,添加web的支持
  2. 导入相关的pom依赖和maven资源过滤

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>

    <groupId>com.fanjhgroupId>
    <artifactId>ssmbuildartifactId>
    <version>1.0-SNAPSHOTversion>

    
    <dependencies>
        
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.12version>
        dependency>

        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>5.1.47version>
        dependency>

        
        <dependency>
            <groupId>com.mchangegroupId>
            <artifactId>c3p0artifactId>
            <version>0.9.5.2version>
        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.2version>
        dependency>
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatis-springartifactId>
            <version>2.0.2version>
        dependency>
        
        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webmvcartifactId>
            <version>5.1.9.RELEASEversion>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-jdbcartifactId>
            <version>5.1.9.RELEASEversion>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <version>1.18.12version>
        dependency>
    dependencies>

    
    <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>
project>

注意:这里导包之后记得查看project structure中有无相关包,一般要手动导入
ssm框架整合详细过程_第1张图片

  1. 建立基本结构和框架:
  • com.fanjh.pojo
  • com.fanjh.dao
  • com.fanjh.service
  • com.fanjh.controller
  • mybatis-config.xml

这里给出最终结构
ssm框架整合详细过程_第2张图片
前端调用controller层, controller层调用service层,service层调用dao层

1.2 mybatis层编写

  1. 数据库配置文件database.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=false&useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=fjhmysql
  1. 连接数据库
  2. 编写mybatis核心配置文件:mybatis-config.xml


<configuration>
    
    

    <typeAliases>
        <package name="com.fanjh.pojo"/>
    typeAliases>

    <mappers>
        <mapper class="com.fanjh.dao.BookMapper"/>
    mappers>
configuration>
  1. 编写数据库对应实体类:com.fanjh.pojo.Books
    使用lombok插件
package com.fanjh.pojo;

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

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Books {
    private int bookID;
    private String bookName;
    private int bookCounts;
    private String detail;
}
  1. 紧接着编写dao层的mapper接口
package com.fanjh.dao;

import com.fanjh.pojo.Books;
import org.apache.ibatis.annotations.Param;

import java.util.List;
//增删改查方法
public interface BookMapper {
    int addBook(Books book);

    int deleteBookById(@Param("bookId") int id);

    int updateBook(Books book);

    Books queryBookById(@Param("bookId") int id);

    List<Books> queryAllBook();
}
  1. 马上编写接口对应的Mapper.xml文件(对应sql语句), 需要注册到mybatis.xml





    
        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" parameterType="int" resultType="Books">
        select * from ssmbuild.books where bookID=#{bookId};
    select>
    
    <select id="queryAllBook" resultType="Books">
        select * FROM ssmbuild.books
    select>
mapper>

至此,搞定dao层,接下来业务层。

  1. 编写Service层接口和实现类
    接口:
package com.fanjh.service;

import com.fanjh.pojo.Books;
import org.apache.ibatis.annotations.Param;
import java.util.List;

public interface BookService {
    int addBook(Books book);

    int deleteBookById(int id);

    int updateBook(Books book);

    Books queryBookById(int id);

    List<Books> queryAllBook();
}

实现类:

package com.fanjh.service;

import com.fanjh.dao.BookMapper;
import com.fanjh.pojo.Books;
import java.util.List;

public class BookServiceImpl implements BookService {
    //service层调dao层
    private BookMapper bookMapper;

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

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

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

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

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

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

可以看到,service层的方法都是直接调用dao层的方法,到此底层需求操作编写完毕。

1.3 spring层

  1. 配置Spring整合MyBatis,这里使用c3p0连接池。
  2. 编写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.fanjh.dao"/>
    bean>
beans>
  1. 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.fanjh.service"/>

    
    <bean id="BookServiceImpl" class="com.fanjh.service.BookServiceImpl">
        <property name="bookMapper" ref="bookMapper"/>
    bean>

    
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        
        <property name="dataSource" ref="datasource"/>
    bean>
beans>

至此,spring层搞定,spring就是个大容器,整合dao层和service层,也是实现了dao层和service层的分离——解耦。

1.4 springMVC层

  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>encodingFilterfilter-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>encodingFilterfilter-name>
        <url-pattern>/*url-pattern>
    filter-mapping>

    
    <session-config>
        <session-timeout>15session-timeout>
    session-config>

web-app>
  1. spring-mvc.xml

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

    

    
    <mvc:annotation-driven/>
    
    <mvc:default-servlet-handler/>
    
    <context:component-scan base-package="com.fanjh.controller"/>
    
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    bean>
beans>
  1. 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>

至此,所有的配置文件暂告一段落,接下来编写Controller和视图层,Controller和视图层交互,然后调用service层。

  1. BookController类编写,增删改查书籍(Controller层的编写需要实时对照视图层)
package com.fanjh.controller;
import com.fanjh.pojo.Books;
import com.fanjh.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 list(Model model) {
        List<Books> list = bookService.queryAllBook();
        model.addAttribute("list", list);
        return "allBook";
    }

    //跳转到增加书籍页面
    @RequestMapping("/toAddBook")
    public String toAddBook(){

        return "addBook";
    }

    //添加书籍的请求
    @RequestMapping("/addBook")//执行完后,重定向到allbook页面
    public String addBook(Books books){
        System.out.println("addBook=>" + books);
        bookService.addBook(books);
        return "redirect:/book/allBook";
    }

    //跳转到修改书籍页面
    @RequestMapping("/toUpdate")
    public String toUpdateBook(int id, Model model){
        Books books = bookService.queryBookById(id);//根据id取到图书
        model.addAttribute("Qbooks",books);//将图书返回给前端

        return "updateBook";
    }

    //修改书籍
    //接收到前端传来的数据,调用service层执行修改操作
    @RequestMapping("/updateBook")
    public String updateBook(Books books){
        System.out.println("updateBook=>" + books);
        bookService.updateBook(books);

        return "redirect:/book/allBook";
    }

    //删除书籍
    @RequestMapping("/deleteBook/{bookId}")//restful风格
    public String deleteBook(@PathVariable("bookId") int id){
        bookService.deleteBookById(id);
        
        return "redirect:/book/allBook";
    }
}
  1. 编写首页index.jsp
<%--
  Created by IntelliJ IDEA.
  User: fjh990
  Date: 2020/11/7
  Time: 12:16
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
  <title>首页</title>
  <style>
    a{
      text-decoration: none;
      color: gold;
      font-size: 50px;
    }
    h3{
      width:500px;
      height:80px;
      margin:500px auto;
      text-align: center;
      line-height: 80px;
      background: black;
      border-radius: 6px;
    }
  </style>
</head>
<body>

<h3>
  <a href="${pageContext.request.contextPath}/book/allBook">进入书籍页面</a>
</h3>

</body>
</html>

  1. 新建三个.jsp文件:
  • allBook:显示所有书籍
  • addBook:增加书籍
  • updateBook:修改书籍

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>
        <%--增加书籍按钮,点击后跳到controller页面,然后根据return值到addbook.jsp--%>
        <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="${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/toUpdate?id=${book.bookID}">修改</a>
                                &nbsp; | &nbsp;
                                <a href="${pageContext.request.contextPath}/book/deleteBook/${book.bookID}">删除</a>
                            </td>
                        </tr>
                    </c:forEach>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
</body>
</html>

addBook.jsp:

<%@ 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>

    <%--点击添加按钮后,跳转到/book/addBook执行添加操作(属性名一定要一致)--%>
    <form action="${pageContext.request.contextPath}/book/addBook"
          method="post">
        书籍名称:<input type="text" name="bookName" required><br><br><br>
        书籍数量:<input type="text" name="bookCounts" required><br><br><br>
        书籍详情:<input type="text" name="detail" required><br><br><br>
        <input type="submit" value="添加">
    </form>
</div>

</body>
</html>

这里拿增加书籍举例梳理整个流程:

  1. 前端点击新增书籍按钮后,跳转到controller找到/book/toAddBook,跳转到toAddBook页面
  2. 根据toAddBook页面的return语句,拼接后找到/WEB-INF/jsp/addBook.jsp文件
  3. 根据页面展示,填写所要增加的书籍的内容
  4. 点击“添加”按钮,返回controller找到/book/addBook页面,并传回books信息
  5. controller层调用service层执行增加书籍操作。
  6. 返回到显示书籍页面

updateBook.jsp:

<%@ 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>



    <%--我们提交了修改的sql请求,但是修改失败,spring接管事务后不需要显式的配置,不是事务问题
         看一下sql语句,能否执行成功:sql执行失败
         前端传递隐藏域--%>

    <form action="${pageContext.request.contextPath}/book/updateBook"
          method="post">
        <input type="hidden" name="bookID" value="${Qbooks.bookID}">

        书籍名称:<input type="text" name="bookName" value="${Qbooks.bookName}" required><br><br><br>
        书籍数量:<input type="text" name="bookCounts" value="${Qbooks.bookCounts}" required><br><br><br>
        书籍详情:<input type="text" name="detail" value="${Qbooks.detail}" required><br><br><br>
        <input type="submit" value="修改">
    </form>
</div>

</body>
</html>

至此,整个项目整合完毕

你可能感兴趣的:(框架,java,spring,ssm)