通俗易懂-SSM三大框架整合案例(SpringMVC+Spring+Mybatis)

前言:
学习B站UP狂神说视频笔记整理视频链接
相关代码已经上传至码云:码云链接

前期准备

项目介绍

demo项目是一个简单的图书管理系统,主要功能为表单数据的增删改查
Web端使用JSP+Bootstrap
后端使用SpringMVC+Spring+Mybatis

使用技术:

技术 说明
Junit 单元测试
MyBatis ORM框架
SpringMVC MVC框架
Lombok 简化对象封装工具
c3p0 数据库连接池
Bootstrap 前端开源工具包

项目预览:

展示页
通俗易懂-SSM三大框架整合案例(SpringMVC+Spring+Mybatis)_第1张图片

新增页
通俗易懂-SSM三大框架整合案例(SpringMVC+Spring+Mybatis)_第2张图片
修改页
通俗易懂-SSM三大框架整合案例(SpringMVC+Spring+Mybatis)_第3张图片

环境要求

IDEA
MySQL 5.7.19
Tomcat 9
Maven 3.6

数据库环境

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

创建Maven项目导入依赖

通俗易懂-SSM三大框架整合案例(SpringMVC+Spring+Mybatis)_第4张图片
在pom.xml中导入依赖

<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>
            <scope>providedscope>
        dependency>
    dependencies>

处理Maven资源过滤问题

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

将项目变成一个Web项目
通俗易懂-SSM三大框架整合案例(SpringMVC+Spring+Mybatis)_第5张图片

通俗易懂-SSM三大框架整合案例(SpringMVC+Spring+Mybatis)_第6张图片

建立基本结构和配置框架

通俗易懂-SSM三大框架整合案例(SpringMVC+Spring+Mybatis)_第7张图片

mybatis-config.xml



<configuration>
    
    
configuration>

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

database.properties

jdbc.driver=com.mysql.jdbc.Driver
#使用Mybatis8.0+ 必须要设置时区serverTimezone=UTC
jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=true&useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=123456

Mybatis层编写

编写Mybatis原生配置文件-mybatis-config.xml



<configuration>
    


    
    <settings>
        
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    settings>

    
    <typeAliases>
        <package name="com.tony.pojo"/>
    typeAliases>
    
configuration>

创建数据库实体类-Books

/**
 * 数据库实体类
 * @Author Tu_Yooo
 * @create 2021/4/4 10:53
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Books {
     
    private int bookID;
    private String bookName;
    private int bookCounts;
    private String detail;
}

编写Mapper接口-BooksMapper

/**
 * 数据库dao层Mapper接口
 * @Author Tu_Yooo
 * @create 2021/4/4 10:54
 */
public interface BooksMapper {
     

    //增加一个Book
    int addBook(Books book);

    //根据id删除一个Book
    int deleteBookById(int id);

    //更新Book
    int updateBook(Books books);

    //根据id查询,返回一个Book
    Books queryBookById(int id);

    //如果不传参 则查询全部Book,返回list集合 如果传参 则查询具体内容
    List<Books> queryAllBook(String bookName);

}

编写Mapper接口映射文件-BooksMapper.xml





<mapper namespace="com.tony.dao.BooksMapper">

    
    <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=#{id}
    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="com.tony.pojo.Books">
        select * from ssmbuild.books where bookID=#{id}
    select>
    
    <select id="queryAllBook" parameterType="string" resultType="books">
         select * from ssmbuild.books
         <where>
             <if test="bookName != null">
                 bookName like concat('%',#{bookName},'%')
             if>
         where>
    select>
mapper>

编写Service层的接口和实现类

Service接口-BooksService

/**
 * Service层接口
 * @Author Tu_Yooo
 * @create 2021/4/4 11:05
 */
public interface BooksService {
     

    //增加一个Book
    int addBook(Books book);
    //根据id删除一个Book
    int deleteBookById(int id);
    //更新Book
    int updateBook(Books books);
    //根据id查询,返回一个Book
    Books queryBookById(int id);
    //如果不传参 则查询全部Book,返回list集合 如果传参 则查询具体内容
    List<Books> queryAllBook(String bookName);

}

Service接口实现类-BooksServiceImpl

/**
 * Service层接口实现类
 * @Author Tu_Yooo
 * @create 2021/4/4 11:06
 */
@Service
public class BooksServiceImpl implements BooksService{
     


    //调用dao层的操作,设置一个set接口,方便Spring管理
    @Autowired
    private BooksMapper bookMapper;

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

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

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

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

    @Override
    public List<Books> queryAllBook(String bookName) {
     
        List<Books> books = bookMapper.queryAllBook(bookName);
        if (books.size()==0){
      //判断是否查询到值 如果没查询到 则查全量
            books= bookMapper.queryAllBook(null);
        }
        return books;
    }
}

当前项目目录如下:
通俗易懂-SSM三大框架整合案例(SpringMVC+Spring+Mybatis)_第8张图片

Spring层编写

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

Spring整合Mybatis

创建与编写mybatis-spring.xml配置文件


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.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"/>
        
        <property name="mapperLocations" value="classpath:mapper/BooksMapper.xml"/>
    bean>

    
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    bean>

    
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        
        <property name="basePackage" value="com.tony.dao"/>
    bean>

beans>

Spring整合service

创建与编写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"
       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:component-scan base-package="com.tony.service"/>
    
    <context:annotation-config/>

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

beans>

SpringMVC层编写

Spring整合SpringMVC

编写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/>
    
    <context:component-scan base-package="com.tony.controller"/>
    
    
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver">
        
        <property name="prefix" value="/WEB-INF/jsp/"/>
        
        <property name="suffix" value=".jsp"/>
    bean>

beans>

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

汇总所有配置文件

编写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="mybatis-spring.xml"/>
    
    <import resource="spring-service.xml"/>
    
    <import resource="spring-mvc.xml"/>
beans>

当前项目结构目录如下:
通俗易懂-SSM三大框架整合案例(SpringMVC+Spring+Mybatis)_第9张图片

编写业务

页面相关

首页-index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>首页title>
    <style>
      h3 a{
      
        color: darkcyan;
        text-decoration: none;
        font-family: fantasy;
        font-size: 20px;
        text-decoration: none;
      }
      h3{
      
        width: 300px;
        height: 300px;
        margin: 0 auto;
        text-align: center;
        line-height: 300px;
        background: bisque;
        border-radius: 10px;
      }
      a:hover{
      
        color: steelblue;
        font-size: 30px;
      }
    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>
    <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>

    <div class="row">
        <div class="col-md-4 column">
            <a class="btn btn-primary" href="${pageContext.request.contextPath}/book/toAddBook">新增a>
        div>
        <div class="col-md-4 column">div>
        <div class="col-md-4 column">
            <%--查询书籍--%>
            <form  class="form-inline" action="${pageContext.request.contextPath}/book/queryBookName" method="post" style="float: right">
                <input type="text" name="queryBookName" class="form-control" placeholder="请输入要查询的书籍">
                <input type="submit" value="查询" class="btn btn-primary">
            form>
        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.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>

body>
html>

新增页-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">
        <div class="form-group">
            <lable>书籍名称:lable>
            <input type="text" name="bookName" class="form-control" required>
        div>
        <div class="form-group">
            <lable>书籍数量:lable>
            <input type="text" name="bookCounts" class="form-control" required>
        div>
        <div class="form-group">
            <lable>书籍详情:lable>
            <input type="text" name="detail" class="form-control" required>
        div>
        <div class="form-group">
            <input type="submit" value="添加">
        div>
    form>
div>

body>
html>

修改页-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">
        <div class="form-group">
            <lable>书籍id:lable>
            <input type="text" name="bookID" class="form-control" value="${Qbooks.bookID}" readonly>
        div>
        <div class="form-group">
            <lable>书籍名称:lable>
            <input type="text" name="bookName" class="form-control" value="${Qbooks.bookName}" required>
        div>
        <div class="form-group">
            <lable>书籍数量:lable>
            <input type="text" name="bookCounts" class="form-control" value="${Qbooks.bookCounts}" required>
        div>
        <div class="form-group">
            <lable>书籍详情:lable>
            <input type="text" name="detail" class="form-control" value="${Qbooks.detail}" required>
        div>
        <div class="form-group">
            <input type="submit" value="修改">
        div>
    form>
div>

body>
html>

Controller代码编写

编写BooksController

/**
 * Controller层
 * @Author Tu_Yooo
 * @create 2021/4/4 11:33
 */
@Controller
@RequestMapping("/book")
public class BooksController {
     

    //controller层调service层
    @Autowired
    private BooksService booksService;

    /**
     * 查询全部书籍
     * @param model
     * @return 返回书籍展示页面
     */
    @RequestMapping("/allBook")
    public String listall(Model model){
     
        List<Books> books = booksService.queryAllBook(null);
        model.addAttribute("list",books);
        return "allBook";
    }

    /**
     * 查询指定名字的书籍
     * @param queryBookName 要查询的书籍
     * @param model 封装查询到的数据
     * @return 返回页面 注意:此处不能使用重定向
     */
    @RequestMapping("/queryBookName")
    public String listall(String queryBookName,Model model){
     
        String trim = queryBookName.trim();
        List<Books> books = booksService.queryAllBook(trim);
        model.addAttribute("list",books);
        return "allBook";
    }

    /**
     * 新增页面
     * @return 跳转到新增书籍页面
     */
    @RequestMapping("/toAddBook")
    public String toaddBook(Model model){
     
        model.addAttribute("msg","成功跳转页面");
        return "addBook";
    }

    /**
     * 新增书籍数据
     * @param books 添加表单值
     * @return 重定向到查询页
     */
    @RequestMapping("/addBook")
    public String addBook(Books books){
     
        booksService.addBook(books);
        return "redirect:/book/allBook";
    }

    /**
     * 基于id查询对应数据 返回修改页面
     * @param id 修改数据的id
     * @param modle 封装书籍id对应的数据
     * @return 返回一个修改页面
     */
    @RequestMapping("/toUpdateBook")
    public String updateBook(int id,Model modle){
     
        Books books = booksService.queryBookById(id);
        modle.addAttribute("Qbooks",books);
        return "updateBook";
    }

    /**
     * 修改表单数据
     * @param books 修改数据
     * @return 重定向到查询页
     */
    @RequestMapping("/updateBook")
    public String updateBook(Books books){
     
        int i = booksService.updateBook(books);
        return "redirect:/book/allBook";
    }

    /**
     * 删除书籍
     * @param bookID 需要删除的书籍id
     * @return 重定向到查询页
     */
    @RequestMapping("/del/{bookID}")
    public String delBook(@PathVariable int bookID){
     
        booksService.deleteBookById(bookID);
        return "redirect:/book/allBook";
    }

}

测试运行

配置tomcat

通俗易懂-SSM三大框架整合案例(SpringMVC+Spring+Mybatis)_第10张图片

通俗易懂-SSM三大框架整合案例(SpringMVC+Spring+Mybatis)_第11张图片

发布项目

通俗易懂-SSM三大框架整合案例(SpringMVC+Spring+Mybatis)_第12张图片

扩展功能-文件上传

概述

文件上传是项目开发中最常见的功能之一 ,springMVC 可以很好的支持文件上传,但是SpringMVC上下文中默认没有装配MultipartResolver,因此默认情况下其不能处理文件上传工作。如果想使用Spring的文件上传功能,则需要在上下文中配置MultipartResolver。

CommonsMultipartFile 的 常用方法:

  1. String getOriginalFilename():获取上传文件的原名

  2. InputStream getInputStream():获取文件流

  3. void transferTo(File dest):将上传文件保存到一个目录文件中

前端要求

前端表单要求:为了能上传文件,必须将表单的method设置为POST,并将enctype设置为multipart/form-data。只有在这样的情况下,浏览器才会把用户选择的文件以二进制数据发送给服务器;

表单中的 enctype 属性做个详细的说明:

1.application/x-www=form-urlencoded:默认方式,只处理表单域中的 value 属性值,采用这种编码方式的表单会将表单域中的值处理成 URL 编码方式。
2.multipart/form-data:这种编码方式会以二进制流的方式来处理表单数据,这种编码方式会把文件域指定文件的内容也封装到请求参数中,不会对字符编码。
3.text/plain:除了把空格转换为 “+” 号外,其他字符都不做编码处理,这种方式适用直接通过表单发送邮件。

<form action="" enctype="multipart/form-data" method="post">
   <input type="file" name="file"/>
   <input type="submit">
form>

文件上传

通俗易懂-SSM三大框架整合案例(SpringMVC+Spring+Mybatis)_第13张图片

导入依赖

导入文件上传的jar包,commons-fileupload


<dependency>
   <groupId>commons-fileuploadgroupId>
   <artifactId>commons-fileuploadartifactId>
   <version>1.3.3version>
dependency>

<dependency>
   <groupId>javax.servletgroupId>
   <artifactId>javax.servlet-apiartifactId>
   <version>4.0.1version>
dependency>

修改新增页-addBook.jsp

添加表单代码

  <%--文件上传--%>
    <form action="${pageContext.request.contextPath}/file/upload" enctype="multipart/form-data" method="post">
        <div class="form-group">
            <input type="file" name="file"/>
            <span>${filename}span>
        div>
        <div class="form-group">
            <input type="submit" id="importForm" value="提交">
        div>
    form>

配置bean-multipartResolver

在mvc配置文件spring-mvc.xml配置bean
【注意!!!这个bena的id必须为:multipartResolver , 否则上传文件会报400的错误!在这里栽过坑,教训!】


<bean id="multipartResolver"  class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
   
   <property name="defaultEncoding" value="utf-8"/>
   
   <property name="maxUploadSize" value="10485760"/>
   <property name="maxInMemorySize" value="40960"/>
bean>

编写FileController

/**
 * 文件相关
 * @author Tu_Yooo
 * @Date 2021/4/8 9:56
 */
@Controller
@RequestMapping("/file")
public class FileController {
     

    //图片存储路径
    private String localDir="D:/Download/";

    /**
     * 文件上传
     * @param file 传输过来的图片文件
     * @param request 请求头
     * @return 回显是否成功
     */
    @RequestMapping("/upload")
    public String upload(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request, Model model){
     
        //获取文件名
        String filename = file.getOriginalFilename();
        //将图片名称转换成小写字母
        filename = filename.toLowerCase();
        //如果文件名为空直接返回到首页
        if("".equals(filename)){
     
            model.addAttribute("filename","文件名为空!");
            return "addBook";
        }
        System.out.println("上传文件名 : "+filename);
        //正则表达式校验 是否为图片
        if(!filename.matches("^.+\\.(png|jpg|gif)$")) {
     
            model.addAttribute("filename","请上传图片");
            return "addBook";
        }
        //校验是否为恶意程序
        try {
     
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
            int width = bufferedImage .getWidth();
            int height = bufferedImage.getHeight();
            if(width == 0 || height ==0){
       //说明 上传的不是图片,为恶意程序.
                model.addAttribute("filename","请上传图片");
                return "addBook";
            }
            //按照时间将目录进行划分 yyyy/MM/dd
            String deteDir = new SimpleDateFormat("yyyy/MM/dd/").format(new Date());
            String localFileDir  = localDir+deteDir;
            File file1 = new File(localFileDir);
            if(!file1.exists()) {
     //如果目录不存在则创建多级目录
                file1.mkdirs();
            }

            //动态生成文件名
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            //abc.jpg
            int index = filename.lastIndexOf(".");
            String fileType = filename.substring(index);//截取文件后缀
            String realFileName  = uuid + fileType;

            //文件上传
            String realFilePath = localFileDir + realFileName;
            File imageFile = new File(realFilePath);

            //通过CommonsMultipartFile的方法直接写文件
            file.transferTo(imageFile);
            model.addAttribute("filename",realFilePath);
            return "addBook";
        } catch (IOException e) {
     
            e.printStackTrace();
            model.addAttribute("filename","未知异常!");
            return "addBook";
        }

    }

}

常见问题解答

访问出现404

排查步骤:
1.查看jar依赖是否正确导入
2.如果jar包存在,显示无法输出,就在IDEA的项目发布中添加lib依赖!
3.重启Tomcat即可解决
在这里插入图片描述

通俗易懂-SSM三大框架整合案例(SpringMVC+Spring+Mybatis)_第14张图片
通俗易懂-SSM三大框架整合案例(SpringMVC+Spring+Mybatis)_第15张图片
通俗易懂-SSM三大框架整合案例(SpringMVC+Spring+Mybatis)_第16张图片
通俗易懂-SSM三大框架整合案例(SpringMVC+Spring+Mybatis)_第17张图片

ClassNotFoundException

在这里插入图片描述
原因:
lib目录下缺少相关依赖
通俗易懂-SSM三大框架整合案例(SpringMVC+Spring+Mybatis)_第18张图片
解决: 补全依赖,重启项目

你可能感兴趣的:(狂神说学习笔记,mybatis,spring,springmvc,java)