UEditor之——与SpringMVC整合

Posted 冰 河

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了UEditor之——与SpringMVC整合相关的知识,希望对你有一定的参考价值。

转载请注明出处:http://blog.csdn.net/l1028386804/article/details/52389722

一、引言

相信大家做项目时,很多时候都会用到富文本编辑器。今天是2016年8月的最后一天,那么就给大家带来一篇关于JSP UEditor整合SpringMVC的文章吧,UEditor是百度的一款富文本编辑器产品,网址为:http://ueditor.baidu.com/website/  , 但是直接使用Editor时,会将编辑的图片直接上传到服务器的项目所在路径,如果每次部署项目的时候,都是全量部署(删除服务器上原有项目,重新部署),则之前上传的图片都会清空,所以,一般情况下,我们最好是将图片上传到服务器上某个单独的目录下,这样,即使我们全量部署项目,之前上传的图片也就不会丢失了。好,那我们一起来看如何将Editor整合,并将图片保存到单独的目录下。

二、准备

这里我们用的UEditor的版本是1.4.3.3 下载地址为:http://ueditor.baidu.com/build/build_down.php?n=ueditor&v=1_4_3_3-utf8-jsp  

三、实战

1、新建项目,导入UEditor

这里,我们新建Maven工程ueditor,将下载的UEditor解压后重命名为ueditor,并将文件夹拷贝到webapp/static目录下,如下图所示:



2、导入jar包

如图:


3、编辑pom.xml

<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.lyz</groupId>
  <artifactId>lyz</artifactId>
  <version>1.0.0-SNAPSHOT</version>
  <packaging>war</packaging>
  
 <properties>
        <spring.version>4.0.5.RELEASE</spring.version>
        <hibernate.version>4.3.5.Final</hibernate.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</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-orm</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <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-tx</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- hibernate -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        
        <!-- 配置HttpClient -->
         <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.1.1</version>
        </dependency>

        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.4</version>
        </dependency>

   <!--      <dependency>
            <groupId>commons-httpclient</groupId>
            <artifactId>commons-httpclient</artifactId>
            <version>3.0.1</version>
        </dependency> -->
    
        <!-- Java EE -->
        <dependency>
            <groupId>javax.persistence</groupId>
            <artifactId>persistence-api</artifactId>
            <version>1.0</version>
        </dependency>
        <dependency>
          <groupId>javax.servlet</groupId>
          <artifactId>javax.servlet-api</artifactId>
          <version>3.0.1</version>
        </dependency>
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.5</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.30</version>
        </dependency>
        
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>17.0</version>
        </dependency>
        
        <dependency>
        <groupId>net.sf.ezmorph</groupId>
        <artifactId>ezmorph</artifactId>
        <version>1.0.6</version>
        <type>jar</type>
        <scope>compile</scope>
        </dependency>
        
        <dependency> 
        <groupId>net.sf.json-lib</groupId> 
        <artifactId>json-lib</artifactId> 
        <version>2.2.3</version> 
        <classifier>jdk15</classifier> 
        </dependency>
        
        <dependency>
        <groupId>com.thoughtworks.xstream</groupId>
        <artifactId>xstream</artifactId>
        <version>1.4.4</version>
        </dependency>
        
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.0.13</version>
        </dependency>

        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.9.13</version>
        </dependency>
        <dependency>  
            <groupId>org.codehaus.jackson</groupId>  
            <artifactId>jackson-core-asl</artifactId>  
            <version>1.9.13</version>  
        </dependency>  
        
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.2.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-io</artifactId>
             <version>1.3.2</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>com.esotericsoftware.reflectasm</groupId>
            <artifactId>reflectasm</artifactId>
            <version>1.09</version>
        </dependency>
		
		<dependency>
            <groupId>xmlpull</groupId>
            <artifactId>xmlpull</artifactId>
            <version>1.1.3.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>xpp3</groupId>
            <artifactId>xpp3</artifactId>
            <version>1.1.4c</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.thoughtworks.xstream</groupId>
            <artifactId>xstream</artifactId>
            <version>1.4.7</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.7</version>
        </dependency>
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib-nodep</artifactId>
            <version>2.1_3</version>
        </dependency>
        <dependency>
            <groupId>commons-pool</groupId>
            <artifactId>commons-pool</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.6.0</version>
        </dependency>

        <!-- quartz -->
        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz</artifactId>
            <version>2.2.1</version>
        </dependency>
        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz-jobs</artifactId>
            <version>2.2.1</version>
        </dependency>
        <!-- joda time -->
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
            <version>2.4</version>
        </dependency>
        
        <dependency>
			<groupId>xml-apis</groupId>
			<artifactId>xml-apis</artifactId>
			<version>1.4.01</version>
		</dependency>
		
		 <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>fluent-hc</artifactId>
            <version>4.3.5</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.3.5</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient-cache</artifactId>
            <version>4.3.5</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.3.2</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.3.5</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
			<groupId>org.json</groupId>
			<artifactId>json</artifactId>
			<version>20140107</version>
		</dependency>
		
		  <dependency>    
		    <groupId>org.slf4j</groupId>    
		    <artifactId>slf4j-simple</artifactId>    
		    <version>1.6.1</version>
		  </dependency>    
		  <dependency>    
		    <groupId>org.slf4j</groupId>    
		    <artifactId>slf4j-api</artifactId>    
		    <version>1.6.1</version>
		  </dependency>    
		  <dependency>    
		    <groupId>commons-pool</groupId>    
		    <artifactId>commons-pool</artifactId>    
		    <version>1.5.6</version>
		  </dependency>
		  
		  <dependency>
            <groupId>codec</groupId>
            <artifactId>codec</artifactId>
            <version>1.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/commons-codec-1.9.jar</systemPath>
         </dependency>
		  <dependency>
            <groupId>fileupload</groupId>
            <artifactId>fileupload</artifactId>
            <version>1.3.1</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/commons-fileupload-1.3.1.jar</systemPath>
         </dependency>
		  <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/commons-io-2.4.jar</systemPath>
         </dependency>
		  <dependency>
            <groupId>json</groupId>
            <artifactId>json</artifactId>
            <version>1.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/json.jar</systemPath>
         </dependency>
		  <dependency>
            <groupId>ueditor</groupId>
            <artifactId>ueditor</artifactId>
            <version>1.1.2</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/ueditor-1.1.2.jar</systemPath>
         </dependency>
		 
    </dependencies>

    <build>
        <finalName>lyz</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>2.4</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-eclipse-plugin</artifactId>
                <configuration>
                    <wtpmanifest>true</wtpmanifest>
                    <wtpapplicationxml>true</wtpapplicationxml>
                    <wtpversion>2.0</wtpversion>
                </configuration>
            </plugin>
        </plugins>
        
    </build>
</project>

4、设置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_3_0.xsd" 
		id="WebApp_ID" version="3.0">
  <display-name>lyz</display-name>
  
  <!-- 配置spring监听器 -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	
	
	<!-- 加载配置文件路径 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath*:applicationContext*.xml</param-value>
	</context-param>
	
	<!-- springmvc配置 -->
	<servlet>
		<servlet-name>lyz</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
	      <param-name>contextConfigLocation</param-name>
	      <param-value>classpath*:lyz-servlet*.xml</param-value>
	    </init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>lyz</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
	
	<!-- 配置OpenSessionInView -->
	<filter>
        <filter-name>hibernateFilter</filter-name>
        <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
        <!-- singleSession默认为true,若设为false则等于没用OpenSessionInView -->
        <init-param>
            <param-name>singleSession</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
	
	<filter-mapping>
		<filter-name>hibernateFilter</filter-name>
		<url-pattern>/*</url-pattern>
	 </filter-mapping>
	 
	   <filter>
		  <filter-name>CorsFilter</filter-name>
		  <filter-class>com.lyz.utils.cors.filter.CorsFilter</filter-class>
		</filter>
		<filter-mapping>
		  <filter-name>CorsFilter</filter-name>
		  <url-pattern>/*</url-pattern>
		</filter-mapping>
	
	<!-- 字符编码过滤器 -->
    <filter>
        <filter-name>CharacterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
	
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
</web-app>

5、新建applicationContext.xml

<?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:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop" 
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:cache="http://www.springframework.org/schema/cache"
       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
 						http://www.springframework.org/schema/tx 
 						http://www.springframework.org/schema/tx/spring-tx-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/mvc 
						http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
						http://www.springframework.org/schema/cache 
						http://www.springframework.org/schema/cache/spring-cache-4.0.xsd">

      <!-- 扫描项目包的根路径 -->
    <context:component-scan base-package="com.lyz" />

    <!-- database connection pool configuration -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
    
        <!-- 基本属性 url、user、password -->
        
        <!-- 原配置 -->
        <property name="url" value="jdbc:mysql://127.0.0.1:3306/shop?characterEncoding=utf8" />
        <property name="username" value="root" />
        <property name="password" value="root" />

        <!-- 配置初始化大小、最小、最大 -->
        <property name="initialSize" value="1" />
        <property name="minIdle" value="1" />
        <property name="maxActive" value="20" />

        <!-- 配置获取连接等待超时的时间 -->
        <property name="maxWait" value="60000" />

        <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
        <property name="timeBetweenEvictionRunsMillis" value="60000" />

        <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="300000" />

        <property name="validationQuery" value="SELECT 'x'" />
        <property name="testWhileIdle" value="true" />
        <property name="testOnBorrow" value="false" />
        <property name="testOnReturn" value="false" />

        <!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
        <property name="poolPreparedStatements" value="false" />
        <property name="maxPoolPreparedStatementPerConnectionSize" value="20" />

        <!-- 配置监控统计拦截的filters -->
        <property name="filters" value="stat" />
    </bean>

	<!-- 配置sessionFactory -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="packagesToScan" value="com.lyz.**.entity"></property>
        <property name="hibernateProperties">
            <props>
                <prop key="javax.persistence.validation.mode">none</prop>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
            </props>
        </property>
    </bean>

    <!--  配置spring声明式事物管理 -->
    <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="dataSource" ref="dataSource" />
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <!-- 配置注解驱动 -->
    <tx:annotation-driven transaction-manager="transactionManager" />
	
 	<!-- 配置spring声明式事物管理:第二种方式:基于xml -->
 	<!-- 配置事务切入点,局限方法名(采用XML方法配置) -->
 	<tx:advice id="advice" transaction-manager="transactionManager">
 		<tx:attributes>
 			<!-- 配置那些方法需要切入什么事务类型 -->
 			<tx:method name="save*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
 			<tx:method name="delete*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
 			<tx:method name="update*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
 			<tx:method name="remove*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
 			<tx:method name="add*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
 			<tx:method name="*" propagation="SUPPORTS"/>
 		</tx:attributes>
 	</tx:advice>
 	
 	<!-- 上面只配置了方法的事务类型,并没有配置向哪些类(对象)切入 -->
 	<!-- 关联切入表达式 -->
 	<aop:config>
 		<aop:advisor advice-ref="advice" pointcut="execution(* com.lyz.**.service.*.*(..))"/>
 		<aop:advisor advice-ref="advice" pointcut="execution(* com.lyz.**.service.impl.*.*(..))"/>
 	</aop:config>
	
</beans>	

6、新建applications.properties

这个文件主要用来设置一些配置信息,比如图片访问路径,上传路径等,具体如下所示:

lyz.uploading.url=d:/lyz/static
lyz.visit.url=/upload/
lyz.resource.url=http://127.0.0.1:8099

7、配置log4j

#\\u8F93\\u51FA\\u5230\\u63A7\\u5236\\u53F0

log4j.appender.stout=org.apache.log4j.ConsoleAppender
log4j.appender.stout.layout=org.apache.log4j.PatternLayout
log4j.appender.stout.layout.ConversionPattern=[%p]%d{yyyy-MM-dd HH:mm:ss} %l: %m%n
#log4j.appender.stout.layout.ConversionPattern=[%p]%d{yyyy-MM-dd HH:mm:ss}: %m%n


#\\u8F93\\u51FA\\u5230\\u6587\\u4EF6
log4j.appender.fout=org.apache.log4j.FileAppender
log4j.appender.fout.file=d:/Tomcat_Project/logs/wine.log
#log4j.appender.fout.file=/opt/apache-tomcat-7.0.56/logs/wine.log
log4j.appender.fout.layout=org.apache.log4j.PatternLayout
log4j.appender.fout.layout.ConversionPattern=[%p]%d{yyyy-MM-dd HH:mm:ss} %l: %m%n
#log4j.appender.stout.layout.ConversionPattern=[%p]%d{yyyy-MM-dd HH:mm:ss}: %m%n

#\\u8F93\\u51FA\\u7EA7\\u522B
log4j.rootLogger=INFO, stout

8、配置lyz-servlet

<?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:mvc="http://www.springframework.org/schema/mvc"
	xmlns:beans="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context" 
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc 
	http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
    http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/tx 
    http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">

	<!-- <mvc:resources mapping="/resources/**" location="/resources/" /> -->
	<mvc:resources mapping="/static/**" location="/static/" />
	
	<mvc:annotation-driven /> 
	<context:component-scan base-package="com.lyz.**.controller"/>  

	<!-- Map simple view name such as "test" into /WEB-INF/test.jsp -->
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/jsp/" />
		<property name="suffix" value=".jsp" />
	</bean>

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

</beans>

9、建立实体类Shop

创建实体类主要的目的是方便运行整个项目框架,具体如下:

package com.lyz.entity;

import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

	
/**
 * 实体类shop
 * @author liuyazhuang
 *
 */
@Entity
@Table(name="c_shop")
public class Shop implements Serializable {
	private static final long serialVersionUID = -6980546472329430674L;
	@Id
    @Column(name="id")
    @GeneratedValue(strategy=GenerationType.IDENTITY)
	private Long id;
	
	public Shop() {
		super();
	}
	
	public Shop(Long id) {
		super();
		this.id = id;
	}

	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}

	@Override
	public String toString() {
		return "Shop [id=" + id + "]";
	}
	
}

10、创建读取properties文件的工具类LoadPropertiesDataUtils

package com.lyz.utils;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * 加载Properties文件数据的工具类
 * @author liuyazhuang
 *
 */
public final class LoadPropertiesDataUtils{
	
	private volatile static Properties mProperties; 
	
	static{
		mProperties = new Properties();
		InputStream in = LoadPropertiesDataUtils.class.getResourceAsStream("/applications.properties");
		try{
			mProperties.load(in);
		} catch (IOException e){
			e.printStackTrace();
		}
	}
	
	public static String getValue(String key){
		if(mProperties == null) return "";
		return mProperties.getProperty(key, "");
	}
}

11、创建随机数工具类

这个类的主要作用是生成指定位数的随机数,具体如下所示:

package com.lyz.utils;

import java.util.Random;

/**
 * 随机数工具类
 * @author liuyazhuang
 *
 */
public final class RandomUtils {
	/**
	 * 获取指定位数的随机数
	 * @param num
	 * @return
	 */
	public static String getRandom(int num){
		Random random = new Random();
		StringBuilder sb = new StringBuilder();
		for(int i = 0;i < num; i++){
			sb.append(String.valueOf(random.nextInt(10)));
		}
		return sb.toString();
	}
}

12、创建字符串工具类StringUtils

package com.lyz.utils;

/**
 * 字符串工具类
 * @author liuyazhuang
 *
 */
public final class StringUtils {
	
	/**
	 * 判断字符串是否为空
	 * @param str
	 * @return
	 */
	public static boolean isEmpty(String str){
		return (str == null || "".equals(str.trim()));
	}
	
	/**
	 * 获取名称后缀
	 * @param name
	 * @return
	 */
	public static String getExt(String name){
		if(name == null || "".equals(name) || !name.contains("."))
			return "";
		return name.substring(name.lastIndexOf(".")+1);
	}
	
}

13、创建解决跨域的类CorsFilter

package com.lyz.utils.cors.filter;
import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.filter.OncePerRequestFilter;

/**
 * 解决跨域
 * @author liuyazhuang
 *
 */
public class CorsFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
    response.addHeader("Access-Control-Allow-Origin", "*");
    response.addHeader("Access-Control-Allow-Methods",
            "GET, POST, PUT, DELETE, OPTIONS");
    response.addHeader("Access-Control-Allow-Headers",
            "origin, content-type, accept, x-requested-with, sid, mycustom, smuser");
        filterChain.doFilter(request, response);
    }
}

14、创建跳转到首页的控制器类IndexController

package com.lyz.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * 首页controller,主要的功能是跳转到首页
 * @author liuyazhuang
 *
 */
@Controller
@RequestMapping(value="/index")
public class IndexController {
	
	/**
	 * 跳转到首页
	 * @param request
	 * @param response
	 */
	@RequestMapping(value="/page", method = RequestMethod.GET)
	public String page(HttpServletRequest request, HttpServletResponse response){
		return "/index";
	}
	
}

15、创建上传文件的类UploadImageController

package com.lyz.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.lyz.utils.LoadPropertiesDataUtils;
import com.lyz.utils.RandomUtils;
import com.lyz.utils.StringUtils;


/**
 * 上传图片的controller
 * @author liuyazhuang
 *
 */
@Controller
@RequestMapping(value="/resource/upload")
public class UploadImageController {
	
	/**
	 * 上传图片
	 * @param file
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/images")
	public Map<String, Object> images (MultipartFile upfile, HttpServletRequest request, HttpServletResponse response){
		Map<String, Object> params = new HashMap<String, Object>();
		try{
			 String basePath = LoadPropertiesDataUtils.getValue("lyz.uploading.url");
			 String visitUrl = LoadPropertiesDataUtils.getValue("lyz.visit.url");
			 if(basePath == null || "".equals(basePath)){
				 basePath = "d:/lyz/static";  //与properties文件中lyz.uploading.url相同,未读取到文件数据时为basePath赋默认值
			 }
			 if(visitUrl == null || "".equals(visitUrl)){
				 visitUrl = "/upload/"; //与properties文件中lyz.visit.url相同,未读取到文件数据时为visitUrl赋默认值
			 }
			 String ext = StringUtils.getExt(upfile.getOriginalFilename());
			 String fileName = String.valueOf(System.currentTimeMillis()).concat("_").concat(RandomUtils.getRandom(6)).concat(".").concat(ext);
			 StringBuilder sb = new StringBuilder();
			 //拼接保存路径
			 sb.append(basePath).append("/").append(fileName);
			 visitUrl = visitUrl.concat(fileName);
			 File f = new File(sb.toString());
			 if(!f.exists()){
				 f.getParentFile().mkdirs();
			 }
			 OutputStream out = new FileOutputStream(f);
			 FileCopyUtils.copy(upfile.getInputStream(), out);
			 params.put("state", "SUCCESS");
			 params.put("url", visitUrl);
			 params.put("size", upfile.getSize());
			 params.put("original", fileName);
			 params.put("type", upfile.getContentType());
		} catch (Exception e){
			 params.put("state", "ERROR");
		}
		 return params;
	}
	
}

16、引入jquery

我们在webapp/static目录下创建lib目录,然后将jquery导入到lib目录下,如下图所示:


17、创建index.jsp

在webapp/WEB_INF/jsp目录下创建index.jsp,具体如下:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
 <%
	String path = request.getContextPath();
	String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>UEditor</title>
<script type="text/javascript">
	var basePath = "<%=basePath%>";
</script>
<script type="text/javascript" src="../static/lib/jquery-1.12.0.min.js"></script>
<script type="text/javascript" src="../static/ueditor/ueditor.config.js"></script>
<script type="text/javascript" src="../static/ueditor/ueditor.all.js"></script>
<script type="text/javascript" src="../static/ueditor/lang/zh-cn/zh-cn.js"></script>
<script type="text/javascript" src="../static/index/index.js"></script>
</head>
<body>
	<div>
		<textarea id="myEditor"></textarea>
	</div>
</body>
</html>
由上述代码可知,我们再index.jsp中主要定义了一个textarea标签。

18、创建index.js文件

我们在webapp/static目录下创建index文件夹,并在index文件夹中创建index.js,主要内容如下:

$(function(){
	
	//富文本编辑器
	UE.getEditor('myEditor')
	
	UE.Editor.prototype._bkGetActionUrl = UE.Editor.prototype.getActionUrl;
	UE.Editor.prototype.getActionUrl = function(action){
		if(action == '/resource/upload/images'){
			return basePath+'resource/upload/images';
		}else{
			return this._bkGetActionUrl.call(this, action);
		}
	}
});

19、编辑UEditor的config.json文件

编辑后的文件如下图所示:

/* 前后端通信相关的配置,注释只允许使用多行方式 */
{
    /* 上传图片配置项 */
    "imageActionName": "/resource/upload/images", /* 执行上传图片的action名称 */
    "imageFieldName": "upfile", /* 提交的图片表单名称 */
    "imageMaxSize": 2048000, /* 上传大小限制,单位B */
    "imageAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"], /* 上传图片格式显示 */
    "imageCompressEnable": true, /* 是否压缩图片,默认是true */
    "imageCompressBorder": 1600, /* 图片压缩最长边限制 */
    "imageInsertAlign": "none", /* 插入的图片浮动方式 */
    "imageUrlPrefix": "http://127.0.0.1:8099", /* 图片访问路径前缀 */
    "imagePathFormat": "/upload/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */
                                /* {filename} 会替换成原文件名,配置这项需要注意中文乱码问题 */
                                /* {rand:6} 会替换成随机数,后面的数字是随机数的位数 */
                                /* {time} 会替换成时间戳 */
                                /* {yyyy} 会替换成四位年份 */
                                /* {yy} 会替换成两位年份 */
                                /* {mm} 会替换成两位月份 */
                                /* {dd} 会替换成两位日期 */
                                /* {hh} 会替换成两位小时 */
                                /* {ii} 会替换成两位分钟 */
                                /* {ss} 会替换成两位秒 */
                                /* 非法字符 \\ : * ? " < > | */
                                /* 具请体看线上文档: fex.baidu.com/ueditor/#use-format_upload_filename */

    /* 涂鸦图片上传配置项 */
    "scrawlActionName": "uploadscrawl", /* 执行上传涂鸦的action名称 */
    "scrawlFieldName": "upfile", /* 提交的图片表单名称 */
    "scrawlPathFormat": "/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */
    "scrawlMaxSize": 2048000, /* 上传大小限制,单位B */
    "scrawlUrlPrefix": "", /* 图片访问路径前缀 */
    "scrawlInsertAlign": "none",

    /* 截图工具上传 */
    "snapscreenActionName": "uploadimage", /* 执行上传截图的action名称 */
    "snapscreenPathFormat": "/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */
    "snapscreenUrlPrefix": "", /* 图片访问路径前缀 */
    "snapscreenInsertAlign": "none", /* 插入的图片浮动方式 */

    /* 抓取远程图片配置 */
    "catcherLocalDomain": ["127.0.0.1", "localhost", "img.baidu.com"],
    "catcherActionName": "catchimage", /* 执行抓取远程图片的action名称 */
    "catcherFieldName": "source", /* 提交的图片列表表单名称 */
    "catcherPathFormat": "/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */
    "catcherUrlPrefix": "", /* 图片访问路径前缀 */
    "catcherMaxSize": 2048000, /* 上传大小限制,单位B */
    "catcherAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"], /* 抓取图片格式显示 */

    /* 上传视频配置 */
    "videoActionName": "uploadvideo", /* 执行上传视频的action名称 */
    "videoFieldName": "upfile", /* 提交的视频表单名称 */
    "videoPathFormat": "/ueditor/jsp/upload/video/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */
    "videoUrlPrefix": "", /* 视频访问路径前缀 */
    "videoMaxSize": 102400000, /* 上传大小限制,单位B,默认100MB */
    "videoAllowFiles": [
        ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
        ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid"], /* 上传视频格式显示 */

    /* 上传文件配置 */
    "fileActionName": "uploadfile", /* controller里,执行上传视频的action名称 */
    "fileFieldName": "upfile", /* 提交的文件表单名称 */
    "filePathFormat": "/ueditor/jsp/upload/file/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */
    "fileUrlPrefix": "", /* 文件访问路径前缀 */
    "fileMaxSize": 51200000, /* 上传大小限制,单位B,默认50MB */
    "fileAllowFiles": [
        ".png", ".jpg", ".jpeg", ".gif", ".bmp",
        ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
        ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid",
        ".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso",
        ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml"
    ], /* 上传文件格式显示 */

    /* 列出指定目录下的图片 */
    "imageManagerActionName": "listimage", /* 执行图片管理的action名称 */
    "imageManagerListPath": "/ueditor/jsp/upload/image/", /* 指定要列出图片的目录 */
    "imageManagerListSize": 20, /* 每次列出文件数量 */
    "imageManagerUrlPrefix": "", /* 图片访问路径前缀 */
    "imageManagerInsertAlign": "none", /* 插入的图片浮动方式 */
    "imageManagerAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"], /* 列出的文件类型 */

    /* 列出指定目录下的文件 */
    "fileManagerActionName": "listfile", /* 执行文件管理的action名称 */
    "fileManagerListPath": "/ueditor/jsp/upload/file/", /* 指定要列出文件的目录 */
    "fileManagerUrlPrefix": "", /* 文件访问路径前缀 */
    "fileManagerListSize": 20, /* 每次列出文件数量 */
    "fileManagerAllowFiles": [
        ".png", ".jpg", ".jpeg", ".gif", ".bmp",
        ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
        ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid",
        ".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso",
        ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml"
    ] /* 列出的文件类型 */

}
此文件中imageActionName名称的配置与index.js中的判断条件中的配置保持一致,如下图:



imageUrlPrefix为图片访问前缀。

20、配置tomcat server.xml文件

由于我们将图片放到了项目外面,独立于tomcat,所以我们要在tomcat的server.xml文件中设置虚拟路径,如下在<Host></Host>节点中添加如下代码:

<Context docBase="d:/lyz/static" path="/upload" reloadable="true"/>
此处的docBase与applications.properties文件中的lyz.uploading.url一致,path与applications.properties文件中的lyz.visit.url一致。

如下图所示:


至此,我们完成了整个项目的开发,下面我们来运行这个项目

四、运行测试

我们将项目发布到tomcat,在浏览器地址栏输入http://127.0.0.1:8099/ueditor/index/page,原因是我将tomcat端口设置为8099,


此时,查看我的图片保存路径d:/lyz/static


没有任何图片。那现在我们编辑图片吧。如下图,我在UEditor中编辑了一张图片:


我们再打开d:/lyz/static目录:



图片已经上传到我们的指定的配置目录中了。

至此整个工程创建运行结束。

五、附录

大家可以到链接http://download.csdn.net/detail/l1028386804/9618375下载基于Maven的SpringMVC整合UEditor(可单独配置上传路径 )的完整实例源码

以上是关于UEditor之——与SpringMVC整合的主要内容,如果未能解决你的问题,请参考以下文章

springMVC -- 整合UEditor(富文本编辑器)

activiti自己定义流程之整合:使用angular js整合ueditor创建表单

Java之SSM框架整合-案例IDEA版(一篇文章精通系列)Spring+SpringMVC+MyBatis(整合源代码)

Java之SSM框架整合-案例IDEA版(一篇文章精通系列)Spring+SpringMVC+MyBatis(整合源代码)

Redis之实战篇(与Mybatis整合)

springmvc学习笔记-springmvc整合mybatis之service