SSM框架整合+案例

SSM框架整合

    • 1、环境要求
    • 2、数据库环境
    • 3、基本环境搭建
      • 3.1 创建项目
      • 3.2 Maven项目添加web支持
      • 3.3 配置pom.xml文件
      • 3.4 建立框架的基本结构和配置文件
        • 3.4.1 创建包
        • 3.4.2 添加配置文件
        • 3.4.3 database.properties文件
        • 3.4.4 mybatis-config.xml 文件
        • 3.4.5 applicationContext.xml 文件
        • 3.4.6 spring-dao.xml 文件
        • 3.4.7 spring-service.xml文件
      • 3.4.8 spring-mvc.xml文件
      • 3.5 框架配置 web.xml文件
    • 4、案例
      • 4.1 创建实体类Books
      • 4.2 编写Mapper接口
      • 4.3 编写Mapper.xml文件
      • 4.4 编写业务层接口BookService
      • 4.5 编写业务层接口BookService 实现类BookServiceImpl
      • 4.6 编写控制层BooksController
      • 4.7 前端页面
        • 4.7.1 index.jsp页面
        • 4.7.2 allBook.jsp页面
        • 4.7.3 addBook.jsp页面
        • 4.7.4 updateBook.jsp页面
        • 4.7.5 运行展示图:

1、环境要求

环境:

开发工具:IDEA  
数据库:MySQL 8  
服务器:Tomcat 9  
Maven 3.6

要求:
需要熟练掌握MySQL数据库,Spring,JavaWeb及MyBatis知识,简单的前端知识;

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 '书名', 
	`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,'从进门到进牢');

3、基本环境搭建

3.1 创建项目

  1. 打开idea,创建新项目。
    SSM框架整合+案例_第1张图片
    新建一Maven项目
    SSM框架整合+案例_第2张图片
    项目名字叫ssm
    SSM框架整合+案例_第3张图片
    创建完成以后,maven目录结构如下:
    SSM框架整合+案例_第4张图片

3.2 Maven项目添加web支持

右键项目添加web支持
SSM框架整合+案例_第5张图片
选择添加web框架,注意版本,点击OK!
SSM框架整合+案例_第6张图片
添加后,idea会自动生成web目录
SSM框架整合+案例_第7张图片

3.3 配置pom.xml文件

在pom.xml文件中导入相关的pom依赖,设置静态资源过滤!

    <dependencies>
        
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.13.2version>
            <scope>testscope>
        dependency>
        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>8.0.23version>
        dependency>
        
        <dependency>
            <groupId>com.mchangegroupId>
            <artifactId>c3p0artifactId>
            <version>0.9.5.5version>
        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.6version>
        dependency>
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatis-springartifactId>
            <version>2.0.6version>
        dependency>
        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webmvcartifactId>
            <version>5.3.5version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-jdbcartifactId>
            <version>5.3.5version>
        dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.coregroupId>
            <artifactId>jackson-databindartifactId>
            <version>2.12.0version>
        dependency>
        
        <dependency>
            <groupId>org.aspectjgroupId>
            <artifactId>aspectjweaverartifactId>
            <version>1.9.6version>
        dependency>
        
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <version>1.16.20version>
            <scope>compilescope>
        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>

3.4 建立框架的基本结构和配置文件

3.4.1 创建包

  • com.ssm.pojo
  • com.ssm.dao
  • com.ssm.service
  • com.ssm.controller
  • com.ssm.service.Impl

创建后,如下图:
SSM框架整合+案例_第8张图片

3.4.2 添加配置文件

在resources文件夹下创建以下几个配置文件

  • mybatis-config.xml
  • applicationContext.xml
  • database.properties
  • spring-dao.xml
  • spring-service.xml
  • spring-mvc.xml

添加完成,如下图:
SSM框架整合+案例_第9张图片

3.4.3 database.properties文件

jdbc.Driver = com.mysql.cj.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/2022?useSSL=true&useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai
jdbc.username = root
jdbc.password = 123456

3.4.4 mybatis-config.xml 文件


DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    settings>
    
    <typeAliases>
       <package name="com.ming.pojo"/>
    typeAliases>
    <mappers>
        <mapper resource="com/ssm/dao/BookMapper.xml"/>
    mappers>
configuration>

3.4.5 applicationContext.xml 文件


<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:content="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">
    
    <import resource="spring-dao.xml"/>
    <import resource="spring-mvc.xml"/>
    <import resource="spring-service.xml"/>
beans>

3.4.6 spring-dao.xml 文件

配置Spring整合MyBatis,我们这里数据源使用c3p0连接池:


<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:content="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">
    
    
    <content:property-placeholder location="classpath*:db.properties"/>
    
    
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        
        <property name="driverClass" value="${jdbc.Driver}">property>
        <property name="jdbcUrl" value="${jdbc.url}">property>
        <property name="user" value="${jdbc.username}">property>
        <property name="password" value="${jdbc.password}">property>
        
        <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.ming.dao"/>
    bean>
beans>

3.4.7 spring-service.xml文件

Spring整合service层


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:content="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       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/aop
       https://www.springframework.org/schema/aop/spring-aop.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd">
    <import resource="spring-dao.xml"/>
    
    
    <content:component-scan base-package="com.ssm.service"/>

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

    
    <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="*" propagation="REQUIRED"/>
        tx:attributes>
    tx:advice>
    <aop:config>
        <aop:pointcut id="txPointcut" expression="execution(* com.ssm.dao.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut">aop:advisor>
    aop:config>


beans>

3.4.8 spring-mvc.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"
       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">
    
    
    <mvc:annotation-driven/>
    
    <mvc:default-servlet-handler/>
    
    <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>
    
    <context:component-scan base-package="com.ssm.controller"/>
beans>

3.5 框架配置 web.xml文件

SSM框架整合+案例_第10张图片

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

4、案例

目录结构如下:
SSM框架整合+案例_第11张图片

4.1 创建实体类Books

package com.ssm.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;
}

4.2 编写Mapper接口

package com.ssm.dao;
import com.ssm.pojo.Books;
import java.util.List;

public interface BookMapper {
    int addBook(Books book);
    int deleteBookById(int id);
    int updateBook(Books book);
    Books queryBookById(int id);
    List<Books> queryAllBooks();
    List<Books> queryBookByName(String bookName);
}

4.3 编写Mapper.xml文件

<?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="com.ssm.dao.BookMapper">
    <insert id="addBook" parameterType="Books">
        insert  into books
        values(#{bookID},#{bookName},#{bookCounts},#{detail})
    </insert>
    <delete id="deleteBookById" parameterType="int">
        delete
        from books
        where bookID = #{id}
    </delete>
    <update id="updateBook" parameterType="Books">
        update books
        set bookName= #{bookName}, bookCounts= #{bookCounts},detail= #{detail}
        where bookID = #{bookID}
    </update>
    <select id="queryBookById" parameterType="int" resultType="Books">
        select *
        from books
        where bookID= #{id}
    </select>
    <select id="queryAllBooks" resultType="Books">
        select  *
        from books
    </select>
    <select id="queryBookByName" parameterType="string" resultType="Books">
        select *
        from books
        where bookName = #{bookName}
    </select>
</mapper>

4.4 编写业务层接口BookService

package com.ssm.service;
import com.ssm.pojo.Books;
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> queryAllBooks();
    List<Books> queryBookByName(String bookName);
}

4.5 编写业务层接口BookService 实现类BookServiceImpl

package com.ming.service.Impl;
import com.ming.dao.BookMapper;
import com.ming.pojo.Books;
import com.ming.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
public class BookServiceImpl implements BookService {
    //调用dao层的操作,设置一个set接口,方便Spring管理
    @Autowired
    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> queryAllBooks() {
        return bookMapper.queryAllBooks();
    }

    public List<Books> queryBookByName(String bookName) {
        return bookMapper.queryBookByName(bookName);
    }
}

4.6 编写控制层BooksController

package com.ssm.controller;

import com.ssm.pojo.Books;
import com.ssm.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import java.util.List;

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

    //查询所有图书
    @GetMapping("/queryAllBooks")
    public String queryAllBooks(Model model) {
        List<Books> books = bookService.queryAllBooks();
        System.out.println(books.toString());
        model.addAttribute("books", books);
        //通过视图解析器返回allBook.jsp
        return "allBook";
    }

    @RequestMapping("/toAddBook")
    public String toAddPaper() {
        return "addBook";
    }
    //添加图书
    @PostMapping("/addBook")
    public String addBook(Books books, Model model) {
        System.out.println(books);
        int i = bookService.addBook(books);
        if (i == 1) {
            model.addAttribute("msg", "添加成功!");
            return "redirect:/book/queryAllBooks";
        } else {
            model.addAttribute("msg", "添加失败!");
            return "redirect:/book/queryAllBooks";
        }
    }
    //更新图书
    @PostMapping("/updateBook")
    public String updateBook(Books book,Model model){
        System.out.println(book);
        int i = bookService.updateBook(book);
        if (i == 1) {
            model.addAttribute("msg", "修改成功!");
            return "redirect:/book/queryAllBooks";
        } else {
            model.addAttribute("msg", "修改失败!");
            return "redirect:/book/queryAllBooks";
        }
    }
    @GetMapping("/toUpdateBook")
    public String toUpdateBook(int id,Model model){
        Books books = bookService.queryBookById(id);
        model.addAttribute("book",books);
        return "updateBook";
    }
    //删除图书
    @RequestMapping("/del/{bookID}")
    public String deleteBookById(@PathVariable("bookID") int id,Model model){
        System.out.println("---------------------");
        System.out.println(id);
        int i = bookService.deleteBookById(id);
        if (i == 1) {
            return "redirect:/book/queryAllBooks";
        } else{
            return "index";
        }
    }
    @PostMapping("/queryBookByName")
    public String queryBookByName(String queryBookName , Model model){
        System.out.println("搜索!!!");
        List<Books> books = bookService.queryBookByName(queryBookName);
        if (books==null){
            books = bookService.queryAllBooks();
            model.addAttribute("books",books);
        }else{
            model.addAttribute("books",books);
        }
        return "allBook";

    }
}

4.7 前端页面

4.7.1 index.jsp页面

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
DOCTYPE HTML>
<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>
<h1 style="color: red">${msg}h1>
<h3>
    <a href="${pageContext.request.contextPath}/book/queryAllBooks">点击进入列表页a>
h3>
body>
html>

4.7.2 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>
    <meta name="viewport" content="width=device-width, initial- scale=1.0">
    
    <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>
                <c:if test="${msg}!=null">
                    <h2><small>${msg}small>h2>
                c:if>
            div>
        div>
        <div class="col-md-4 column">div>
        <div class="col-md-4 column">
            <form class="form-inline" action="${pageContext.request.contextPath}/book/queryBookByName" method="post" style="float: right">
                <input type="text" name="queryBookName" class="form-control" placeholder="输入查询书名" required>
                <input type="submit" value="查询" class="btn btn-primary">form>
        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('books')}">
                    <tr>
                        <td>${book.getBookID()}td>
                        <td>${book.getBookName()}td>
                        <td>${book.getBookCounts()}td>
                        <td>${book.getDetail()}td>
                        <td>
                            <a href="${pageContext.request.contextPath}/book/toUpdateBook?id=${book.getBookID()}">更改a>
                            <a href="${pageContext.request.contextPath}/book/del/${book.getBookID()}"> 删除a>
                        td>
                    tr>
                c:forEach>
                tbody>
            table>
        div>
    div>
div>

4.7.3 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>
    <meta name="viewport" content="width=device-width, initial- scale=1.0"> 
    <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="bookCounts"><br><br><br>
        书籍详情:<input type="text" name="detail"><br><br><br>
        <input type="submit" value="添加">form>
div>

4.7.4 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>
    <meta name="viewport" content="width=device-width, initial- scale=1.0"> 
    <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="bookCounts" value="${book.getBookCounts()}"/>
        书籍详情:<input type="text" name="detail" value="${book.getDetail() }"/>
        <input type="submit" value="提交"/>form>
div>

4.7.5 运行展示图:

查询所有图书:
SSM框架整合+案例_第12张图片
添加图书:
SSM框架整合+案例_第13张图片
更新图书:
SSM框架整合+案例_第14张图片

结束!!!

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