手机版
你好,游客 登录 注册
背景:
阅读新闻

SpringMVC+Spring+MyBatis 整合与图片上传简单示例

[日期:2018-05-02] 来源:Linux社区  作者:gdwkong [字体: ]

一、思路:

(一) Dao层:

1、 SqlMapConfig.xml,空文件即可。需要文件头。
2、 applicationContext_dao.xml。

a) 数据库连接池
b) SqlSessionFactory对象,需要spring和mybatis整合包下的。
c) 配置mapper文件扫描器。

(二)Service层:

1、applicationContext_service.xml包扫描器,扫描@service注解的类。
2、applicationContext_trans.xml配置事务。

(三)Controller层:

Springmvc.xml
1、包扫描器,扫描@Controller注解的类。
2、配置注解驱动。
3、视图解析器。

(四)web.xml

1. 配置spring容量监听器
2. 配置前端控制器

二、构建项目

(一)构建maven项目,添加依赖

<?xml version="1.0" encoding="UTF-8"?>

<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.0</modelVersion>

  <groupId>com.cenobitor</groupId>
  <artifactId>ssm_template</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>ssm_template Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <!--设置编译的版本使用1.8版本-->
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <!-- 和设置编译插件是一样的效果-->
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>


    <junit.version>4.12</junit.version>
    <spring.version>4.3.10.RELEASE</spring.version>
    <servlet-api.version>2.5</servlet-api.version>
    <mybatis.version>3.2.8</mybatis.version>
    <mybatis.spring.version>1.2.2</mybatis.spring.version>
    <pagehelper.version>4.0.0</pagehelper.version>
    <Javassist.version>3.11.0.GA</javassist.version>
    <mysql.version>5.1.32</mysql.version>
    <druid.version>1.0.9</druid.version>
    <commons-fileupload.version>1.3.1</commons-fileupload.version>
    <commons-lang3.version>3.3.2</commons-lang3.version>
    <commons-io.version>1.3.2</commons-io.version>
    <jackson.version>2.8.9</jackson.version>
    <jstl.version>1.2</jstl.version>
    <jsp-api.version>2.0</jsp-api.version>
    <fastjson.version>1.2.28</fastjson.version>
    <slf4j.version>1.6.4</slf4j.version>
    <lombok.version>1.16.20</lombok.version>
  </properties>

  <dependencies>
    <!-- Apache工具组件 -->
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-lang3</artifactId>
      <version>${commons-lang3.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-io</artifactId>
      <version>${commons-io.version}</version>
    </dependency>
    <!-- Jackson Json处理工具包 -->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>${jackson.version}</version>
    </dependency>

    <!--alibaba json处理工具包-->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>${fastjson.version}</version>
    </dependency>
    <!-- 日志处理 -->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>${slf4j.version}</version>
    </dependency>
    <!--实体类get/set注解-->
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>${lombok.version}</version>
      <scope>provided</scope>
    </dependency>
    <!--单元测试-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>${junit.version}</version>
    </dependency>

    <!-- Spring -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aspects</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jms</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context-support</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <!--jsp相关-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>${servlet-api.version}</version>
      <scope>provided</scope>
    </dependency>
    <!-- 文件上传组件 -->
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>${commons-fileupload.version}</version>
    </dependency>
    <!-- Mybatis -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>${mybatis.version}</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>${mybatis.spring.version}</version>
    </dependency>
    <!--MyBatis分页插件-->
    <dependency>
      <groupId>com.github.pagehelper</groupId>
      <artifactId>pagehelper</artifactId>
      <version>${pagehelper.version}</version>
    </dependency>
    <!-- MySql -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>${mysql.version}</version>
    </dependency>
    <!-- 连接池 -->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>${druid.version}</version>
    </dependency>

  </dependencies>

  <build>
    <finalName>ssm_template</finalName>
    <!--设置mapper.xml配置与mapper类处于同个包下,否则编译时候无法生成到同一目录下,会报BindingException-->
    <resources>
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.xml</include>
        </includes>
      </resource>
      <resource>
        <directory>src/main/resources</directory>
      </resource>
    </resources>

    <plugins>
      <!-- 配置Tomcat7插件 -->
      <plugin>
        <groupId>org.apache.tomcat.maven</groupId>
        <artifactId>tomcat7-maven-plugin</artifactId>
        <version>2.2</version>
        <configuration>
          <uriEncoding>UTF-8</uriEncoding>
        </configuration>
      </plugin>
      <!-- 配置打包时跳过测试  -->
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>2.12.4</version>
      </plugin>
    </plugins>
  </build>

</project>

(二)applicationContext.xml的配置

1、applicationContext_dao.xml(数据库)的配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:context="http://www.springframework.org/schema/context"
      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-4.0.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-4.0.xsd">


    <!-- dao层 数据库连接部分-->
    <!-- 加载配置文件 -->
    <context:property-placeholder location="classpath:properties/db.properties" />

    <!-- 数据库连接池 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driver}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}"/>
        <!-- 连接池的最大数据库连接数 -->
        <property name="maxActive" value="10" />
        <!-- 最大空闲数 -->
        <property name="maxIdle" value="5" />
    </bean>
    <!-- 配置SqlSessionFactory单例 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 配置数据源 -->
        <property name="dataSource" ref="dataSource" />
        <!-- 加载mybatis核心配置文件 -->
        <property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml" />
        <!--别名包扫描-->
        <property name="typeAliasesPackage" value="com.cenobitor.pojo"/>

    </bean>
    <!-- 动态代理dao配置,包扫描(推荐方式)-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 支持多包配置,多包时用,或者;分隔 -->
        <property name="basePackage" value="com.cenobitor.mapper" />
    </bean>
</beans>

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm?characterEncoding=utf-8
jdbc.username=root
jdbc.password=

2、applicationContext_service.xml(service扫描)的配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:context="http://www.springframework.org/schema/context"
      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-4.0.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <!-- 配置service扫描 -->
    <context:component-scan base-package="com.cenobitor.service"/>

</beans>

3、applicationContext_trans.xml(事务)的配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:aop="http://www.springframework.org/schema/aop"
      xmlns:tx="http://www.springframework.org/schema/tx"
      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-4.0.xsd
            http://www.springframework.org/schema/aop
            http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
            http://www.springframework.org/schema/tx
            http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

    <!-- 事务管理器 -->
    <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="save*" propagation="REQUIRED"/>
            <tx:method name="insert*" propagation="REQUIRED"/>
            <tx:method name="delete*" propagation="REQUIRED"/>
            <tx:method name="update*" propagation="REQUIRED"/>
            <tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
            <tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
            <tx:method name="query*" propagation="SUPPORTS" read-only="true"/>
        </tx:attributes>
    </tx:advice>

    <!-- 切面 -->
    <aop:config>
        <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.cenobitor.service.*.*(..))"/>
    </aop:config>
</beans>

(三)web.xml 的配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns="http://java.sun.com/xml/ns/javaee"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
            http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
        id="WebApp_ID" version="2.5">
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    <!-- spring配置文件路径 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:/spring/applicationContext_*.xml</param-value>
    </context-param>

    <!-- 解决post乱码问题 -->
    <filter>
        <filter-name>encoding</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <!-- 设置编码参是UTF8 -->
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encoding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- 配置SpringMvc 前端控制器 -->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--指定SpringMvc 配置文件-->
        <!-- springmvc的配置文件默认路径是 /WEB-INF/${servlet-name}_servlet.xml -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring/springmvc.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>*.action</url-pattern>
    </servlet-mapping>

</web-app>

(四)MyBatis的配置文件,实体类和对应的映射文件由通用Mapper生成,在此采用手动创建方式(详细见下文件图片上传案例)

此处建文件,配置mybatis分页插件即可:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <plugins>
        <!-- com.github.pagehelper为PageHelper类所在包名 -->
        <plugin interceptor="com.github.pagehelper.PageHelper">
            <!-- 设置数据库类型 Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六种数据库-->
            <property name="dialect" value="mysql"/>
        </plugin>
    </plugins>

</configuration>

(五)springMVC的配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:context="http://www.springframework.org/schema/context"
      xmlns:mvc="http://www.springframework.org/schema/mvc"
      xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
              http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
              http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <!--配置controller扫描-->
    <context:component-scan base-package="com.cenobitor.controller"/>

    <!-- 注解驱动 -->
    <mvc:annotation-driven/>

    <!--&lt;!&ndash;自定义转换器配置模板&ndash;&gt;
    &lt;!&ndash;使用自定义转换器&ndash;&gt;
    <mvc:annotation-driven conversion-service="myConverter" />

    &lt;!&ndash; 定义转换器 &ndash;&gt;
    <bean id="myConverter" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
        <property name="converters">
            <set>
                &lt;!&ndash; 日期转换器 &ndash;&gt;
                <bean class="com.cenobitor.converter.DateConverter" />
            </set>
        </property>
    </bean>-->

    <!-- 配置多媒体解析器,用于上传等的配置,如果是纯文本则无需配置 -->
    <!-- 注意:这里的id只能是multipartResolver -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 限定文件最大上传大小为:8MB -->
        <property name="maxUploadSize" value="8388608" />
    </bean>

    <!--可减少简写路径名-->
    <!--<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        &lt;!&ndash; 配置逻辑视图的前缀 &ndash;&gt;
        <property name="prefix" value="/WEB-INF/views/"/>
        <property name="suffix" value=".jsp"/>
    </bean>-->
</beans>

(六)log4j配置文件,位于resources包下:

log4j.rootLogger=DEBUG, Console
#Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
log4j.logger.java.sql.ResultSet=INFO
log4j.logger.org.apache=INFO
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG

三、 图片上传预览

1、创建表以及pojo

CREATE TABLE `pic` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `url` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8

 

package com.cenobitor.pojo;

import lombok.Data;

/**
 * @Description:
 * @Date: Created in 11:05 AM 2018/5/1
 * @Author: Cenobitor
 * @Modified By:
 */
@Data
public class Pic {

    private Integer id;
    private String name;
    private String url;

    public Pic(String name, String url) {
        this.name = name;
        this.url = url;
    }

    public Pic() {
    }
}

2、设置文件存储的虚拟路径

2、创建上传页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>上传图片</title>
</head>
<body>
    <form id="upload" action="/uploadpic.action" method="post" enctype="multipart/form-data">
        <input type="file"  name="picFile"/>
        <br/>
        <input type="submit" value="提交"/>
    </form>
</body>
</html>

3、创建Controller类

package com.cenobitor.controller;

import com.cenobitor.service.UploadFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class UploadFileController {

    @Autowired
    private UploadFileService uploadFileService;

    //图片上传用MultipartFile接收文件,其中参数名要表单中的文件名一致
    @RequestMapping("/uploadpic")
    public String uploadPic(MultipartFile picFile) throws Exception {
        String picUrl = uploadFileService.UploadPic(picFile);
        if (picUrl == null){
            return "redirect:error.html";
        }
        //重定向预览图片
        return "redirect:"+picUrl;
    }
}

4、创建service层

public interface UploadFileService {
    public String UploadPic(MultipartFile picFile);
 }

 

package com.cenobitor.service.impl;

import com.cenobitor.mapper.PicMapper;
import com.cenobitor.pojo.Pic;
import com.cenobitor.service.UploadFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Service
@Transactional
public class UploadFileServiceImpl implements UploadFileService {

    @Autowired
    private PicMapper picMapper;

    @Override
    public String UploadPic(MultipartFile picFile) {
        try {
            // 图片新名字
            String name = UUID.randomUUID().toString();
            // 图片原名字
            String oldName = picFile.getOriginalFilename();
            // 后缀名
            String exeName = oldName.substring(oldName.lastIndexOf("."));
            //保存图片路径为绝对路径
            File pic = new File("/Users/Shared/jpg/" + name + exeName);
            // 保存图片到本地磁盘
            picFile.transferTo(pic);

            //保存数据到数据库中
            picMapper.add(new Pic(name,"../jpg/"+name+exeName));
            return "/jpg/"+name+exeName;

        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}

5、创建dao层(mapper层)

package com.cenobitor.mapper;

import com.cenobitor.pojo.Pic;

public interface PicMapper {
    //添加图片
    int add(Pic pic);

}

 

<?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">
<!--namespace为对应的mapper类的全路径名-->
<mapper namespace="com.cenobitor.mapper.PicMapper">

    <!-- 添加 -->
    <!-- id为对应的方法名, parameterType为入参的全路径名-->
    <insert id="add" parameterType = "com.cenobitor.pojo.Pic">
        insert into
        pic(name,url)
        values
        (#{name},#{url});
    </insert>

</mapper>

6、项目的目录结构

7、效果

本文永久更新链接地址https://www.linuxidc.com/Linux/2018-05/152167.htm

linux
相关资讯       Spring  MyBatis  SpringMVC 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款