SSM框架最新整合保姆级教程(IDEA版)

SSM框架最新整合保姆级教程(IDEA版)

一、环境要求

​ 环境:

  • IDEA
  • MySQL 5.7.19
  • Tomcat 9
  • Maven 3.6

要求:

  • 需要熟练掌握MySQL数据库SpringJavaWebMyBatis知识,简单的前端知识;

完整代码:完整代码下载

二、数据库环境

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

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.1 新建项目

① 新建Maven项目

SSM框架最新整合保姆级教程(IDEA版)_第1张图片

② 编辑项目名称

SSM框架最新整合保姆级教程(IDEA版)_第2张图片

3.2 导入相关的pom依赖


    <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>1.3.1version>
        dependency>
        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webmvcartifactId>
            <version>5.3.6version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-jdbcartifactId>
            <version>5.2.14.RELEASEversion>
        dependency>
        <dependency>
            <groupId>org.aspectjgroupId>
            <artifactId>aspectjweaverartifactId>
            <version>1.8.13version>
        dependency>
    dependencies>

3.3 Maven资源过滤设置(pom.xml文件中)

<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 建立基本的结构和配置框架

  • com.wang.pojo

  • com.wang.dao

  • com.wang.service

  • com.wang.controller

  • mybatis-config.xml(mybatis的核心配置文件)

    
    DOCTYPE configuration
           PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
           "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <configuration>
    
    configuration>
    
  • applicationContext.xml(spring的核心配置文件)

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

四、Mybatis层编写

4.1 数据库配置文件database.properties

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

4.2 IDEA关联数据库

① 输入用户名、密码,测试连接

SSM框架最新整合保姆级教程(IDEA版)_第3张图片

② 选择数据库

SSM框架最新整合保姆级教程(IDEA版)_第4张图片

4.3 编写mybatis核心配置文件

① 配置mybatis核心配置文件


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.wang.pojo"/>
    typeAliases>

    <mappers>
        <mapper class="com.wang.dao.BookMapper"/>
    mappers>

configuration>

② 编写实体类books

package com.wang.pojo;

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

/**
 * @author Wang
 * @date 2021/6/2 0012 19:43
 * description 实体类books
 */
@Data
@AllArgsConstructor //有参构造
@NoArgsConstructor //无参构造
public class Books {

    private int bookID;
    private String bookName;
    private int bookCounts;
    private String detail;
}

③ 新建一个dao接口

package com.wang.dao;import com.wang.pojo.Books;import org.apache.ibatis.annotations.Param;import org.springframework.stereotype.Repository;import java.util.List;/** * @author Wang * @date 2021/6/2 0012 19:52 * description */@Repositorypublic interface BookMapper {//    增加一本书    int addBook(Books books);//    删除一本书    int deleteBookById(@Param("bookID") int id);//    更新一本书    int updateBook(Books books);//    查询一本书    Books queryBookById(@Param("bookID") int id);//    查询全部的书    List queryAllBook();    Books queryBookByName(@Param("bookName") String bookName);}

④ 书写mapper.xml文件

一个mapper就要有一个namespace。


DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.wang.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>


    <select id="queryBookByName" resultType="Books">
        select * from ssmbuild.books
        where bookName = '${bookName}'
    select>

mapper>

⑤ 编写service

package com.wang.service;

import com.wang.pojo.Books;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author Wang
 * @date 2021/5/12 0012 20:03
 * description
 */
@Service
public interface BookService {
    //    增加一本书
    int addBook(Books books);
    //    删除一本书
    int deleteBookById(int id);
    //    更新一本书
    int updateBook(Books books);
    //    查询一本书
    Books queryBookById(int id);
    //    查询全部的书
    List<Books> queryAllBook();

    Books queryBookByName(String bookName);
}
package com.wang.service;

import com.wang.dao.BookMapper;
import com.wang.pojo.Books;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author Wang
 * @date 2021/5/12 0012 20:04
 * description
 */
@Service
public class BookServiceImpl implements BookService {

//    service调用dao层
    @Autowired
    private BookMapper bookMapper;

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

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

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

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

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

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

五、整合Spring层

1、新建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 https://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.wang.dao"/>
    bean>
beans>

2、新建Spring-service.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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
       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">


    <context:component-scan base-package="com.wang.service"/>







    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

        <property name="dataSource" ref="dataSource"/>
    bean>


    <aop:config>
        <aop:pointcut id="txPointCut" expression="execution(* com.wang.dao.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
    aop:config>

    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="add" propagation="REQUIRED"/>
            <tx:method name="delete" propagation="REQUIRED"/>
            <tx:method name="update" propagation="REQUIRED"/>
            <tx:method name="query" read-only="true"/>
            <tx:method name="*" propagation="REQUIRED"/>
        tx:attributes>
    tx:advice>
beans>

六、整合SpringMVC

1、增加web依赖

右键项目名–>选择Add Frameworks Support

SSM框架最新整合保姆级教程(IDEA版)_第5张图片

2、编写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>

3、创建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 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/>

    
    <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.wang.controller" />
beans>

4、编写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-mvc.xml"/>    <import resource="classpath:spring-service2.xml"/>    <import resource="classpath:spring-dao.xml"/>beans>

七、编写功能

1、查询书籍功能

① 编写BookController

package com.wang.controller;

import com.wang.pojo.Books;
import com.wang.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.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Wang
 * @date 2021/5/12 0012 21:12
 * description
 */
@Controller
@RequestMapping("/book")
public class BookController {

//    controller调用service层
    @Autowired
    private BookService bookService;

//    查询选全部的书籍,并且返回到一个书籍展示页面
    @RequestMapping("/allBook")
    public String list(Model model){
        List<Books> list = bookService.queryAllBook();

        model.addAttribute("list",list);
        return "allBook";
    }

//    跳转到增加书籍页面
    @RequestMapping("/toAddBookPage")
    public String toAddPaper(){
        return "addBook";
    }

//    进行添加书籍
    @RequestMapping("/addBook")
    public String addBook(Books books){
        System.out.println("=======>"+books);
        bookService.addBook(books);
        return "redirect:/book/allBook";//重定向到我们的@RequestMapping("/allBook")
    }

//    跳转到修改书籍页面
    @RequestMapping("/toEditBookPage")
    public String toEditBookPage(int id,Model model){
        Books books = bookService.queryBookById(id);
        model.addAttribute("books",books);
        return "editBook";
    }

    @RequestMapping("/editBook")
    public String editBook(Books books){
        System.out.println("=======>"+books);
        bookService.updateBook(books);
        return "redirect:/book/allBook";//重定向到我们的@RequestMapping("/allBook")
    }

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

    @RequestMapping("/queryBook")
    public String queryBook(String queryBookName,Model model){
        Books books = bookService.queryBookByName(queryBookName);
        List<Books> list = new ArrayList<Books>();
        list.add(books);
        if(books==null){
            list = bookService.queryAllBook();
            model.addAttribute("error","未查到");
        }
        model.addAttribute("list",list);
        return "allBook";
    }
}

② 测试查询书籍功能

· 发现错误
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-j8xKlggW-1689059857746)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20210602173809613.png)]

· 修改方法,可以看到WEB-INF下面只有一个classes文件,没有lib文件夹

SSM框架最新整合保姆级教程(IDEA版)_第6张图片

· 把原来的这个books:war exploded叉掉,新建一个即可
SSM框架最新整合保姆级教程(IDEA版)_第7张图片

· 又发现错误
SSM框架最新整合保姆级教程(IDEA版)_第8张图片

· 检查发现少了一个依赖

<dependency>      
	<groupId>org.aspectjgroupId>      
	<artifactId>aspectjweaverartifactId>      
	<version>1.8.13version>
dependency>

③ 测试成功

Preparing: SELECT * from ssmbuild.books
Parameters:
< Columns: bookID, bookName, bookCounts, detail
< Row: 1, Java, 77, 从入门到放弃
< Row: 2, MySQL, 101, 从删库到跑路
< Row: 3, Linux, 5, 从进门到进牢哈哈哈哈
< Row: 5, 数据结构, 99, C语言版
< Row: 6, C#程序设计实用教程, 88, 机械工业出版社
< Row: 7, C程序设计, 36, 清华大学出版社
< Total: 6

SSM框架最新整合保姆级教程(IDEA版)_第9张图片

2、添加书籍

① 跳转到增加书籍页面

//    跳转到增加书籍页面    
@RequestMapping("/toAddBookPage")    
public String toAddPaper(){        
	return "addBook";    
}

② 编写增加书籍页面

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2021/6/3 0012
  Time: 23:35
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>增加书籍页面title>
    <link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
head>
<body>
<div class="container">
    <div class="row clearfix">
        <div class="col-md-4 column">
            <div class="page-header">
                <div class="alert alert-info" role="alert">
                    <h1>增加书籍页面h1>
                div>
            div>
            <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="btn btn-primary" value="添加">
                div>
            form>
        div>
    div>
div>
body>
html>

③ 进行书籍的添加

//    进行添加书籍
    @RequestMapping("/addBook")
    public String addBook(Books books){
        System.out.println("=======>"+books);
        bookService.addBook(books);
        return "redirect:/book/allBook";//重定向到我们的@RequestMapping("/allBook")
    }

3、修改书籍信息

① 跳转到修改书籍页面

//    跳转到修改书籍页面
    @RequestMapping("/toEditBookPage")
    public String toEditBookPage(int id,Model model){
        Books books = bookService.queryBookById(id);
        model.addAttribute("books",books);
        return "editBook";
    }

② 修改书籍页面

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2021/6/3 0012
  Time: 23:35
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>修改书籍页面title>
    <link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
head>
<body>
<div class="container">
    <div class="row clearfix">
        <div class="col-md-4 column">
            <div class="page-header">
                <div class="alert alert-danger" role="alert">
                    <h1>修改书籍页面h1>
                div>
            div>
            <form action="${pageContext.request.contextPath}/book/editBook" method="post">
                <input type="hidden" name="bookID" value="${books.bookID}">
                <div class="form-group">
                    <label>书籍名称label>
                    <input type="text" class="form-control" name="bookName" value="${books.bookName}" required>
                div>
                <div class="form-group">
                    <label>书籍数量label>
                    <input type="text" class="form-control" name="bookCounts" value="${books.bookCounts}" required>
                div>
                <div class="form-group">
                    <label>书籍描述label>
                    <input type="text" class="form-control" name="detail" value="${books.detail}" required>
                div>
                <div class="form-group">
                    <input type="submit" class="btn btn-danger" value="修改">
                div>
            form>
        div>
    div>
div>
body>
html>

③ 进行书籍信息修改

@RequestMapping("/editBook")
    public String editBook(Books books){
        System.out.println("=======>"+books);
        bookService.updateBook(books);
        return "redirect:/book/allBook";//重定向到我们的@RequestMapping("/allBook")
    }
          <input type="text" class="form-control" name="bookCounts" value="${books.bookCounts}" required>
                div>
                <div class="form-group">
                    <label>书籍描述label>
                    <input type="text" class="form-control" name="detail" value="${books.detail}" required>
                div>
                <div class="form-group">
                    <input type="submit" class="btn btn-danger" value="修改">
                div>
            form>
        div>
    div>
div>
body>
html>

③ 进行书籍信息修改

@RequestMapping("/editBook")
    public String editBook(Books books){
        System.out.println("=======>"+books);
        bookService.updateBook(books);
        return "redirect:/book/allBook";//重定向到我们的@RequestMapping("/allBook")
    }

你可能感兴趣的:(SpringBoot,java,SSM,spring)