SpringMVC+JSP上传文件的demo

鉴于网上很多文件上传的例子不完整,或者是没有突出重点:

怎么把文本域和二进制数据一起提交到Controller里面? 故本文来探讨这个问题,把自己踩到的坑分享出来

环境:

hibernate+springmvc+jsp

功能实现:form页面填写文本字段+文件,点击提交按钮一起提交到后台

数据库mysql使用LongBlob字段存储,对应java的byte[]类型

提示:在真实生产环境中不推荐使用数据库直接存储图片文件!但是本文为了突出说明技术重点和难点。所以使用了这种简单的办法

POM文件

PS:这个POM很长,不需要参考的话直接拖下去...

<?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.hellobike.zhangjianan</groupId>
	<artifactId>zjngraduationdesign</artifactId>
	<version>1.1.0</version>
	<packaging>war</packaging>
	<name>zjngraduationdesign</name>
	<url>http://www.zhangjianan.com</url>
    
	<!-- 项目属性 -->
	<properties>
	    
		<!-- version setting -->
		<spring.version>3.2.5.RELEASE</spring.version><!-- 
		<spring-data-jpa.version>1.3.0.RELEASE</spring-data-jpa.version> -->
		<hibernate.version>4.2.0.Final</hibernate.version>
		<hibernate-search.version>4.2.0.Final</hibernate-search.version>
		<hibernate-validator.version>5.0.1.Final</hibernate-validator.version>
		<mybatis.version>3.2.3</mybatis.version>
		<mybatis-spring.version>1.2.1</mybatis-spring.version>        
		<druid.version>1.0.1</druid.version>
		<shiro.version>1.2.2</shiro.version>
		<ehcache.version>2.6.6</ehcache.version>
		<sitemesh.version>2.4.2</sitemesh.version>
		<activiti.version>5.14</activiti.version>
		<slf4j.version>1.7.5</slf4j.version>
		<log4j.version>1.2.17</log4j.version>
		<commons-lang3.version>3.1</commons-lang3.version>
		<commons-io.version>2.4</commons-io.version>
		<commons-codec.version>1.8</commons-codec.version>
		<commons-fileupload.version>1.3</commons-fileupload.version>
		<commons-beanutils.version>1.8.3</commons-beanutils.version>
		<jackson.version>2.2.1</jackson.version>
		<xstream.version>1.4.3</xstream.version>
		<guava.version>14.0.1</guava.version>
		<dozer.version>5.4.0</dozer.version>
		<poi.version>3.9</poi.version>
		<freemarker.version>2.3.19</freemarker.version>
		
		<!-- jdbc driver setting -->
		<mysql.driver.version>5.1.13</mysql.driver.version>
		<oracle.driver.version>10.2.0.1.0</oracle.driver.version>
		<mssql.driver.version>1.2.4</mssql.driver.version>
	    
		<!-- other setting -->
		<jdk.version>1.6</jdk.version>
		<tomcat.version>2.1</tomcat.version>
		<jetty.version>7.6.10.v20130312</jetty.version>
		<webserver.port>8181</webserver.port>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<downloadSources>false</downloadSources>
		
	</properties>

	<!-- 设定除中央仓库(repo1.maven.org/maven2/)外的其他仓库,按设定顺序进行查找. -->
	<repositories>
	
		<!-- 如有Nexus私服, 取消注释并指向正确的服务器地址.
		<repository>
			<id>nexus-repos</id>
			<name>Team Nexus Repository</name>
			<url>http://localhost:8081/nexus/content/groups/public</url>
			<releases>
				<enabled>true</enabled>
			</releases>
			<snapshots>
				<enabled>false</enabled>
			</snapshots>
		</repository> -->
		
		<repository>
			<id>central-repos</id>
			<name>Central Repository</name>
			<url>http://repo.maven.apache.org/maven2</url>
		</repository>
		
		<repository>
			<id>central-repos2</id>
			<name>Central Repository 2</name>
			<url>http://repo1.maven.org/maven2/</url>
		</repository>
		
		<repository>
			<id>springsource-repos</id>
			<name>SpringSource Repository</name>
			<url>http://repo.springsource.org/libs-milestone-local</url>
	    </repository>
		
		<repository>
			<id>activiti-repos</id>
			<name>Activiti Repository</name>
			<url>https://maven.alfresco.com/nexus/content/groups/public</url>
		</repository>
		
		<repository>
			<id>activiti-repos2</id>
			<name>Activiti Repository 2</name>
			<url>https://app.camunda.com/nexus/content/groups/public</url>
		</repository>
		
		<repository> 
			<id>thinkgem-repos</id> 
			<name>ThinkGem Repository</name>
			<url>http://git.oschina.net/thinkgem/repos/raw/master</url>
		</repository>
		
		<repository> 
			<id>thinkgem-repos2</id> 
			<name>ThinkGem Repository 2</name>
			<url>https://raw.github.com/thinkgem/repository/master</url>
		</repository>
		
	</repositories>	
	<pluginRepositories> 
	
		<!-- 如有Nexus私服, 取消注释并指向正确的服务器地址.
		<pluginRepository>
			<id>nexus-repos</id>
			<name>Team Nexus Repository</name>
			<url>http://localhost:8081/nexus/content/groups/public</url>
			<releases>
				<enabled>true</enabled>
			</releases>
			<snapshots>
				<enabled>false</enabled>
			</snapshots>
		</pluginRepository> -->
		
	</pluginRepositories> 
	
	<!-- 依赖项定义 -->
	<dependencies>
		<!-- ERMaster begin -->
		<dependency>
		    <groupId>org.eclipse</groupId>
		    <artifactId>swt</artifactId>
		    <version>3.3.0-v3346</version>
		</dependency>
		<dependency>
			<groupId>org.eclipse</groupId>
			<artifactId>draw2d</artifactId>
			<version>3.2.100-v20070529</version>
		</dependency>
		<dependency>
			<groupId>org.eclipse</groupId>
			<artifactId>jface</artifactId>
			<version>3.3.0-I20070606-0010</version>
		</dependency>
		<dependency>
            <groupId>org.insightech.er</groupId>
            <artifactId>ERMaster</artifactId>
            <version>20121127-2328</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/src/main/webapp/WEB-INF/lib/org.insightech.er_1.0.0.v20121127-2328.jar</systemPath>
        </dependency>
		<!-- ERMaster end -->
		<dependency>
		   <groupId>bitwalker</groupId>
		   <artifactId>UserAgentUtils</artifactId>
		   <version>1.13</version>
		</dependency>
		<dependency>
		    <groupId>org.zeroturnaround</groupId>
		    <artifactId>zt-zip</artifactId>
		    <version>1.6</version>
		    <type>jar</type>
		</dependency>
	
		<!-- SPRING begin -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
			<exclusions>
				<exclusion>
					<groupId>commons-logging</groupId>
					<artifactId>commons-logging</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</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-aop</artifactId>
			<version>${spring.version}</version>
			<exclusions>
				<exclusion>
					<groupId>commons-logging</groupId>
					<artifactId>commons-logging</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>${spring.version}</version>
		</dependency>
			
		<!-- spring orm -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>${spring.version}</version>
		</dependency>
		
		<!-- spring data jpa
		<dependency>
	    	<groupId>org.springframework.data</groupId>
	    	<artifactId>spring-data-jpa</artifactId>
	    	<version>${spring-data-jpa.version}</version>
			<exclusions>
				<exclusion>
					<groupId>junit</groupId>
					<artifactId>junit-dep</artifactId>
				</exclusion>
			</exclusions>
		</dependency> -->
		<!-- SPRING end -->
		
		<!-- AOP begin -->
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjrt</artifactId>
			<version>1.7.4</version>
		</dependency>
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
			<version>1.7.4</version>
		</dependency>
		<dependency>
			<groupId>cglib</groupId>
			<artifactId>cglib</artifactId>
			<version>3.1</version>
			<scope>runtime</scope>
		</dependency>
		<!-- AOP end -->

		<!-- PERSISTENCE begin -->
		<!-- Hibernate -->
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>${hibernate.version}</version>
		</dependency><!-- jpa
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-entitymanager</artifactId>
			<version>${hibernate.version}</version>
		</dependency> -->
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-ehcache</artifactId>
			<version>${hibernate.version}</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-validator</artifactId>
			<version>${hibernate-validator.version}</version>
		</dependency>
		<dependency>
		    <groupId>org.hibernate</groupId>
		    <artifactId>hibernate-search</artifactId>
		    <version>${hibernate-search.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>
		
        <!-- 中文分词 -->
		<dependency>
            <groupId>org.wltea</groupId>
            <artifactId>analyzer</artifactId>
            <version>2012_u6</version>
        </dependency>

		<!-- connection pool -->
		<dependency>
		     <groupId>com.alibaba</groupId>
		     <artifactId>druid</artifactId>
		     <version>${druid.version}</version>
		</dependency>

		<!-- jdbc driver -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>${mysql.driver.version}</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>com.oracle</groupId>
			<artifactId>ojdbc14</artifactId>
			<version>${oracle.driver.version}</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>net.sourceforge.jtds</groupId>
			<artifactId>jtds</artifactId>
			<version>${mssql.driver.version}</version>
			<scope>runtime</scope>
		</dependency>
		<!-- PERSISTENCE end -->

		<!-- WEB begin -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</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-oxm</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>opensymphony</groupId>
			<artifactId>sitemesh</artifactId>
			<version>${sitemesh.version}</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>taglibs</groupId>
			<artifactId>standard</artifactId>
			<version>1.1.2</version>
			<type>jar</type>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
			<type>jar</type>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
		    <groupId>javax.servlet.jsp</groupId>
		    <artifactId>jsp-api</artifactId>
		    <version>2.1</version>
		    <scope>provided</scope>
		</dependency>
		<!-- WEB end -->

		<!-- EHCACHE begin -->
		<dependency>
			<groupId>net.sf.ehcache</groupId>
			<artifactId>ehcache-core</artifactId>
			<version>${ehcache.version}</version>
		</dependency>
		<dependency>
            <groupId>net.sf.ehcache</groupId>  
            <artifactId>ehcache-web</artifactId>  
            <version>2.0.4</version>
        </dependency>
		<!-- EHCACHE end -->
		
		<!-- SECURITY begin -->
		<dependency>
			<groupId>org.apache.shiro</groupId>
			<artifactId>shiro-core</artifactId>
			<version>${shiro.version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.shiro</groupId>
			<artifactId>shiro-spring</artifactId>
			<version>${shiro.version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.shiro</groupId>
			<artifactId>shiro-web</artifactId>
			<version>${shiro.version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.shiro</groupId>
			<artifactId>shiro-ehcache</artifactId>
			<version>${shiro.version}</version>
		</dependency>
		<!-- SECURITY end -->
		
		<!-- Activiti -->
		<dependency>
			<groupId>org.activiti</groupId>
			<artifactId>activiti-engine</artifactId>
			<version>${activiti.version}</version>
		</dependency>
		<dependency>
			<groupId>org.activiti</groupId>
			<artifactId>activiti-spring</artifactId>
			<version>${activiti.version}</version>
		</dependency>
		<dependency>
			<groupId>org.eclipse</groupId>
			<artifactId>draw2d</artifactId>
			<version>3.2.100-v20070529</version>
		</dependency>
		
		<!-- LOGGING begin -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${slf4j.version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>${slf4j.version}</version>
			<scope>runtime</scope>
		</dependency>
		<!-- common-logging 实际调用slf4j -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>jcl-over-slf4j</artifactId>
			<version>${slf4j.version}</version>
			<scope>runtime</scope>
		</dependency>
		<!-- java.util.logging 实际调用slf4j -->
		<dependency>
        	<groupId>org.slf4j</groupId>
        	<artifactId>jul-to-slf4j</artifactId>
        	<version>${slf4j.version}</version>
        	<scope>runtime</scope>
      	</dependency>
      	<!-- log4j -->
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>${log4j.version}</version>
		</dependency>
		<!-- log4jdbc -->
		<dependency>
			<groupId>org.lazyluke</groupId>
			<artifactId>log4jdbc-remix</artifactId>
			<version>0.2.7</version>
			<scope>runtime</scope>
		</dependency>
		<!-- LOGGING end -->
		
		<!-- GENERAL UTILS begin -->
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
			<version>${commons-lang3.version}</version>
		</dependency>
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>${commons-io.version}</version>
		</dependency>
		<dependency>
			<groupId>commons-codec</groupId>
			<artifactId>commons-codec</artifactId>
			<version>${commons-codec.version}</version>
		</dependency>
		<dependency>
		    <groupId>commons-fileupload</groupId>
		    <artifactId>commons-fileupload</artifactId>
		    <version>${commons-fileupload.version}</version>
		</dependency>
		<dependency>
			<groupId>commons-beanutils</groupId>
			<artifactId>commons-beanutils</artifactId>
			<version>${commons-beanutils.version}</version>
			<exclusions>
				<exclusion>
					<groupId>commons-logging</groupId>
					<artifactId>commons-logging</artifactId>
				</exclusion>
			</exclusions>
		</dependency>

		<!-- google java library -->
		<dependency>
			<groupId>com.google.guava</groupId>
			<artifactId>guava</artifactId>
			<version>${guava.version}</version>
		</dependency>
		
		<!-- jackson json -->
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-core</artifactId>
			<version>${jackson.version}</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>${jackson.version}</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-annotations</artifactId>
			<version>${jackson.version}</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.module</groupId>
			<artifactId>jackson-module-jaxb-annotations</artifactId>
			<version>${jackson.version}</version>
		</dependency>
		
		<!-- xstream xml -->
		<dependency>
			<groupId>com.thoughtworks.xstream</groupId>
			<artifactId>xstream</artifactId>
			<version>${xstream.version}</version>
		</dependency>
		
		<!-- pojo copy -->
		<dependency>
			<groupId>net.sf.dozer</groupId>
			<artifactId>dozer</artifactId>
			<version>${dozer.version}</version>
		</dependency>
       	
        <!-- freemarker engine -->
		<dependency>
			<groupId>org.freemarker</groupId>
			<artifactId>freemarker</artifactId>
			<version>${freemarker.version}</version>
		</dependency>
		
		<!-- email -->
		<dependency>
		    <groupId>javax.mail</groupId>
		    <artifactId>mail</artifactId>
		    <version>1.4.7</version>
		</dependency>
		<dependency>
		    <groupId>javax.activation</groupId>
		    <artifactId>activation</artifactId>
		    <version>1.1.1</version>
		</dependency>
		
		<!-- poi office -->
	  	<dependency>
		    <groupId>org.apache.poi</groupId>
		    <artifactId>poi</artifactId>
		    <version>${poi.version}</version>
		</dependency>
		<dependency>
		    <groupId>org.apache.poi</groupId>
		    <artifactId>poi-ooxml</artifactId>
		    <version>${poi.version}</version>
		</dependency>
		<dependency>
		    <groupId>org.apache.poi</groupId>
		    <artifactId>poi-ooxml-schemas</artifactId>
		    <version>${poi.version}</version>
		</dependency>
		
		<!-- image util -->
		<dependency>
		    <groupId>com.drewnoakes</groupId>
		    <artifactId>metadata-extractor</artifactId>
		    <version>2.6.2</version>
		</dependency>
		<!-- GENERAL UTILS end -->
		
		<!-- CKFinder begin -->
		<dependency>
		    <groupId>net.coobird</groupId>
		    <artifactId>thumbnailator</artifactId>
		    <version>0.4.2</version>
		</dependency>
		<dependency>
            <groupId>com.ckfinder</groupId>
            <artifactId>apache-ant-zip</artifactId>
            <version>2.3</version>
        </dependency>
		<dependency>
            <groupId>com.ckfinder</groupId>
            <artifactId>ckfinder</artifactId>
            <version>2.3</version>
        </dependency>
		<dependency>
            <groupId>com.ckfinder</groupId>
            <artifactId>ckfinderplugin-fileeditor</artifactId>
            <version>2.3</version>
        </dependency>
		<dependency>
            <groupId>com.ckfinder</groupId>
            <artifactId>ckfinderplugin-imageresize</artifactId>
            <version>2.3</version>
        </dependency>
		<!-- CKFinder end -->
		
		<!-- TEST begin -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.11</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<!-- TEST end -->
		
		<!-- 自定义jar依赖包
		<dependency>
            <groupId>com.test</groupId>
            <artifactId>test-core</artifactId>
            <version>1.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/src/main/webapp/WEB-INF/lib/test-core-1.0.jar</systemPath>
        </dependency> -->
		
	</dependencies>

	<build>
		<outputDirectory>${project.basedir}/src/main/webapp/WEB-INF/classes/</outputDirectory>
		<plugins>
			<!-- Compiler 插件, 设定JDK版本 -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.5.1</version>
				<configuration>
					<source>${jdk.version}</source>
					<target>${jdk.version}</target>
					<showWarnings>true</showWarnings>
				</configuration>
			</plugin>

			<!-- war 打包插件, 设定war包名称不带版本号 -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-war-plugin</artifactId>
				<version>2.3</version>
				<configuration>
					<warName>${project.artifactId}</warName>
				</configuration>
			</plugin>
			
			<!-- Eclipse 插件 -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-eclipse-plugin</artifactId>
				<version>2.9</version>
				<configuration>
					<downloadSources>${downloadSources}</downloadSources>
					<downloadJavadocs>false</downloadJavadocs>
					<wtpversion>2.0</wtpversion>
					<sourceIncludes>
						<sourceInclude>**/*.xml</sourceInclude>
						<sourceInclude>**/*.jsp</sourceInclude>
					</sourceIncludes>
					<additionalConfig>
						<file>
							<name>.settings/org.eclipse.core.resources.prefs</name>
							<content>
					    	    <![CDATA[eclipse.preferences.version=1${line.separator}encoding/<project>=${project.build.sourceEncoding}${line.separator}]]>
							</content>
						</file>
					</additionalConfig>
					<additionalProjectnatures>
						<projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
					</additionalProjectnatures>
				</configuration>
			</plugin>
			
			<!-- tomcat6插件 -->
			<plugin>
				<groupId>org.apache.tomcat.maven</groupId>
				<artifactId>tomcat6-maven-plugin</artifactId>
				<version>${tomcat.version}</version> 
				<configuration>
					<port>${webserver.port}</port>
					<path>/${project.artifactId}</path>
					<uriEncoding>${project.build.sourceEncoding}</uriEncoding>
				</configuration>
			</plugin>
			
			<!-- tomcat7插件 -->
			<plugin>
				<groupId>org.apache.tomcat.maven</groupId>
				<artifactId>tomcat7-maven-plugin</artifactId>
				<version>${tomcat.version}</version> 
				<configuration>
					<port>${webserver.port}</port>
					<path>/${project.artifactId}</path>
					<uriEncoding>${project.build.sourceEncoding}</uriEncoding>
				</configuration>
			</plugin>

			<!-- jetty插件 -->
			<plugin>
				<groupId>org.mortbay.jetty</groupId>
				<artifactId>jetty-maven-plugin</artifactId>
				<version>${jetty.version}</version>
				<configuration>
					<connectors>
						<connector implementation="org.eclipse.jetty.server.nio.SelectChannelConnector">
							<port>${webserver.port}</port>
						</connector>
					</connectors>
					<webAppConfig>
						<contextPath>/${project.artifactId}</contextPath>
					</webAppConfig>
					<systemProperties>  
			            <systemProperty>
			            	<name>org.mortbay.util.URI.charset</name>
			            	<value>${project.build.sourceEncoding}</value>
			        	</systemProperty>
			        </systemProperties>
				</configuration>
			</plugin>
			
			<!-- resource插件 -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-resources-plugin</artifactId>
				<version>2.6</version>
			</plugin>
			
			<!-- install插件 -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-install-plugin</artifactId>
				<version>2.4</version>
			</plugin>

			<!-- clean插件 -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-clean-plugin</artifactId>
				<version>2.5</version>
			</plugin>
			
			<!-- ant插件 -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-antrun-plugin</artifactId>
				<version>1.7</version>
			</plugin>
			
			<!-- dependency插件 -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-dependency-plugin</artifactId>
				<version>2.5.1</version>
			</plugin>
		</plugins>
	</build>
	
	<profiles>
		<!-- 初始化数据库 -->			
		<profile>
			<id>init-db</id>
			<dependencies>
				<dependency>
					<groupId>org.dbunit</groupId>
					<artifactId>dbunit</artifactId>
					<version>2.4.8</version>
				</dependency>
			  	<dependency>
				    <groupId>org.apache.poi</groupId>
				    <artifactId>poi</artifactId>
				    <version>3.2-FINAL</version>
				</dependency>
			</dependencies>
			<build>
				<plugins>
					<plugin>
						<groupId>org.apache.maven.plugins</groupId>
        				<artifactId>maven-antrun-plugin</artifactId>
        				<version>1.7</version>
        				<configuration>
              				<target>
              				    
              				    <!-- mysql -->
								<property name="dbunit.datatype" value="org.dbunit.ext.mysql.MySqlDataTypeFactory" />
								
								<!-- oracle
								<property name="dbunit.datatype" value="org.dbunit.ext.oracle.Oracle10DataTypeFactory" /> -->
								
              				    <!-- mssql
								<property name="dbunit.datatype" value="org.dbunit.ext.mssql.MsSqlDataTypeFactory" /> -->
								
								<property file="src/main/resources/application.properties" />              				    
                				<sql driver="${jdbc.driver}" url="${jdbc.url}" userid="${jdbc.username}" password="${jdbc.password}" 
                				    onerror="continue" encoding="${project.build.sourceEncoding}">
									<classpath refid="maven.test.classpath" />
									<transaction src="db/sys/jeesite_${jdbc.type}.sql"/>
									<transaction src="db/cms/jeesite_${jdbc.type}.sql"/>
									<transaction src="db/oa/jeesite_${jdbc.type}.sql"/>
									<transaction src="db/prj/jeesite_${jdbc.type}.sql"/>
									<transaction src="db/act/drop/activiti.${jdbc.type}.drop.engine.sql"/>
									<transaction src="db/act/drop/activiti.${jdbc.type}.drop.history.sql"/>
									<transaction src="db/act/drop/activiti.${jdbc.type}.drop.identity.sql"/>
									<transaction src="db/act/create/activiti.${jdbc.type}.create.engine.sql"/>
									<transaction src="db/act/create/activiti.${jdbc.type}.create.history.sql"/>
									<transaction src="db/act/create/activiti.${jdbc.type}.create.identity.sql"/>
								</sql>
								
								<taskdef name="dbunit" classname="org.dbunit.ant.DbUnitTask" classpathref="maven.test.classpath" />
								
								<!-- mysql、mssql -->
	                            <dbunit driver="${jdbc.driver}" url="${jdbc.url}" userid="${jdbc.username}" password="${jdbc.password}">
	                            
								<!-- oracle
	                            <dbunit driver="${jdbc.driver}" url="${jdbc.url}" userid="${jdbc.username}" password="${jdbc.password}"
	                                schema="${jdbc.username}" > -->
									
									<dbconfig>
										<property name="datatypeFactory" value="${dbunit.datatype}" />
									</dbconfig>
									<classpath refid="maven.test.classpath" />
									<operation type="INSERT" src="db/sys/jeesite_data.xls" format="xls" transaction="true"/>
									<operation type="INSERT" src="db/cms/jeesite_data.xls" format="xls" transaction="true"/>
									<operation type="INSERT" src="db/oa/jeesite_data.xls" format="xls" transaction="true"/>
									
								</dbunit>
								
              				</target>
            			</configuration>
					</plugin>
				</plugins>
			</build>
		</profile>
		
		<!-- 生成自定义代码 -->
		<profile>
			<id>code-gen</id>
			<build>
				<plugins>
					<plugin>
						<groupId>org.apache.maven.plugins</groupId>
						<artifactId>maven-antrun-plugin</artifactId>
						<version>1.7</version>
						<configuration>
							<target>
								<echo message="Code Generate" />
								<java classname="com.hellobike.zhangjianan.generate.Generate">
									<classpath refid="maven.runtime.classpath"/>
								</java>
							</target>
						</configuration>
					</plugin>
				</plugins>
			</build>
		</profile>
		
	</profiles>
	
	<!-- 开发者信息 -->
	<developers>  
		<developer>
			<id>thinkgem</id>
			<name>ZhangJiaNan</name>
			<email>thinkgem at 163.com</email>
			<roles><role>Project lead</role></roles>
			<timezone>+8</timezone>  
		</developer>
	</developers>
	
</project>

四个要素

1.mvc配置文件

SpringMVC配置文件里面必须有这个bean

<!-- 上传文件拦截,设置最大上传文件大小   10M=10*1024*1024(B)=10485760 bytes -->  
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
        <property name="maxUploadSize" value="10485760" />  
</bean>

2.form的写法

form里面必须有 enctype="multipart/form-data"

	<form:form id="inputForm" modelAttribute="hotel" 
         action="${ctx}/frontsite/hotel/save" method="post" 
         enctype="multipart/form-data" 
		 class="form-horizontal">

		<form:hidden path="id" />
		<tags:message content="${message}" />

		<div class="control-group">
			<label class="control-label" for="value">名称:</label>
			<div class="controls">
				<form:input path="name" htmlEscape="false" maxlength="50" class="required" />
			</div>
		</div>
        <!-- 其他的一些表单域,在此省略 -->
        .
        .
        .
        .
        .
        .
		<div class="control-group">
			<label class="control-label" for="sort">图片:</label>
			<div class="controls">
				<!--input-group start-->
				<div id="preview">
					<c:if test="${hotel.id == null}">
						<img id="imghead" border="0" src="${ctxStatic}/images/photo_icon.png" width="90" height="90"
							onclick="$('#picture').click();">
					</c:if>
					<c:if test="${hotel.id != null}">
						<img id="imghead" border="0" src="${ctx}/frontsite/hotel/getPhotoBlob?id=${hotel.id}"
							width="90" height="90" onclick="$('#picture').click();">
					</c:if>
				</div>
				<form:input path="picture" type="file" onchange="previewImage(this)" style="display: none;" />
				<!--input-group end-->
			</div>
		</div>
		<div class="form-actions">
			<input id="btnSubmit" class="btn btn-primary" type="submit" value="保 存" />&nbsp; <input
				id="btnCancel" class="btn" type="button" value="返 回" onclick="history.go(-1)" />
		</div>
	</form:form>

3.Controller里面写法

Controller里面保存数据的方法必须这样写:

目的就是把MultipartHttpServletRequestHttpServletRequest 分开处理

@RequiresPermissions("frontsite:hotel:view")
@RequestMapping(value = "save")
public String save(HttpServletRequest request, Model model, RedirectAttributes redirectAttributes) {
	Hotel hotel = null;
	if(StringUtils.isNotBlank(request.getParameter("id"))){
		 hotel = hotelService.get(Long.valueOf(request.getParameter("id")));
	 }else{
		 hotel  = new Hotel();
	 }
	if (request instanceof MultipartHttpServletRequest) {
		 MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartHttpServletRequest.getFileMap();
        for(Map.Entry<String, MultipartFile> entry : fileMap.entrySet()){
            // 对文件进处理
            System.out.println(entry.getKey() + ":" + entry.getValue().getOriginalFilename());
            try {
				hotel.setPicture(entry.getValue().getBytes());
			} catch (IOException e) {
				e.printStackTrace();
			}
        }
        
		hotel.setName(request.getParameter("name"));
		hotel.setInfo(request.getParameter("info"));
		hotel.setAddress(request.getParameter("address"));		
        hotel.setPrice(new BigDecimal(request.getParameter("price")));
		hotel.setPhone(request.getParameter("phone"));
		hotel.setCountry(request.getParameter("country"));
		hotel.setProvince(request.getParameter("province"));
		hotel.setCity(request.getParameter("city"));
		hotel.setArea(request.getParameter("area"));
	}
	hotelService.save(hotel);
	return "redirect:" + Global.getAdminPath() + "/frontsite/hotel/";
}

4.数据回显怎么办?

前三个要素满足了,保存文件到数据库的longBlob字段就没问题了

但是要想在编辑页面把图片回显出来,还需要下功夫,见如下jsp代码

//代码说明:新增页面和修改页面分开来处理,用<c:if判断,关键是用src="XXXX"指向一个专门获取图片的controller方法
<div class="control-group">
	<label class="control-label" for="sort">图片:</label>
	<div class="controls">
		<!--input-group start-->
		<div id="preview">
			<c:if test="${hotel.id == null}">
				<img id="imghead" border="0" src="${ctxStatic}/images/photo_icon.png" width="90" height="90"
					onclick="$('#picture').click();">
			</c:if>
			<c:if test="${hotel.id != null}">
				<img id="imghead" border="0" src="${ctx}/frontsite/hotel/getPhotoBlob?id=${hotel.id}"
					width="90" height="90" onclick="$('#picture').click();">
			</c:if>
		</div>
		<form:input path="picture" type="file" onchange="previewImage(this)" style="display: none;" />
		<!--input-group end-->
	</div>
</div>

上面这段代码最关键的是

src="${ctxStatic}/images/photo_icon.png"

和这个代码对应的Controller后台的代码如下:

@RequestMapping("getPhotoBlob")
public void getPhotoBlob(Long id, HttpServletRequest request, HttpServletResponse response) {
	try {
		// blob就是你要显示的那张图片
		byte[] data = hotelService.findPictureById(id);
		OutputStream out = response.getOutputStream();
		response.setContentType("image/png");
		out.write(data);
		out.close();
	} catch (Exception e) {
		e.printStackTrace();
	}
}

service层

public byte[] findPictureById(Long id) throws SQLException {
	return hotelDao.findPictureById(id);
}	

和DAO层:

public byte[] findPictureById(Long id) throws SQLException {
	ScenicSpot scenicSpot = getByHql("from ScenicSpot where id=:p1", new Parameter(id));
	if (scenicSpot != null && scenicSpot.getPicture() != null) {
		return scenicSpot.getPicture();
	} else {
		// 为了防止页面空指针
		return "null".getBytes();
	}
}

添加页面:

174857_Dhbm_2338224.png

 

 

修改页面回显:

174812_0Nt5_2338224.png

至此,大功告成 

 

附加内容

好人做到底,顺便把文件上传的控件代码也提供一下,请叫我雷锋:

<%@ page contentType="text/html;charset=UTF-8"%>
<%@ include file="/WEB-INF/views/include/taglib.jsp"%>
<html>
<head>
<title>酒店管理</title>
<meta name="decorator" content="default" />
<script type="text/javascript">
	$(document).ready(function() {
		$("#value").focus();
		$("#inputForm").validate();
	});
</script>
</head>
<body>
	<ul class="nav nav-tabs">
		<li><a href="${ctx}/frontsite/hotel/">酒店列表</a></li>
		<li class="active"><a href="${ctx}/frontsite/hotel/form?id=${hotel.id}">酒店${not empty hotel.id?'修改':'添加'}</a></li>
	</ul>
	<br />

	<form:form id="inputForm" modelAttribute="hotel" action="${ctx}/frontsite/hotel/save" method="post" enctype="multipart/form-data" 
		class="form-horizontal">
		<form:hidden path="id" />
		<tags:message content="${message}" />

		<div class="control-group">
			<label class="control-label" for="value">名称:</label>
			<div class="controls">
				<form:input path="name" htmlEscape="false" maxlength="50" class="required" />
			</div>
		</div>
		<div class="control-group">
			<label class="control-label" for="label">描述信息:</label>
			<div class="controls">
				<form:input path="info" htmlEscape="false" maxlength="50" class="required" />
			</div>
		</div>
		<div class="control-group">
			<label class="control-label" for="type">地址:</label>
			<div class="controls">
				<form:input path="address" htmlEscape="false" maxlength="50" class="required" />
			</div>
		</div>
		<div class="control-group">
			<label class="control-label" for="description">价格:</label>
			<div class="controls">
				<form:input path="price" htmlEscape="false" maxlength="50" class="required" />
			</div>
		</div>
		<div class="control-group">
			<label class="control-label" for="sort">电话:</label>
			<div class="controls">
				<form:input path="phone" htmlEscape="false" maxlength="11" class="required" />
			</div>
		</div>
		<div class="control-group">
			<label class="control-label" for="sort">图片:</label>
			<div class="controls">
				<!--input-group start-->
				<div id="preview">
					<c:if test="${hotel.id == null}">
						<img id="imghead" border="0" src="${ctxStatic}/images/photo_icon.png" width="90" height="90"
							onclick="$('#picture').click();">
					</c:if>
					<c:if test="${hotel.id != null}">
						<img id="imghead" border="0" src="${ctx}/frontsite/hotel/getPhotoBlob?id=${hotel.id}"
							width="90" height="90" onclick="$('#picture').click();">
					</c:if>
				</div>
				<form:input path="picture" type="file" onchange="previewImage(this)" style="display: none;" />
				<!--input-group end-->
			</div>
		</div>
		<div class="control-group">
			<label class="control-label" for="sort">国家:</label>
			<div class="controls">
				<form:input path="country" htmlEscape="false" maxlength="11" class="required" />
			</div>
		</div>
		<div class="control-group">
			<label class="control-label" for="sort">省:</label>
			<div class="controls">
				<form:input path="province" htmlEscape="false" maxlength="11" class="required" />
			</div>
		</div>
		<div class="control-group">
			<label class="control-label" for="sort">市:</label>
			<div class="controls">
				<form:input path="city" htmlEscape="false" maxlength="11" class="required" />
			</div>
		</div>
		<div class="control-group">
			<label class="control-label" for="sort">区:</label>
			<div class="controls">
				<form:input path="area" htmlEscape="false" maxlength="11" class="required" />
			</div>
		</div>
		<div class="form-actions">
			<input id="btnSubmit" class="btn btn-primary" type="submit" value="保 存" />&nbsp; <input
				id="btnCancel" class="btn" type="button" value="返 回" onclick="history.go(-1)" />
		</div>
	</form:form>
	<script type="text/javascript">
		//图片上传预览    IE是用了滤镜。
		function previewImage(file) {
			var MAXWIDTH = 180;
			var MAXHEIGHT = 180;
			var div = document.getElementById('preview');
			if (file.files && file.files[0]) {
				div.innerHTML = '<img id=imghead onclick=$("#picture").click()>';
				var img = document.getElementById('imghead');
				img.onload = function() {
					var rect = clacImgZoomParam(MAXWIDTH, MAXHEIGHT,
							img.offsetWidth, img.offsetHeight);
					img.width = rect.width;
					img.height = rect.height;
					//         img.style.marginLeft = rect.left+'px';
					img.style.marginTop = rect.top + 'px';
				}
				var reader = new FileReader();
				reader.onload = function(evt) {
					img.src = evt.target.result;
				}
				reader.readAsDataURL(file.files[0]);
			} else //兼容IE
			{
				var sFilter = 'filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale,src="';
				file.select();
				var src = document.selection.createRange().text;
				div.innerHTML = '<img id=imghead>';
				var img = document.getElementById('imghead');
				img.filters.item('DXImageTransform.Microsoft.AlphaImageLoader').src = src;
				var rect = clacImgZoomParam(MAXWIDTH, MAXHEIGHT,
						img.offsetWidth, img.offsetHeight);
				status = ('rect:' + rect.top + ',' + rect.left + ','
						+ rect.width + ',' + rect.height);
				div.innerHTML = "<div id=divhead style='width:"+rect.width+"px;height:"+rect.height+"px;margin-top:"+rect.top+"px;"+sFilter+src+"\"'></div>";
			}
		}
		function clacImgZoomParam(maxWidth, maxHeight, width, height) {
			var param = {
				top : 0,
				left : 0,
				width : width,
				height : height
			};
			if (width > maxWidth || height > maxHeight) {
				rateWidth = width / maxWidth;
				rateHeight = height / maxHeight;

				if (rateWidth > rateHeight) {
					param.width = maxWidth;
					param.height = Math.round(height / rateWidth);
				} else {
					param.width = Math.round(width / rateHeight);
					param.height = maxHeight;
				}
			}
			param.left = Math.round((maxWidth - param.width) / 2);
			param.top = Math.round((maxHeight - param.height) / 2);
			return param;
		}
	</script>
</body>
</html>

 

转载于:https://my.oschina.net/u/2338224/blog/1799294

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值