SpringMVC+Spring+MyBatis 整合与图片上传简单示例
一、思路:
(一) 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项目,添加依赖
1 <?xml version="1.0" encoding="UTF-8"?> 2 3 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 5 <modelVersion>4.0.0</modelVersion> 6 7 <groupId>com.cenobitor</groupId> 8 <artifactId>ssm_template</artifactId> 9 <version>1.0-SNAPSHOT</version> 10 <packaging>war</packaging> 11 12 <name>ssm_template Maven Webapp</name> 13 <!-- FIXME change it to the project's website --> 14 <url>http://www.example.com</url> 15 16 <properties> 17 <!--设置编译的版本使用1.8版本--> 18 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 19 <!-- 和设置编译插件是一样的效果--> 20 <maven.compiler.source>1.8</maven.compiler.source> 21 <maven.compiler.target>1.8</maven.compiler.target> 22 23 24 <junit.version>4.12</junit.version> 25 <spring.version>4.3.10.RELEASE</spring.version> 26 <servlet-api.version>2.5</servlet-api.version> 27 <mybatis.version>3.2.8</mybatis.version> 28 <mybatis.spring.version>1.2.2</mybatis.spring.version> 29 <pagehelper.version>4.0.0</pagehelper.version> 30 <javassist.version>3.11.0.GA</javassist.version> 31 <mysql.version>5.1.32</mysql.version> 32 <druid.version>1.0.9</druid.version> 33 <commons-fileupload.version>1.3.1</commons-fileupload.version> 34 <commons-lang3.version>3.3.2</commons-lang3.version> 35 <commons-io.version>1.3.2</commons-io.version> 36 <jackson.version>2.8.9</jackson.version> 37 <jstl.version>1.2</jstl.version> 38 <jsp-api.version>2.0</jsp-api.version> 39 <fastjson.version>1.2.28</fastjson.version> 40 <slf4j.version>1.6.4</slf4j.version> 41 <lombok.version>1.16.20</lombok.version> 42 </properties> 43 44 <dependencies> 45 <!-- Apache工具组件 --> 46 <dependency> 47 <groupId>org.apache.commons</groupId> 48 <artifactId>commons-lang3</artifactId> 49 <version>${commons-lang3.version}</version> 50 </dependency> 51 <dependency> 52 <groupId>org.apache.commons</groupId> 53 <artifactId>commons-io</artifactId> 54 <version>${commons-io.version}</version> 55 </dependency> 56 <!-- Jackson Json处理工具包 --> 57 <dependency> 58 <groupId>com.fasterxml.jackson.core</groupId> 59 <artifactId>jackson-databind</artifactId> 60 <version>${jackson.version}</version> 61 </dependency> 62 63 <!--alibaba json处理工具包--> 64 <dependency> 65 <groupId>com.alibaba</groupId> 66 <artifactId>fastjson</artifactId> 67 <version>${fastjson.version}</version> 68 </dependency> 69 <!-- 日志处理 --> 70 <dependency> 71 <groupId>org.slf4j</groupId> 72 <artifactId>slf4j-log4j12</artifactId> 73 <version>${slf4j.version}</version> 74 </dependency> 75 <!--实体类get/set注解--> 76 <dependency> 77 <groupId>org.projectlombok</groupId> 78 <artifactId>lombok</artifactId> 79 <version>${lombok.version}</version> 80 <scope>provided</scope> 81 </dependency> 82 <!--单元测试--> 83 <dependency> 84 <groupId>junit</groupId> 85 <artifactId>junit</artifactId> 86 <version>${junit.version}</version> 87 </dependency> 88 89 <!-- Spring --> 90 <dependency> 91 <groupId>org.springframework</groupId> 92 <artifactId>spring-context</artifactId> 93 <version>${spring.version}</version> 94 </dependency> 95 <dependency> 96 <groupId>org.springframework</groupId> 97 <artifactId>spring-beans</artifactId> 98 <version>${spring.version}</version> 99 </dependency> 100 <dependency> 101 <groupId>org.springframework</groupId> 102 <artifactId>spring-webmvc</artifactId> 103 <version>${spring.version}</version> 104 </dependency> 105 <dependency> 106 <groupId>org.springframework</groupId> 107 <artifactId>spring-jdbc</artifactId> 108 <version>${spring.version}</version> 109 </dependency> 110 <dependency> 111 <groupId>org.springframework</groupId> 112 <artifactId>spring-aspects</artifactId> 113 <version>${spring.version}</version> 114 </dependency> 115 <dependency> 116 <groupId>org.springframework</groupId> 117 <artifactId>spring-jms</artifactId> 118 <version>${spring.version}</version> 119 </dependency> 120 <dependency> 121 <groupId>org.springframework</groupId> 122 <artifactId>spring-context-support</artifactId> 123 <version>${spring.version}</version> 124 </dependency> 125 <dependency> 126 <groupId>org.springframework</groupId> 127 <artifactId>spring-test</artifactId> 128 <version>${spring.version}</version> 129 </dependency> 130 <!--jsp相关--> 131 <dependency> 132 <groupId>javax.servlet</groupId> 133 <artifactId>servlet-api</artifactId> 134 <version>${servlet-api.version}</version> 135 <scope>provided</scope> 136 </dependency> 137 <!-- 文件上传组件 --> 138 <dependency> 139 <groupId>commons-fileupload</groupId> 140 <artifactId>commons-fileupload</artifactId> 141 <version>${commons-fileupload.version}</version> 142 </dependency> 143 <!-- Mybatis --> 144 <dependency> 145 <groupId>org.mybatis</groupId> 146 <artifactId>mybatis</artifactId> 147 <version>${mybatis.version}</version> 148 </dependency> 149 <dependency> 150 <groupId>org.mybatis</groupId> 151 <artifactId>mybatis-spring</artifactId> 152 <version>${mybatis.spring.version}</version> 153 </dependency> 154 <!--MyBatis分页插件--> 155 <dependency> 156 <groupId>com.github.pagehelper</groupId> 157 <artifactId>pagehelper</artifactId> 158 <version>${pagehelper.version}</version> 159 </dependency> 160 <!-- MySql --> 161 <dependency> 162 <groupId>mysql</groupId> 163 <artifactId>mysql-connector-java</artifactId> 164 <version>${mysql.version}</version> 165 </dependency> 166 <!-- 连接池 --> 167 <dependency> 168 <groupId>com.alibaba</groupId> 169 <artifactId>druid</artifactId> 170 <version>${druid.version}</version> 171 </dependency> 172 173 </dependencies> 174 175 <build> 176 <finalName>ssm_template</finalName> 177 <!--设置mapper.xml配置与mapper类处于同个包下,否则编译时候无法生成到同一目录下,会报BindingException--> 178 <resources> 179 <resource> 180 <directory>src/main/java</directory> 181 <includes> 182 <include>**/*.xml</include> 183 </includes> 184 </resource> 185 <resource> 186 <directory>src/main/resources</directory> 187 </resource> 188 </resources> 189 190 <plugins> 191 <!-- 配置Tomcat7插件 --> 192 <plugin> 193 <groupId>org.apache.tomcat.maven</groupId> 194 <artifactId>tomcat7-maven-plugin</artifactId> 195 <version>2.2</version> 196 <configuration> 197 <uriEncoding>UTF-8</uriEncoding> 198 </configuration> 199 </plugin> 200 <!-- 配置打包时跳过测试 --> 201 <plugin> 202 <groupId>org.apache.maven.plugins</groupId> 203 <artifactId>maven-surefire-plugin</artifactId> 204 <version>2.12.4</version> 205 </plugin> 206 </plugins> 207 </build> 208 209 </project>
(二)applicationContext.xml的配置
1、applicationContext_dao.xml(数据库)的配置
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:context="http://www.springframework.org/schema/context" 4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 5 xsi:schemaLocation="http://www.springframework.org/schema/beans 6 http://www.springframework.org/schema/beans/spring-beans-4.0.xsd 7 http://www.springframework.org/schema/context 8 http://www.springframework.org/schema/context/spring-context-4.0.xsd"> 9 10 11 <!-- dao层 数据库连接部分--> 12 <!-- 加载配置文件 --> 13 <context:property-placeholder location="classpath:properties/db.properties" /> 14 15 <!-- 数据库连接池 --> 16 <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close"> 17 <property name="driverClassName" value="${jdbc.driver}" /> 18 <property name="url" value="${jdbc.url}" /> 19 <property name="username" value="${jdbc.username}" /> 20 <property name="password" value="${jdbc.password}"/> 21 <!-- 连接池的最大数据库连接数 --> 22 <property name="maxActive" value="10" /> 23 <!-- 最大空闲数 --> 24 <property name="maxIdle" value="5" /> 25 </bean> 26 <!-- 配置SqlSessionFactory单例 --> 27 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> 28 <!-- 配置数据源 --> 29 <property name="dataSource" ref="dataSource" /> 30 <!-- 加载mybatis核心配置文件 --> 31 <property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml" /> 32 <!--别名包扫描--> 33 <property name="typeAliasesPackage" value="com.cenobitor.pojo"/> 34 35 </bean> 36 <!-- 动态代理dao配置,包扫描(推荐方式)--> 37 <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> 38 <!-- 支持多包配置,多包时用,或者;分隔 --> 39 <property name="basePackage" value="com.cenobitor.mapper" /> 40 </bean> 41 </beans>
1 jdbc.driver=com.mysql.jdbc.Driver 2 jdbc.url=jdbc:mysql://localhost:3306/ssm?characterEncoding=utf-8 3 jdbc.username=root 4 jdbc.password=
2、applicationContext_service.xml(service扫描)的配置
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:context="http://www.springframework.org/schema/context" 4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 5 xsi:schemaLocation="http://www.springframework.org/schema/beans 6 http://www.springframework.org/schema/beans/spring-beans-4.0.xsd 7 http://www.springframework.org/schema/context 8 http://www.springframework.org/schema/context/spring-context-4.0.xsd"> 9 10 <!-- 配置service扫描 --> 11 <context:component-scan base-package="com.cenobitor.service"/> 12 13 </beans>
3、applicationContext_trans.xml(事务)的配置
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:aop="http://www.springframework.org/schema/aop" 4 xmlns:tx="http://www.springframework.org/schema/tx" 5 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 6 xsi:schemaLocation="http://www.springframework.org/schema/beans 7 http://www.springframework.org/schema/beans/spring-beans-4.0.xsd 8 http://www.springframework.org/schema/aop 9 http://www.springframework.org/schema/aop/spring-aop-4.0.xsd 10 http://www.springframework.org/schema/tx 11 http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"> 12 13 <!-- 事务管理器 --> 14 <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> 15 <!--数据源--> 16 <property name="dataSource" ref="dataSource"/> 17 </bean> 18 <!-- 通知 --> 19 <tx:advice id="txAdvice" transaction-manager="transactionManager"> 20 <tx:attributes> 21 <tx:method name="save*" propagation="REQUIRED"/> 22 <tx:method name="insert*" propagation="REQUIRED"/> 23 <tx:method name="delete*" propagation="REQUIRED"/> 24 <tx:method name="update*" propagation="REQUIRED"/> 25 <tx:method name="find*" propagation="SUPPORTS" read-only="true"/> 26 <tx:method name="get*" propagation="SUPPORTS" read-only="true"/> 27 <tx:method name="query*" propagation="SUPPORTS" read-only="true"/> 28 </tx:attributes> 29 </tx:advice> 30 31 <!-- 切面 --> 32 <aop:config> 33 <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.cenobitor.service.*.*(..))"/> 34 </aop:config> 35 </beans>
(三)web.xml 的配置
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xmlns="http://java.sun.com/xml/ns/javaee" 4 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 5 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 6 id="WebApp_ID" version="2.5"> 7 <welcome-file-list> 8 <welcome-file>index.jsp</welcome-file> 9 </welcome-file-list> 10 11 <!-- spring配置文件路径 --> 12 <context-param> 13 <param-name>contextConfigLocation</param-name> 14 <param-value>classpath:/spring/applicationContext_*.xml</param-value> 15 </context-param> 16 17 <!-- 解决post乱码问题 --> 18 <filter> 19 <filter-name>encoding</filter-name> 20 <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> 21 <!-- 设置编码参是UTF8 --> 22 <init-param> 23 <param-name>encoding</param-name> 24 <param-value>UTF-8</param-value> 25 </init-param> 26 </filter> 27 <filter-mapping> 28 <filter-name>encoding</filter-name> 29 <url-pattern>/*</url-pattern> 30 </filter-mapping> 31 32 <listener> 33 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 34 </listener> 35 36 <!-- 配置SpringMvc 前端控制器 --> 37 <servlet> 38 <servlet-name>springmvc</servlet-name> 39 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 40 <!--指定SpringMvc 配置文件--> 41 <!-- springmvc的配置文件默认路径是 /WEB-INF/${servlet-name}_servlet.xml --> 42 <init-param> 43 <param-name>contextConfigLocation</param-name> 44 <param-value>classpath:spring/springmvc.xml</param-value> 45 </init-param> 46 </servlet> 47 <servlet-mapping> 48 <servlet-name>springmvc</servlet-name> 49 <url-pattern>*.action</url-pattern> 50 </servlet-mapping> 51 52 </web-app>
(四)MyBatis的配置文件,实体类和对应的映射文件由通用Mapper生成,在此采用手动创建方式(详细见下文件图片上传案例)
此处建文件,配置mybatis分页插件即可:
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE configuration 3 PUBLIC "-//mybatis.org//DTD Config 3.0//EN" 4 "http://mybatis.org/dtd/mybatis-3-config.dtd"> 5 <configuration> 6 <plugins> 7 <!-- com.github.pagehelper为PageHelper类所在包名 --> 8 <plugin interceptor="com.github.pagehelper.PageHelper"> 9 <!-- 设置数据库类型 Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六种数据库--> 10 <property name="dialect" value="mysql"/> 11 </plugin> 12 </plugins> 13 14 </configuration>
(五)springMVC的配置
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xmlns:mvc="http://www.springframework.org/schema/mvc" 6 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd 7 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd 8 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> 9 10 <!--配置controller扫描--> 11 <context:component-scan base-package="com.cenobitor.controller"/> 12 13 <!-- 注解驱动 --> 14 <mvc:annotation-driven/> 15 16 <!--<!–自定义转换器配置模板–> 17 <!–使用自定义转换器–> 18 <mvc:annotation-driven conversion-service="myConverter" /> 19 20 <!– 定义转换器 –> 21 <bean id="myConverter" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> 22 <property name="converters"> 23 <set> 24 <!– 日期转换器 –> 25 <bean class="com.cenobitor.converter.DateConverter" /> 26 </set> 27 </property> 28 </bean>--> 29 30 <!-- 配置多媒体解析器,用于上传等的配置,如果是纯文本则无需配置 --> 31 <!-- 注意:这里的id只能是multipartResolver --> 32 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 33 <!-- 限定文件最大上传大小为:8MB --> 34 <property name="maxUploadSize" value="8388608" /> 35 </bean> 36 37 <!--可减少简写路径名--> 38 <!--<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 39 <!– 配置逻辑视图的前缀 –> 40 <property name="prefix" value="/WEB-INF/views/"/> 41 <property name="suffix" value=".jsp"/> 42 </bean>--> 43 </beans>
(六)log4j配置文件,位于resources包下:
1 log4j.rootLogger=DEBUG, Console 2 #Console 3 log4j.appender.Console=org.apache.log4j.ConsoleAppender 4 log4j.appender.Console.layout=org.apache.log4j.PatternLayout 5 log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n 6 log4j.logger.java.sql.ResultSet=INFO 7 log4j.logger.org.apache=INFO 8 log4j.logger.java.sql.Connection=DEBUG 9 log4j.logger.java.sql.Statement=DEBUG 10 log4j.logger.java.sql.PreparedStatement=DEBUG
三、 图片上传预览
1、创建表以及pojo
1 CREATE TABLE `pic` ( 2 `id` int(11) NOT NULL AUTO_INCREMENT, 3 `name` varchar(255) DEFAULT NULL, 4 `url` varchar(255) DEFAULT NULL, 5 PRIMARY KEY (`id`) 6 ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8
1 package com.cenobitor.pojo; 2 3 import lombok.Data; 4 5 /** 6 * @Description: 7 * @Date: Created in 11:05 AM 2018/5/1 8 * @Author: Cenobitor 9 * @Modified By: 10 */ 11 @Data 12 public class Pic { 13 14 private Integer id; 15 private String name; 16 private String url; 17 18 public Pic(String name, String url) { 19 this.name = name; 20 this.url = url; 21 } 22 23 public Pic() { 24 } 25 }
2、设置文件存储的虚拟路径
2、创建上传页面
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>上传图片</title> 6 </head> 7 <body> 8 <form id="upload" action="/uploadpic.action" method="post" enctype="multipart/form-data"> 9 <input type="file" name="picFile"/> 10 <br/> 11 <input type="submit" value="提交"/> 12 </form> 13 </body> 14 </html>
3、创建Controller类
1 package com.cenobitor.controller; 2 3 import com.cenobitor.service.UploadFileService; 4 import org.springframework.beans.factory.annotation.Autowired; 5 import org.springframework.stereotype.Controller; 6 import org.springframework.web.bind.annotation.*; 7 import org.springframework.web.multipart.MultipartFile; 8 9 @Controller 10 public class UploadFileController { 11 12 @Autowired 13 private UploadFileService uploadFileService; 14 15 //图片上传用MultipartFile接收文件,其中参数名要表单中的文件名一致 16 @RequestMapping("/uploadpic") 17 public String uploadPic(MultipartFile picFile) throws Exception { 18 String picUrl = uploadFileService.UploadPic(picFile); 19 if (picUrl == null){ 20 return "redirect:error.html"; 21 } 22 //重定向预览图片 23 return "redirect:"+picUrl; 24 } 25 }
4、创建service层
1 public interface UploadFileService { 2 public String UploadPic(MultipartFile picFile); 3 }
1 package com.cenobitor.service.impl; 2 3 import com.cenobitor.mapper.PicMapper; 4 import com.cenobitor.pojo.Pic; 5 import com.cenobitor.service.UploadFileService; 6 import org.springframework.beans.factory.annotation.Autowired; 7 import org.springframework.stereotype.Service; 8 import org.springframework.transaction.annotation.Transactional; 9 import org.springframework.web.multipart.MultipartFile; 10 import java.io.File; 11 import java.io.IOException; 12 import java.util.UUID; 13 14 @Service 15 @Transactional 16 public class UploadFileServiceImpl implements UploadFileService { 17 18 @Autowired 19 private PicMapper picMapper; 20 21 @Override 22 public String UploadPic(MultipartFile picFile) { 23 try { 24 // 图片新名字 25 String name = UUID.randomUUID().toString(); 26 // 图片原名字 27 String oldName = picFile.getOriginalFilename(); 28 // 后缀名 29 String exeName = oldName.substring(oldName.lastIndexOf(".")); 30 //保存图片路径为绝对路径 31 File pic = new File("/Users/Shared/jpg/" + name + exeName); 32 // 保存图片到本地磁盘 33 picFile.transferTo(pic); 34 35 //保存数据到数据库中 36 picMapper.add(new Pic(name,"../jpg/"+name+exeName)); 37 return "/jpg/"+name+exeName; 38 39 } catch (IOException e) { 40 e.printStackTrace(); 41 return null; 42 } 43 } 44 }
5、创建dao层(mapper层)
1 package com.cenobitor.mapper; 2 3 import com.cenobitor.pojo.Pic; 4 5 public interface PicMapper { 6 //添加图片 7 int add(Pic pic); 8 9 }
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE mapper 3 PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 4 "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> 5 <!--namespace为对应的mapper类的全路径名--> 6 <mapper namespace="com.cenobitor.mapper.PicMapper"> 7 8 <!-- 添加 --> 9 <!-- id为对应的方法名, parameterType为入参的全路径名--> 10 <insert id="add" parameterType = "com.cenobitor.pojo.Pic"> 11 insert into 12 pic(name,url) 13 values 14 (#{name},#{url}); 15 </insert> 16 17 </mapper>
6、项目的目录结构
7、效果