自己照着从其他地方找的代码,写了一个测试用的小项目
现在贴出来,后续可以看看
环境:Ubuntu Kylin16.0.4 jdk1.7 tomcat7
1、项目整体结构:
2、因为是web项目,使用maven进行jar包依赖的管理:
web.xml文件和pom.xml文件
pom
1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 2 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 3 <modelVersion>4.0.0</modelVersion> 4 <groupId>com.fh</groupId> 5 <artifactId>com.fh.test</artifactId> 6 <version>0.0.1-SNAPSHOT</version> 7 <packaging>war</packaging> 8 9 10 <properties> 11 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><!-- 12 资源构建编码 --> 13 <spring.version>4.1.3.RELEASE</spring.version> 14 </properties> 15 16 <dependencies> 17 <!-- 测试框架 --> 18 <dependency> 19 <groupId>junit</groupId> 20 <artifactId>junit</artifactId> 21 <version>4.12</version> 22 <scope>test</scope> 23 </dependency> 24 25 <!-- Spring start --> 26 27 <dependency> 28 <groupId>org.springframework</groupId> 29 <artifactId>spring-orm</artifactId> 30 <version>${spring.version}</version> 31 <exclusions> 32 <exclusion> 33 <groupId>org.springframework</groupId> 34 <artifactId>spring-core</artifactId> 35 </exclusion> 36 </exclusions> 37 </dependency> 38 <dependency> 39 <groupId>org.springframework</groupId> 40 <artifactId>spring-tx</artifactId> 41 <version>${spring.version}</version> 42 <exclusions> 43 <exclusion> 44 <groupId>org.springframework</groupId> 45 <artifactId>spring-core</artifactId> 46 </exclusion> 47 </exclusions> 48 </dependency> 49 <dependency> 50 <groupId>org.springframework</groupId> 51 <artifactId>spring-context</artifactId> 52 <version>${spring.version}</version> 53 <exclusions> 54 <exclusion> 55 <groupId>org.springframework</groupId> 56 <artifactId>spring-core</artifactId> 57 </exclusion> 58 </exclusions> 59 </dependency> 60 <dependency> 61 <groupId>org.springframework</groupId> 62 <artifactId>spring-context-support</artifactId> 63 <version>${spring.version}</version> 64 <exclusions> 65 <exclusion> 66 <groupId>org.springframework</groupId> 67 <artifactId>spring-core</artifactId> 68 </exclusion> 69 </exclusions> 70 </dependency> 71 <dependency> 72 <groupId>org.springframework</groupId> 73 <artifactId>spring-beans</artifactId> 74 <version>${spring.version}</version> 75 <exclusions> 76 <exclusion> 77 <groupId>org.springframework</groupId> 78 <artifactId>spring-core</artifactId> 79 </exclusion> 80 </exclusions> 81 </dependency> 82 <dependency> 83 <groupId>org.springframework</groupId> 84 <artifactId>spring-test</artifactId> 85 <version>${spring.version}</version> 86 <exclusions> 87 <exclusion> 88 <groupId>org.springframework</groupId> 89 <artifactId>spring-core</artifactId> 90 </exclusion> 91 </exclusions> 92 </dependency> 93 <dependency> 94 <groupId>org.springframework</groupId> 95 <artifactId>spring-web</artifactId> 96 <version>${spring.version}</version> 97 <exclusions> 98 <exclusion> 99 <groupId>org.springframework</groupId> 100 <artifactId>spring-core</artifactId> 101 </exclusion> 102 </exclusions> 103 </dependency> 104 105 <!-- Spring end --> 106 107 <!-- SpringMvc start --> 108 <dependency> 109 <groupId>org.springframework</groupId> 110 <artifactId>spring-webmvc</artifactId> 111 <version>${spring.version}</version> 112 <exclusions> 113 <exclusion> 114 <groupId>org.springframework</groupId> 115 <artifactId>spring-core</artifactId> 116 </exclusion> 117 </exclusions> 118 </dependency> 119 <dependency> 120 <groupId>org.aspectj</groupId> 121 <artifactId>aspectjweaver</artifactId> 122 <version>1.8.2</version> 123 </dependency> 124 <!-- SpringMvc end --> 125 126 <!-- MyBatis start --> 127 <dependency> 128 <groupId>org.mybatis</groupId> 129 <artifactId>mybatis</artifactId> 130 <version>3.1.1</version> 131 </dependency> 132 <dependency> 133 <groupId>org.mybatis</groupId> 134 <artifactId>mybatis-spring</artifactId> 135 <version>1.2.3</version> 136 </dependency> 137 <dependency> 138 <groupId>org.mybatis</groupId> 139 <artifactId>mybatis-ehcache</artifactId> 140 <version>1.0.0</version> 141 </dependency> 142 <!-- MyBatis end --> 143 144 <dependency> 145 <groupId>org.apache.commons</groupId> 146 <artifactId>commons-collections4</artifactId> 147 <version>4.1</version> 148 </dependency> 149 <dependency> 150 <groupId>log4j</groupId> 151 <artifactId>log4j</artifactId> 152 <version>1.2.17</version> 153 </dependency> 154 <dependency> 155 <groupId>org.slf4j</groupId> 156 <artifactId>slf4j-log4j12</artifactId> 157 <version>1.7.7</version> 158 </dependency> 159 <dependency> 160 <groupId>org.slf4j</groupId> 161 <artifactId>slf4j-api</artifactId> 162 <version>1.7.7</version> 163 </dependency> 164 165 <!-- druid --> 166 <dependency> 167 <groupId>com.alibaba</groupId> 168 <artifactId>druid</artifactId> 169 <version>0.2.10</version> 170 </dependency> 171 172 <!-- JDBC MySQL Driver --> 173 <dependency> 174 <groupId>mysql</groupId> 175 <artifactId>mysql-connector-java</artifactId> 176 <version>5.1.21</version> 177 </dependency> 178 179 <!-- Collections --> 180 <dependency> 181 <groupId>commons-collections</groupId> 182 <artifactId>commons-collections</artifactId> 183 <version>3.2</version> 184 </dependency> 185 <dependency> 186 <groupId>commons-fileupload</groupId> 187 <artifactId>commons-fileupload</artifactId> 188 <version>1.3.1</version> 189 </dependency> 190 <dependency> 191 <groupId>commons-io</groupId> 192 <artifactId>commons-io</artifactId> 193 <version>2.4</version> 194 </dependency> 195 <dependency> 196 <groupId>javax.servlet</groupId> 197 <artifactId>servlet-api</artifactId> 198 <version>2.5</version> 199 </dependency> 200 <dependency> 201 <groupId>net.sf.ehcache</groupId> 202 <artifactId>ehcache-core</artifactId> 203 <version>2.6.11</version> 204 </dependency> 205 <dependency> 206 <groupId>commons-logging</groupId> 207 <artifactId>commons-logging</artifactId> 208 <version>1.1.3</version> 209 </dependency> 210 <dependency> 211 <groupId>com.fasterxml.jackson.core</groupId> 212 <artifactId>jackson-annotations</artifactId> 213 <version>2.8.8</version> 214 </dependency> 215 <dependency> 216 <groupId>com.alibaba</groupId> 217 <artifactId>fastjson</artifactId> 218 <version>1.1.15</version> 219 </dependency> 220 <dependency> 221 <groupId>com.fasterxml.jackson.core</groupId> 222 <artifactId>jackson-core</artifactId> 223 <version>2.1.0</version> 224 </dependency> 225 <dependency> 226 <groupId>com.fasterxml.jackson.core</groupId> 227 <artifactId>jackson-databind</artifactId> 228 <version>2.1.0</version> 229 </dependency> 230 <dependency> 231 <groupId>org.apache.httpcomponents</groupId> 232 <artifactId>httpmime</artifactId> 233 <version>4.5.3</version> 234 <exclusions> 235 <exclusion> 236 <groupId>org.apache.httpcomponents</groupId> 237 <artifactId>httpclient</artifactId> 238 </exclusion> 239 </exclusions> 240 </dependency> 241 <!-- <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> 242 <version>4.1.2</version> </dependency> --> 243 <!-- <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> 244 <version>1.2</version> </dependency> --> 245 </dependencies> 246 247 <build> 248 <plugins> 249 <plugin> 250 <groupId>org.apache.maven.plugins</groupId> 251 <artifactId>maven-war-plugin</artifactId> 252 <version>2.6</version> 253 <configuration> 254 <failOnMissingWebXml>true</failOnMissingWebXml> 255 </configuration> 256 </plugin> 257 258 259 <plugin> 260 <groupId>com.maven.plugins</groupId> 261 <artifactId>maven-compiler-plugin</artifactId> 262 <version>6.1.7</version> 263 <configuration> 264 <source>1.7</source> 265 <target>1.7</target> 266 </configuration> 267 </plugin> 268 269 270 </plugins> 271 </build> 272 </project>
web
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > 3 <web-app> 4 <!-- 对标签有顺序要求 --> 5 <!-- 初始化应用上下文 --> 6 <!-- <context-param> <param-name>contextConfigLocation</param-name> <param-value>WEB-INF/classes/spring.xml</param-value> 7 </context-param> --> 8 <context-param> 9 <param-name>contextConfigLocation</param-name> 10 <param-value>classpath*:/spring.xml</param-value> 11 </context-param> 12 13 <filter> 14 <filter-name>characterEncodingFilter</filter-name> 15 <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> 16 <init-param> 17 <param-name>encoding</param-name> 18 <param-value>utf-8</param-value> 19 </init-param> 20 <init-param> 21 <param-name>forceEncoding</param-name> 22 <param-value>true</param-value> 23 </init-param> 24 </filter> 25 <filter-mapping> 26 <filter-name>characterEncodingFilter</filter-name> 27 <url-pattern>/*</url-pattern> 28 </filter-mapping> 29 30 <listener> 31 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 32 </listener> 33 34 35 36 37 <servlet> 38 <servlet-name>Spring Mvc Servlet</servlet-name> 39 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 40 <init-param> 41 <param-name>contextConfigLocation</param-name> 42 <param-value>classpath*:/spring-mvc.xml</param-value> 43 </init-param> 44 <load-on-startup>2</load-on-startup> 45 </servlet> 46 <!-- druid监控 --> 47 <servlet> 48 <servlet-name>DruidStatView</servlet-name> 49 <servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class> 50 </servlet> 51 <servlet-mapping> 52 <servlet-name>Spring Mvc Servlet</servlet-name> 53 <url-pattern>/</url-pattern> 54 </servlet-mapping> 55 56 57 <servlet-mapping> 58 <servlet-name>DruidStatView</servlet-name> 59 <url-pattern>/druid/*</url-pattern> 60 </servlet-mapping> 61 62 63 64 65 66 <!-- 附:web.xml标签放置顺序 67 1. icon? 68 2. display-name? 69 3. description? 70 4. distributable? 71 5. context-param* 72 6. filter* 73 7. filter-mapping* 74 8. listener* 75 9. servlet* 76 10.servlet-mapping* 77 11.session-config? 78 12.mime-mapping* 79 13.welcome-file-list? 80 14.error-page* 81 15.taglib* 82 16.resource-env-ref* 83 17.resource-ref* 84 18.security-constraint* 85 19.login-config? 86 20.security-role* 87 21.env-entry* 88 22.ejb-ref* 89 23.ejb-local-ref 90 "?"表示该标签出现次数最多为1,"*"表示可以多次出现。 --> 91 92 93 </web-app>
3、下面是配置文件从上往下依次贴出
map文件
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > 3 <mapper namespace="com.fh.test.dao.TestNameDao"> 4 <select id="selectUserById" parameterType="int" resultType="com.fh.test.model.User"> 5 <![CDATA[ select id as id,name as name,age as age from name where id=#{id} ]]> 6 </select> 7 8 <insert id="insertUser" parameterType="com.fh.test.model.User" > 9 <![CDATA[ insert into name(id,name,age) value(#{id},#{name},#{age}) ]]> 10 </insert> 11 12 <update id="updateUser" parameterType="com.fh.test.model.User"> 13 <![CDATA[ update name set name=#{name},age=#{age} where id=#{id} ]]> 14 </update> 15 <delete id="deleteUser" parameterType="int" > 16 <![CDATA[ delete from name where id=#{id} ]]> 17 </delete> 18 19 </mapper>
ehcache.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="true" > 4 <diskStore path="java.io.tmpdir" /> 5 6 <defaultCache 7 maxElementsInMemory="500" 8 eternal="false" 9 timeToIdleSeconds="300" 10 timeToLiveSeconds="1200" 11 overflowToDisk="true" /> 12 <!-- name:缓存名称。 13 maxElementsInMemory:缓存最大个数。 14 eternal:对象是否永久有效,一但设置了,timeout将不起作用。 15 timeToIdleSeconds:对象在失效前的允许闲置时间(秒)。当eternal=false时使用,可选属性,默认值是0,也就是可闲置时间无穷大。 16 timeToLiveSeconds:对象在失效前允许存活时间(秒).最大时间介于创建时间和失效时间之间.当eternal=false时使用,默认是0,也就是对象存活时间无穷大。 17 overflowToDisk:当内存中对象数量达到maxElementsInMemory时,Ehcache将对象写到磁盘中。 18 diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。 19 maxElementsOnDisk:硬盘最大缓存个数。 20 diskPersistent:是否缓存虚拟机重启期数据,默认值为false。 21 diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。 22 memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。 23 clearOnFlush:内存数量最大时是否清除。 24 <diskStore>表示当内存缓存中对象数量超过类设置内存缓存数量时,将 缓存对象写到硬盘,path=”java.io.tmpdir”表示把数据写到这个目录下。Java.io.tmpdir目录在运行时会根据相对路径生成。 25 <defaultCache>表示设定缓存的默认数据过期策略。 26 <cache>表示设定用具体的命名缓存的数据过期策略--> 27 <cache 28 name="indexCache" 29 maxElementsInMemory="150" 30 eternal="true" 31 timeToLiveSeconds="0" 32 timeToIdleSeconds="0" 33 overflowToDisk="false"/> 34 <cache 35 name="nationCache" 36 maxElementsInMemory="200" 37 eternal="true" 38 timeToLiveSeconds="0" 39 timeToIdleSeconds="0" 40 overflowToDisk="false"/> 41 </ehcache>
1 <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" version="1.7"> 2 <xs:element name="ehcache"> 3 <xs:complexType> 4 <xs:sequence> 5 <xs:element maxOccurs="1" minOccurs="0" ref="diskStore"/> 6 <xs:element maxOccurs="1" minOccurs="0" ref="sizeOfPolicy"/> 7 <xs:element maxOccurs="1" minOccurs="0" ref="transactionManagerLookup"/> 8 <xs:element maxOccurs="1" minOccurs="0" ref="cacheManagerEventListenerFactory"/> 9 <xs:element maxOccurs="1" minOccurs="0" ref="managementRESTService"/> 10 <xs:element maxOccurs="unbounded" minOccurs="0" ref="cacheManagerPeerProviderFactory"/> 11 <xs:element maxOccurs="unbounded" minOccurs="0" ref="cacheManagerPeerListenerFactory"/> 12 <xs:element maxOccurs="1" minOccurs="0" ref="terracottaConfig"/> 13 <xs:element maxOccurs="1" minOccurs="0" ref="defaultCache"/> 14 <xs:element maxOccurs="unbounded" minOccurs="0" ref="cache"/> 15 </xs:sequence> 16 <xs:attribute name="name" use="optional"/> 17 <xs:attribute default="true" name="updateCheck" type="xs:boolean" use="optional"/> 18 <xs:attribute default="autodetect" name="monitoring" type="monitoringType" use="optional"/> 19 <xs:attribute default="true" name="dynamicConfig" type="xs:boolean" use="optional"/> 20 <xs:attribute default="15" name="defaultTransactionTimeoutInSeconds" type="xs:integer" use="optional"/> 21 <xs:attribute default="0" name="maxBytesLocalHeap" type="memoryUnitOrPercentage" use="optional"/> 22 <xs:attribute default="0" name="maxBytesLocalOffHeap" type="memoryUnit" use="optional"/> 23 <xs:attribute default="0" name="maxBytesLocalDisk" type="memoryUnit" use="optional"/> 24 </xs:complexType> 25 </xs:element> 26 <xs:element name="managementRESTService"> 27 <xs:complexType> 28 <xs:attribute name="enabled" type="xs:boolean" use="optional"/> 29 <xs:attribute name="bind" use="optional"/> 30 <xs:attribute name="securityServiceLocation" use="optional"/> 31 <xs:attribute name="securityServiceTimeout" use="optional" type="xs:integer"/> 32 <xs:attribute name="sslEnabled" use="optional" type="xs:boolean"/> 33 <xs:attribute name="needClientAuth" use="optional" type="xs:boolean"/> 34 <xs:attribute name="sampleHistorySize" use="optional" type="xs:integer"/> 35 <xs:attribute name="sampleIntervalSeconds" use="optional" type="xs:integer"/> 36 <xs:attribute name="sampleSearchIntervalSeconds" use="optional" type="xs:integer"/> 37 </xs:complexType> 38 </xs:element> 39 <xs:element name="diskStore"> 40 <xs:complexType> 41 <xs:attribute name="path" use="optional"/> 42 </xs:complexType> 43 </xs:element> 44 <xs:element name="transactionManagerLookup"> 45 <xs:complexType> 46 <xs:attribute name="class" use="required"/> 47 <xs:attribute name="properties" use="optional"/> 48 <xs:attribute name="propertySeparator" use="optional"/> 49 </xs:complexType> 50 </xs:element> 51 <xs:element name="cacheManagerEventListenerFactory"> 52 <xs:complexType> 53 <xs:attribute name="class" use="required"/> 54 <xs:attribute name="properties" use="optional"/> 55 <xs:attribute name="propertySeparator" use="optional"/> 56 </xs:complexType> 57 </xs:element> 58 <xs:element name="cacheManagerPeerProviderFactory"> 59 <xs:complexType> 60 <xs:attribute name="class" use="required"/> 61 <xs:attribute name="properties" use="optional"/> 62 <xs:attribute name="propertySeparator" use="optional"/> 63 </xs:complexType> 64 </xs:element> 65 <xs:element name="cacheManagerPeerListenerFactory"> 66 <xs:complexType> 67 <xs:attribute name="class" use="required"/> 68 <xs:attribute name="properties" use="optional"/> 69 <xs:attribute name="propertySeparator" use="optional"/> 70 </xs:complexType> 71 </xs:element> 72 <xs:element name="terracottaConfig"> 73 <xs:complexType> 74 <xs:sequence> 75 <xs:element maxOccurs="1" minOccurs="0" name="tc-config"> 76 <xs:complexType> 77 <xs:sequence> 78 <xs:any maxOccurs="unbounded" minOccurs="0" processContents="skip"/> 79 </xs:sequence> 80 </xs:complexType> 81 </xs:element> 82 </xs:sequence> 83 <xs:attribute default="localhost:9510" name="url" use="optional"/> 84 <xs:attribute name="rejoin" type="xs:boolean" use="optional" default="false"/> 85 <xs:attribute name="wanEnabledTSA" type="xs:boolean" use="optional" default="false"/> 86 </xs:complexType> 87 </xs:element> 88 <!-- 89 add clone support for addition of cacheExceptionHandler. Important! 90 --> 91 <xs:element name="defaultCache"> 92 <xs:complexType> 93 <xs:sequence> 94 <xs:element minOccurs="0" maxOccurs="unbounded" ref="cacheEventListenerFactory"/> 95 <xs:element minOccurs="0" maxOccurs="unbounded" ref="cacheExtensionFactory"/> 96 <xs:element minOccurs="0" maxOccurs="unbounded" ref="cacheLoaderFactory"/> 97 <xs:element minOccurs="0" maxOccurs="unbounded" ref="cacheDecoratorFactory"/> 98 <xs:element minOccurs="0" maxOccurs="1" ref="bootstrapCacheLoaderFactory"/> 99 <xs:element minOccurs="0" maxOccurs="1" ref="cacheExceptionHandlerFactory"/> 100 <xs:element minOccurs="0" maxOccurs="1" ref="pinning"/> 101 <xs:element minOccurs="0" maxOccurs="1" ref="terracotta"/> 102 <xs:element minOccurs="0" maxOccurs="1" ref="cacheWriter"/> 103 <xs:element minOccurs="0" maxOccurs="1" ref="copyStrategy"/> 104 <xs:element minOccurs="0" maxOccurs="1" ref="elementValueComparator"/> 105 <xs:element minOccurs="0" maxOccurs="1" ref="sizeOfPolicy"/> 106 <xs:element minOccurs="0" maxOccurs="1" ref="persistence"/> 107 </xs:sequence> 108 <xs:attribute name="diskExpiryThreadIntervalSeconds" type="xs:integer" use="optional"/> 109 <xs:attribute name="diskSpoolBufferSizeMB" type="xs:integer" use="optional"/> 110 <xs:attribute name="diskPersistent" type="xs:boolean" use="optional"/> 111 <xs:attribute name="diskAccessStripes" type="xs:integer" use="optional" default="1"/> 112 <xs:attribute name="eternal" type="xs:boolean" use="optional" default="false"/> 113 <xs:attribute name="maxElementsInMemory" type="xs:nonNegativeInteger" use="optional"/> 114 <xs:attribute name="maxEntriesLocalHeap" type="xs:nonNegativeInteger" use="optional"/> 115 <xs:attribute name="clearOnFlush" type="xs:boolean" use="optional"/> 116 <xs:attribute name="memoryStoreEvictionPolicy" type="xs:string" use="optional"/> 117 <xs:attribute name="overflowToDisk" type="xs:boolean" use="optional"/> 118 <xs:attribute name="timeToIdleSeconds" type="xs:nonNegativeInteger" use="optional"/> 119 <xs:attribute name="timeToLiveSeconds" type="xs:nonNegativeInteger" use="optional"/> 120 <xs:attribute name="maxElementsOnDisk" type="xs:nonNegativeInteger" use="optional"/> 121 <xs:attribute name="maxEntriesLocalDisk" type="xs:nonNegativeInteger" use="optional"/> 122 <xs:attribute name="transactionalMode" type="transactionalMode" use="optional" default="off"/> 123 <xs:attribute name="statistics" type="xs:boolean" use="optional" default="false"/> 124 <xs:attribute name="copyOnRead" type="xs:boolean" use="optional" default="false"/> 125 <xs:attribute name="copyOnWrite" type="xs:boolean" use="optional" default="false"/> 126 <xs:attribute name="cacheLoaderTimeoutMillis" type="xs:integer" use="optional" default="0"/> 127 <xs:attribute name="overflowToOffHeap" type="xs:boolean" use="optional" default="false"/> 128 <xs:attribute name="maxMemoryOffHeap" type="xs:string" use="optional"/> 129 </xs:complexType> 130 </xs:element> 131 <xs:element name="cache"> 132 <xs:complexType> 133 <xs:sequence> 134 <xs:element minOccurs="0" maxOccurs="unbounded" ref="cacheEventListenerFactory"/> 135 <xs:element minOccurs="0" maxOccurs="unbounded" ref="cacheExtensionFactory"/> 136 <xs:element minOccurs="0" maxOccurs="unbounded" ref="cacheLoaderFactory"/> 137 <xs:element minOccurs="0" maxOccurs="unbounded" ref="cacheDecoratorFactory"/> 138 <xs:element minOccurs="0" maxOccurs="1" ref="bootstrapCacheLoaderFactory"/> 139 <xs:element minOccurs="0" maxOccurs="1" ref="cacheExceptionHandlerFactory"/> 140 <xs:element minOccurs="0" maxOccurs="1" ref="pinning"/> 141 <xs:element minOccurs="0" maxOccurs="1" ref="terracotta"/> 142 <xs:element minOccurs="0" maxOccurs="1" ref="cacheWriter"/> 143 <xs:element minOccurs="0" maxOccurs="1" ref="copyStrategy"/> 144 <xs:element minOccurs="0" maxOccurs="1" ref="searchable"/> 145 <xs:element minOccurs="0" maxOccurs="1" ref="elementValueComparator"/> 146 <xs:element minOccurs="0" maxOccurs="1" ref="sizeOfPolicy"/> 147 <xs:element minOccurs="0" maxOccurs="1" ref="persistence"/> 148 </xs:sequence> 149 <xs:attribute name="diskExpiryThreadIntervalSeconds" type="xs:integer" use="optional"/> 150 <xs:attribute name="diskSpoolBufferSizeMB" type="xs:integer" use="optional"/> 151 <xs:attribute name="diskPersistent" type="xs:boolean" use="optional"/> 152 <xs:attribute name="diskAccessStripes" type="xs:integer" use="optional" default="1"/> 153 <xs:attribute name="eternal" type="xs:boolean" use="optional" default="false"/> 154 <xs:attribute name="maxElementsInMemory" type="xs:nonNegativeInteger" use="optional"/> 155 <xs:attribute name="maxEntriesLocalHeap" type="xs:nonNegativeInteger" use="optional"/> 156 <xs:attribute name="memoryStoreEvictionPolicy" type="xs:string" use="optional"/> 157 <xs:attribute name="clearOnFlush" type="xs:boolean" use="optional"/> 158 <xs:attribute name="name" type="xs:string" use="required"/> 159 <xs:attribute name="overflowToDisk" type="xs:boolean" use="optional"/> 160 <xs:attribute name="timeToIdleSeconds" type="xs:nonNegativeInteger" use="optional"/> 161 <xs:attribute name="timeToLiveSeconds" type="xs:nonNegativeInteger" use="optional"/> 162 <xs:attribute name="maxElementsOnDisk" type="xs:nonNegativeInteger" use="optional"/> 163 <xs:attribute name="maxEntriesLocalDisk" type="xs:nonNegativeInteger" use="optional"/> 164 <xs:attribute name="maxEntriesInCache" type="xs:nonNegativeInteger" use="optional"/> 165 <xs:attribute name="transactionalMode" type="transactionalMode" use="optional" default="off"/> 166 <xs:attribute name="statistics" type="xs:boolean" use="optional" default="false"/> 167 <xs:attribute name="copyOnRead" type="xs:boolean" use="optional" default="false"/> 168 <xs:attribute name="copyOnWrite" type="xs:boolean" use="optional" default="false"/> 169 <xs:attribute name="logging" type="xs:boolean" use="optional" default="false"/> 170 <xs:attribute name="cacheLoaderTimeoutMillis" type="xs:integer" use="optional" default="0"/> 171 <xs:attribute name="overflowToOffHeap" type="xs:boolean" use="optional" default="false"/> 172 <xs:attribute name="maxMemoryOffHeap" type="xs:string" use="optional"/> 173 <xs:attribute default="0" name="maxBytesLocalHeap" type="memoryUnitOrPercentage" use="optional"/> 174 <xs:attribute default="0" name="maxBytesLocalOffHeap" type="memoryUnitOrPercentage" use="optional"/> 175 <xs:attribute default="0" name="maxBytesLocalDisk" type="memoryUnitOrPercentage" use="optional"/> 176 </xs:complexType> 177 </xs:element> 178 <xs:element name="cacheEventListenerFactory"> 179 <xs:complexType> 180 <xs:attribute name="class" use="required"/> 181 <xs:attribute name="properties" use="optional"/> 182 <xs:attribute name="propertySeparator" use="optional"/> 183 <xs:attribute name="listenFor" use="optional" type="notificationScope" default="all"/> 184 </xs:complexType> 185 </xs:element> 186 <xs:element name="bootstrapCacheLoaderFactory"> 187 <xs:complexType> 188 <xs:attribute name="class" use="required"/> 189 <xs:attribute name="properties" use="optional"/> 190 <xs:attribute name="propertySeparator" use="optional"/> 191 </xs:complexType> 192 </xs:element> 193 <xs:element name="cacheExtensionFactory"> 194 <xs:complexType> 195 <xs:attribute name="class" use="required"/> 196 <xs:attribute name="properties" use="optional"/> 197 <xs:attribute name="propertySeparator" use="optional"/> 198 </xs:complexType> 199 </xs:element> 200 <xs:element name="cacheExceptionHandlerFactory"> 201 <xs:complexType> 202 <xs:attribute name="class" use="required"/> 203 <xs:attribute name="properties" use="optional"/> 204 <xs:attribute name="propertySeparator" use="optional"/> 205 </xs:complexType> 206 </xs:element> 207 <xs:element name="cacheLoaderFactory"> 208 <xs:complexType> 209 <xs:attribute name="class" use="required"/> 210 <xs:attribute name="properties" use="optional"/> 211 <xs:attribute name="propertySeparator" use="optional"/> 212 </xs:complexType> 213 </xs:element> 214 <xs:element name="cacheDecoratorFactory"> 215 <xs:complexType> 216 <xs:attribute name="class" use="required"/> 217 <xs:attribute name="properties" use="optional"/> 218 <xs:attribute name="propertySeparator" use="optional"/> 219 </xs:complexType> 220 </xs:element> 221 <xs:element name="searchAttribute"> 222 <xs:complexType> 223 <xs:attribute name="name" use="required" type="xs:string"/> 224 <xs:attribute name="expression" type="xs:string"/> 225 <xs:attribute name="class" type="xs:string"/> 226 <xs:attribute name="type" type="xs:string" use="optional"/> 227 <xs:attribute name="properties" use="optional"/> 228 <xs:attribute name="propertySeparator" use="optional"/> 229 </xs:complexType> 230 </xs:element> 231 <xs:element name="searchable"> 232 <xs:complexType> 233 <xs:sequence> 234 <xs:element minOccurs="0" maxOccurs="unbounded" ref="searchAttribute"/> 235 </xs:sequence> 236 <xs:attribute name="keys" use="optional" type="xs:boolean" default="true"/> 237 <xs:attribute name="values" use="optional" type="xs:boolean" default="true"/> 238 <xs:attribute name="allowDynamicIndexing" use="optional" type="xs:boolean" default="false"/> 239 </xs:complexType> 240 </xs:element> 241 <xs:element name="pinning"> 242 <xs:complexType> 243 <xs:attribute name="store" use="required" type="pinningStoreType"/> 244 </xs:complexType> 245 </xs:element> 246 <xs:element name="terracotta"> 247 <xs:complexType> 248 <xs:sequence> 249 <xs:element minOccurs="0" maxOccurs="1" ref="nonstop"/> 250 </xs:sequence> 251 <xs:attribute name="clustered" use="optional" type="xs:boolean" default="true"/> 252 <xs:attribute name="coherentReads" use="optional" type="xs:boolean" default="true"/> 253 <xs:attribute name="localKeyCache" use="optional" type="xs:boolean" default="false"/> 254 <xs:attribute name="localKeyCacheSize" use="optional" type="xs:positiveInteger" default="300000"/> 255 <xs:attribute name="orphanEviction" use="optional" type="xs:boolean" default="true"/> 256 <xs:attribute name="orphanEvictionPeriod" use="optional" type="xs:positiveInteger" default="4"/> 257 <xs:attribute name="copyOnRead" use="optional" type="xs:boolean" default="false"/> 258 <xs:attribute name="coherent" use="optional" type="xs:boolean" default="false"/> 259 <xs:attribute name="consistency" use="optional" type="consistencyType" default="eventual"/> 260 <xs:attribute name="synchronousWrites" use="optional" type="xs:boolean" default="false"/> 261 <xs:attribute name="concurrency" use="optional" type="xs:nonNegativeInteger" default="0"/> 262 <xs:attribute name="localCacheEnabled" use="optional" type="xs:boolean" default="true"/> 263 <xs:attribute name="compressionEnabled" use="optional" type="xs:boolean" default="false"/> 264 </xs:complexType> 265 </xs:element> 266 <xs:simpleType name="consistencyType"> 267 <xs:restriction base="xs:string"> 268 <xs:enumeration value="strong"/> 269 <xs:enumeration value="eventual"/> 270 </xs:restriction> 271 </xs:simpleType> 272 <xs:element name="nonstop"> 273 <xs:complexType> 274 <xs:sequence> 275 <xs:element minOccurs="0" maxOccurs="1" ref="timeoutBehavior"/> 276 </xs:sequence> 277 <xs:attribute name="enabled" use="optional" type="xs:boolean" default="true"/> 278 <xs:attribute name="immediateTimeout" use="optional" type="xs:boolean" default="false"/> 279 <xs:attribute name="timeoutMillis" use="optional" type="xs:positiveInteger" default="30000"/> 280 <xs:attribute name="searchTimeoutMillis" use="optional" type="xs:positiveInteger" default="30000"/> 281 </xs:complexType> 282 </xs:element> 283 <xs:element name="timeoutBehavior"> 284 <xs:complexType> 285 <xs:attribute name="type" use="optional" type="timeoutBehaviorType" default="exception"/> 286 <xs:attribute name="properties" use="optional" default=""/> 287 <xs:attribute name="propertySeparator" use="optional" default=","/> 288 </xs:complexType> 289 </xs:element> 290 <xs:simpleType name="timeoutBehaviorType"> 291 <xs:restriction base="xs:string"> 292 <xs:enumeration value="noop"/> 293 <xs:enumeration value="exception"/> 294 <xs:enumeration value="localReads"/> 295 <xs:enumeration value="localReadsAndExceptionOnWrite"/> 296 </xs:restriction> 297 </xs:simpleType> 298 <xs:simpleType name="monitoringType"> 299 <xs:restriction base="xs:string"> 300 <xs:enumeration value="autodetect"/> 301 <xs:enumeration value="on"/> 302 <xs:enumeration value="off"/> 303 </xs:restriction> 304 </xs:simpleType> 305 <xs:simpleType name="pinningStoreType"> 306 <xs:restriction base="xs:string"> 307 <xs:enumeration value="localMemory"/> 308 <xs:enumeration value="inCache"/> 309 </xs:restriction> 310 </xs:simpleType> 311 <xs:simpleType name="terracottaCacheValueType"> 312 <xs:restriction base="xs:string"> 313 <xs:enumeration value="serialization"/> 314 <xs:enumeration value="identity"/> 315 </xs:restriction> 316 </xs:simpleType> 317 <xs:simpleType name="transactionalMode"> 318 <xs:restriction base="xs:string"> 319 <xs:enumeration value="off"/> 320 <xs:enumeration value="xa_strict"/> 321 <xs:enumeration value="xa"/> 322 <xs:enumeration value="local"/> 323 </xs:restriction> 324 </xs:simpleType> 325 <xs:element name="cacheWriter"> 326 <xs:complexType> 327 <xs:sequence> 328 <xs:element minOccurs="0" maxOccurs="1" ref="cacheWriterFactory"/> 329 </xs:sequence> 330 <xs:attribute name="writeMode" use="optional" type="writeModeType" default="write-through"/> 331 <xs:attribute name="notifyListenersOnException" use="optional" type="xs:boolean" default="false"/> 332 <xs:attribute name="minWriteDelay" use="optional" type="xs:nonNegativeInteger" default="1"/> 333 <xs:attribute name="maxWriteDelay" use="optional" type="xs:nonNegativeInteger" default="1"/> 334 <xs:attribute name="rateLimitPerSecond" use="optional" type="xs:nonNegativeInteger" default="0"/> 335 <xs:attribute name="writeCoalescing" use="optional" type="xs:boolean" default="false"/> 336 <xs:attribute name="writeBatching" use="optional" type="xs:boolean" default="false"/> 337 <xs:attribute name="writeBatchSize" use="optional" type="xs:positiveInteger" default="1"/> 338 <xs:attribute name="retryAttempts" use="optional" type="xs:nonNegativeInteger" default="0"/> 339 <xs:attribute name="retryAttemptDelaySeconds" use="optional" type="xs:nonNegativeInteger" default="1"/> 340 <xs:attribute name="writeBehindConcurrency" use="optional" type="xs:nonNegativeInteger" default="1"/> 341 <xs:attribute name="writeBehindMaxQueueSize" use="optional" type="xs:nonNegativeInteger" default="0"/> 342 </xs:complexType> 343 </xs:element> 344 <xs:simpleType name="writeModeType"> 345 <xs:restriction base="xs:string"> 346 <xs:enumeration value="write-through"/> 347 <xs:enumeration value="write-behind"/> 348 </xs:restriction> 349 </xs:simpleType> 350 <xs:element name="cacheWriterFactory"> 351 <xs:complexType> 352 <xs:attribute name="class" use="required"/> 353 <xs:attribute name="properties" use="optional"/> 354 <xs:attribute name="propertySeparator" use="optional"/> 355 </xs:complexType> 356 </xs:element> 357 <xs:element name="copyStrategy"> 358 <xs:complexType> 359 <xs:attribute name="class" use="required" type="xs:string"/> 360 </xs:complexType> 361 </xs:element> 362 <xs:element name="elementValueComparator"> 363 <xs:complexType> 364 <xs:attribute name="class" use="required" type="xs:string"/> 365 </xs:complexType> 366 </xs:element> 367 <xs:element name="sizeOfPolicy"> 368 <xs:complexType> 369 <xs:attribute name="maxDepth" use="required" type="xs:integer"/> 370 <xs:attribute name="maxDepthExceededBehavior" use="optional" default="continue" type="maxDepthExceededBehavior"/> 371 </xs:complexType> 372 </xs:element> 373 <xs:element name="persistence"> 374 <xs:complexType> 375 <xs:attribute name="strategy" use="required" type="persistenceStrategy"/> 376 <xs:attribute name="synchronousWrites" use="optional" default="false" type="xs:boolean"/> 377 </xs:complexType> 378 </xs:element> 379 <xs:simpleType name="persistenceStrategy"> 380 <xs:restriction base="xs:string"> 381 <xs:enumeration value="localTempSwap"/> 382 <xs:enumeration value="localRestartable"/> 383 <xs:enumeration value="none"/> 384 <xs:enumeration value="distributed"/> 385 </xs:restriction> 386 </xs:simpleType> 387 <xs:simpleType name="maxDepthExceededBehavior"> 388 <xs:restriction base="xs:string"> 389 <xs:enumeration value="continue"/> 390 <xs:enumeration value="abort"/> 391 </xs:restriction> 392 </xs:simpleType> 393 <xs:simpleType name="notificationScope"> 394 <xs:restriction base="xs:string"> 395 <xs:enumeration value="local"/> 396 <xs:enumeration value="remote"/> 397 <xs:enumeration value="all"/> 398 </xs:restriction> 399 </xs:simpleType> 400 <xs:simpleType name="memoryUnit"> 401 <xs:restriction base="xs:token"> 402 <xs:pattern value="[0-9]+[bBkKmMgG]?"/> 403 </xs:restriction> 404 </xs:simpleType> 405 <xs:simpleType name="memoryUnitOrPercentage"> 406 <xs:restriction base="xs:token"> 407 <xs:pattern value="([0-9]+[bBkKmMgG]?|100%|[0-9]{1,2}%)"/> 408 </xs:restriction> 409 </xs:simpleType> 410 </xs:schema>
上面这个没看过,是直接复制过来的
jdbc
1 jdbc.driverClassName=com.mysql.jdbc.Driver 2 jdbc.url=jdbc:mysql://127.0.0.1:3306/test 3 jdbc.username=fenghao 4 jdbc.password=123456 5 jdbc.fetch_size=50
log4g
1 #log4j.rootLogger=INFO,ROLLING_FILE 2 log4j.rootLogger=INFO,CONSOLE,ROLLING_FILE 3 4 ################## 5 #Console Appender 6 ################## 7 log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender 8 log4j.appender.Threshold=INFO 9 log4j.appender.CONSOLE.Target=System.out 10 log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout 11 log4j.appender.CONSOLE.layout.ConversionPattern= [%p] %d %c - %m%n 12 13 ######################## 14 # Rolling File 15 ######################## 16 log4j.appender.ROLLING_FILE=org.apache.log4j.DailyRollingFileAppender 17 log4j.appender.ROLLING_FILE.Threshold=INFO 18 log4j.appender.ROLLING_FILE.File=/app/log/spring-test.log 19 log4j.appender.ROLLING_FILE.Append=true 20 log4j.appender.ROLLING_FILE.layout=org.apache.log4j.PatternLayout 21 log4j.appender.ROLLING_FILE.layout.ConversionPattern=%d{yyyy-M-d HH:mm:ss}%x[%5p](%F:%L) %m%n 22 23 24 25 log4j.logger.org.springframework.aop.interceptor = ALL 26 27 ##show the mysql for mybatis 28 log4j.logger.com.ibatis=ALL 29 log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=ALL 30 log4j.logger.com.ibatis.common.jdbc.ScriptRunner=ALL 31 log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=ALL 32 log4j.logger.java.sql.Connection=ALL 33 log4j.logger.java.sql.Statement=ALL 34 log4j.logger.java.sql.PreparedStatement=ALL 35 36 log4j.logger.org.springframework.aop.interceptor.PerformanceMonitorInterceptor = TRACE 37 log4j.logger.com.fh.test.controller=ALL 38 log4j.logger.com.fh.test.service.impl=ALL 39 log4j.logger.com.fh.test.aspect=ALL
spring-mvc
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" xmlns:mvc="http://www.springframework.org/schema/mvc" 5 xsi:schemaLocation=" 6 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 11 <context:component-scan base-package="com.fh.test.controller" 12 use-default-filters="true"> 13 </context:component-scan> 14 15 <!-- 配置视图解析器 --> 16 17 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 18 <property name="prefix" value="/WEB-INF/views/"></property> 19 <property name="suffix" value=".jsp"></property> 20 </bean> 21 </beans>
spring
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" xmlns:p="http://www.springframework.org/schema/p" 4 xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" 5 xmlns:context="http://www.springframework.org/schema/context" 6 xmlns:cache="http://www.springframework.org/schema/cache" 7 xsi:schemaLocation=" 8 http://www.springframework.org/schema/beans 9 http://www.springframework.org/schema/beans/spring-beans-4.0.xsd 10 http://www.springframework.org/schema/context 11 http://www.springframework.org/schema/context/spring-context-4.0.xsd 12 http://www.springframework.org/schema/tx 13 http://www.springframework.org/schema/tx/spring-tx-4.0.xsd 14 http://www.springframework.org/schema/aop 15 http://www.springframework.org/schema/aop/spring-aop-4.0.xsd 16 http://www.springframework.org/schema/cache 17 http://www.springframework.org/schema/cache/spring-cache.xsd 18 "> 19 20 <context:property-placeholder location="classpath*:druid.properties" ignore-resource-not-found="true"/> 21 22 <context:property-placeholder location="classpath*:jdbc.properties" ignore-resource-not-found="true"/> 23 24 <context:annotation-config/> 25 <context:component-scan base-package="com.fh.test.dao,com.fh.test.service,com.fh.test.aspect" 26 use-default-filters="true"> 27 </context:component-scan> 28 29 30 <cache:annotation-driven /> 31 <!-- 基于Ehcache 开始 --> 32 <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager" 33 p:cacheManager-ref="ehcacheManager" /> 34 <bean id="ehcacheManager" 35 class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" 36 p:configLocation="classpath:ehcache.xml" /> 37 <!-- Ehcache 结束 --> 38 <!--设置缓存管理器end --> 39 40 41 <!-- 数据库配置 --> 42 <!-- 配置数据源 --> 43 <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> 44 <property name="driverClassName" value="com.mysql.jdbc.Driver"/> 45 <property name="url" value="jdbc:mysql://127.0.0.1:3306/test"/> 46 <property name="username" value="fenghao"/> 47 <property name="password" value="123456"/> 48 49 <!-- 配置初始化大小、最小、最大 --> 50 <!-- <property name="initialSize" value="10"/> 51 <property name="minIdle" value="${druid.minIdle}"/> 52 <property name="maxActive" value="${druid.maxActive}"/> --> 53 54 <!-- 配置获取连接等待超时的时间 55 <property name="maxWait" value="${druid.maxWait}"/> --> 56 57 <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 58 <property name="timeBetweenEvictionRunsMillis" value="${druid.timeBetweenEvictionRunsMillis}"/> --> 59 60 <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 61 <property name="minEvictableIdleTimeMillis" value="${druid.minEvictableIdleTimeMillis}"/> --> 62 63 <!-- <property name="validationQuery" value="${druid.validationQuery}"/> 64 <property name="testWhileIdle" value="${druid.testWhileIdle}"/> 65 <property name="testOnBorrow" value="${druid.testOnBorrow}"/> 66 <property name="testOnReturn" value="${druid.testOnReturn}"/> --> 67 68 <!-- 打开PSCache,并且指定每个连接上PSCache的大小(Oracle使用) --> 69 <!-- <property name="poolPreparedStatements" value="true" /> 70 <property name="maxPoolPreparedStatementPerConnectionSize" value="20" /> --> 71 72 <!-- 配置监控统计拦截的filters --> 73 <property name="filters" value="stat"/> 74 </bean> 75 <!-- 加载model类和映射文件 --> 76 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> 77 <property name="dataSource" ref="dataSource"></property> 78 <property name="mapperLocations" value="classpath*:/mapping/*.xml"></property> 79 <property name="typeAliasesPackage" value="com.fh.test.model"></property> 80 </bean> 81 82 <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> 83 <property name="basePackage" value="com.fh.test.dao"></property> 84 <property name="sqlSessionFactory" ref="sqlSessionFactory"></property> 85 </bean> 86 <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> 87 <property name="dataSource" ref="dataSource"> 88 </property> 89 </bean> 90 <tx:advice id="txAdvice" transaction-manager="transactionManager"> 91 <tx:attributes> 92 <tx:method name="insert*" propagation="REQUIRED"/> 93 <tx:method name="updat*" propagation="REQUIRED"/> 94 <tx:method name="delete" propagation="REQUIRED"/> 95 <!-- <tx:method name="*" propagation="REQUIRED" read-only="true"/> --> 96 </tx:attributes> 97 </tx:advice> 98 <aop:config> 99 <aop:pointcut expression="execution(* com.fh.test.service.impl.*.*(..))" id="txpointcut"/> 100 <aop:advisor advice-ref="txAdvice" pointcut-ref="txpointcut"/> 101 </aop:config> 102 103 <!-- true 表示强制使用cglib代理 --> 104 <aop:aspectj-autoproxy /> 105 106 107 <bean id="test" class="com.fh.test.aspect.TestAspect"></bean> 108 109 <aop:config> 110 <aop:pointcut expression="execution(* com.fh.test.service.TestService.test(String)) and args(key)" id="pio"/> 111 <aop:aspect ref="test"> 112 <aop:before method="before" pointcut-ref="pio"/> 113 <aop:around method="after" pointcut-ref="pio"/> 114 </aop:aspect> 115 </aop:config> 116 117 <!--性能监控开始--> 118 <bean id="performanceMonitor" 119 class="org.springframework.aop.interceptor.PerformanceMonitorInterceptor"> 120 </bean> 121 <!-- 性能监控的切面配置 --> 122 <aop:config> 123 <aop:pointcut id="allServiceMethods" 124 expression="execution(* com.fh.test.service.impl.*.*(..))"/> 125 <aop:advisor pointcut-ref="allServiceMethods" advice-ref="performanceMonitor" 126 order="2"/> 127 </aop:config> 128 <!--性能监控结束--> 129 130 131 132 <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> 133 <property name="messageConverters"> 134 <list> 135 <ref bean="jsonConverter" /> 136 </list> 137 </property> 138 </bean> 139 140 <bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> 141 <property name="supportedMediaTypes" value="application/json" /> 142 </bean> 143 </beans>
4、下面是src/main/java下的代码
aspect
1 package com.fh.test.aspect; 2 3 import org.aspectj.lang.ProceedingJoinPoint; 4 import org.aspectj.lang.annotation.After; 5 import org.aspectj.lang.annotation.Around; 6 import org.aspectj.lang.annotation.Aspect; 7 import org.aspectj.lang.annotation.Before; 8 import org.aspectj.lang.annotation.Pointcut; 9 import org.slf4j.Logger; 10 import org.slf4j.LoggerFactory; 11 import org.springframework.stereotype.Service; 12 13 14 15 public class TestAspect { 16 private static final Logger logger=LoggerFactory.getLogger(TestAspect.class); 17 18 /*@Pointcut("execution(* com.fh.test.service.TestService.test(String) && args(key))") 19 public void test(String key){}; 20 21 @Before("test(key)") 22 public void before(String key){ 23 logger.debug("this is Aspect key is {}",key); 24 } 25 26 @Around("test(key)") 27 public void after(ProceedingJoinPoint jp){ 28 try { 29 Object proceed = jp.proceed(); 30 logger.debug("this is Aspect return is {}",proceed.toString()); 31 } catch (Throwable e) { 32 e.printStackTrace(); 33 } 34 }*/ 35 36 37 38 39 public void before(String key){ 40 logger.debug("this is Aspect before key{}",key); 41 } 42 43 44 public Object after(ProceedingJoinPoint jp,String key){ 45 Object proceed=null; 46 try { 47 proceed = jp.proceed(); 48 logger.debug("this is Aspect return is {}",proceed.toString()); 49 return proceed; 50 } catch (Throwable e) { 51 e.printStackTrace(); 52 return proceed; 53 } 54 } 55 56 }
controller
1 package com.fh.test.controller; 2 3 import java.io.IOException; 4 5 import javax.servlet.ServletInputStream; 6 import javax.servlet.http.HttpServletRequest; 7 import javax.servlet.http.HttpServletResponse; 8 9 import org.apache.commons.io.IOUtils; 10 import org.slf4j.Logger; 11 import org.slf4j.LoggerFactory; 12 import org.springframework.beans.factory.annotation.Autowired; 13 import org.springframework.beans.factory.annotation.Qualifier; 14 import org.springframework.beans.factory.annotation.Value; 15 import org.springframework.stereotype.Controller; 16 import org.springframework.web.bind.annotation.RequestMapping; 17 import org.springframework.web.bind.annotation.RequestMethod; 18 import org.springframework.web.bind.annotation.RequestParam; 19 import org.springframework.web.bind.annotation.ResponseBody; 20 21 import com.alibaba.fastjson.JSONObject; 22 import com.fasterxml.jackson.annotation.JsonPropertyOrder; 23 import com.fh.test.model.User; 24 import com.fh.test.service.TestService; 25 26 @Controller 27 public class ControllerTest { 28 29 private static final Logger logger=LoggerFactory.getLogger(ControllerTest.class); 30 31 @Autowired 32 @Qualifier("testServiceImpl") 33 private TestService test; 34 35 @Value("${test-value}") 36 private String testValue; 37 38 @RequestMapping(value="/test/t",method=RequestMethod.POST) 39 @ResponseBody 40 public String test(@RequestParam(value="id")String id){ 41 User user = test.getUserName(id); 42 logger.debug(" woo!!! {}",testValue); 43 return user.toString(); 44 } 45 46 @RequestMapping(value="/test/insert",method=RequestMethod.POST) 47 @ResponseBody 48 public String insert(HttpServletRequest request, HttpServletResponse response){ 49 String message=null; 50 try { 51 ServletInputStream inputStream = request.getInputStream(); 52 message = IOUtils.toString(inputStream); 53 } catch (IOException e) { 54 logger.error(" IO Excepation"); 55 e.printStackTrace(); 56 } 57 logger.debug("message is "+message); 58 User parse = JSONObject.parseObject(message, User.class); 59 int state = test.insertName(parse); 60 return String.valueOf(state); 61 } 62 63 @RequestMapping(value="/test/update",method=RequestMethod.POST) 64 @ResponseBody 65 public String update(HttpServletRequest request, HttpServletResponse response){ 66 String message=null; 67 try { 68 ServletInputStream inputStream = request.getInputStream(); 69 message = IOUtils.toString(inputStream); 70 } catch (IOException e) { 71 logger.error(" IO Excepation"); 72 e.printStackTrace(); 73 } 74 logger.debug("message is "+message); 75 User parse = JSONObject.parseObject(message, User.class); 76 int updateName = test.updateName(parse); 77 return String.valueOf(updateName); 78 } 79 80 @RequestMapping(value="/test/delete",method=RequestMethod.POST) 81 @ResponseBody 82 public String delete(@RequestParam(value="id")String id){ 83 logger.debug("id {}",id); 84 int deleteName = test.deleteName(Integer.parseInt(id)); 85 return String.valueOf(deleteName); 86 } 87 88 @RequestMapping(value="/test/asp",method=RequestMethod.POST) 89 @ResponseBody 90 public String testAsp(@RequestParam(value="key")String key){ 91 logger.debug("this is Controller"); 92 return test.test(key); 93 } 94 95 @RequestMapping(value="/*") 96 public String index(){ 97 return "index"; 98 } 99 }
1 package com.fh.test.controller; 2 3 import org.springframework.beans.factory.annotation.Autowired; 4 import org.springframework.beans.factory.annotation.Qualifier; 5 import org.springframework.http.HttpStatus; 6 import org.springframework.http.ResponseEntity; 7 import org.springframework.web.bind.annotation.RequestBody; 8 import org.springframework.web.bind.annotation.RequestMapping; 9 import org.springframework.web.bind.annotation.RequestMethod; 10 import org.springframework.web.bind.annotation.ResponseBody; 11 import org.springframework.web.client.HttpStatusCodeException; 12 13 import com.fh.test.model.User; 14 import com.fh.test.service.TestService; 15 16 @org.springframework.web.bind.annotation.RestController 17 @RequestMapping(value="/rest") 18 public class RestController { 19 20 @Autowired 21 @Qualifier("testServiceImpl") 22 private TestService test; 23 24 @RequestMapping(value="/r",method=RequestMethod.POST) 25 public ResponseEntity<User> rest(@RequestBody User user){ 26 int insertName = test.insertName(user); 27 HttpStatus status=null; 28 if(insertName==1){ 29 status=HttpStatus.OK; 30 }else{ 31 status=HttpStatus.NOT_FOUND; 32 } 33 return new ResponseEntity<User>(user,status); 34 } 35 36 37 }
1 package com.fh.test.controller; 2 3 import java.io.File; 4 import java.io.FileOutputStream; 5 import java.io.IOException; 6 import java.io.InputStream; 7 import java.io.OutputStream; 8 import java.io.UnsupportedEncodingException; 9 import java.util.Enumeration; 10 import java.util.Iterator; 11 import java.util.List; 12 import java.util.Map; 13 import java.util.Set; 14 15 import javax.servlet.http.HttpServletRequest; 16 import javax.servlet.http.HttpServletResponse; 17 18 import org.apache.commons.fileupload.FileItem; 19 import org.apache.commons.fileupload.FileItemFactory; 20 import org.apache.commons.fileupload.FileItemIterator; 21 import org.apache.commons.fileupload.FileUploadException; 22 import org.apache.commons.fileupload.disk.DiskFileItemFactory; 23 import org.apache.commons.fileupload.servlet.ServletFileUpload; 24 import org.apache.commons.io.IOUtils; 25 import org.slf4j.Logger; 26 import org.slf4j.LoggerFactory; 27 import org.springframework.stereotype.Controller; 28 import org.springframework.web.bind.ServletRequestBindingException; 29 import org.springframework.web.bind.ServletRequestUtils; 30 import org.springframework.web.bind.annotation.RequestMapping; 31 import org.springframework.web.bind.annotation.RequestMethod; 32 import org.springframework.web.bind.annotation.ResponseBody; 33 34 @Controller 35 @RequestMapping(value="/test") 36 public class UploadController { 37 38 private final static Logger logger=LoggerFactory.getLogger(UploadController.class); 39 40 /** 41 * 使用common-fileupload.jar处理上传文件 42 * @param request 43 * @param response 44 * @return 45 * @throws IOException 46 */ 47 @RequestMapping(value="/upload") 48 public String upload(HttpServletRequest request,HttpServletResponse response) throws IOException{ 49 if(ServletFileUpload.isMultipartContent(request)){ 50 FileItemFactory factory=new DiskFileItemFactory(); 51 ServletFileUpload upload=new ServletFileUpload(factory); 52 try { 53 List<FileItem> fileItem = upload.parseRequest(request); 54 Iterator<FileItem> iterator = fileItem.iterator(); 55 while(iterator.hasNext()){ 56 FileItem next = iterator.next(); 57 if(next.isFormField()){ 58 59 logger.error(next.getFieldName()); 60 InputStream is = next.getInputStream(); 61 String string = IOUtils.toString(is); 62 logger.error(" value {}",string); 63 logger.error(next.getName()); 64 logger.error(next.getContentType()); 65 logger.error(next.getSize()+""); 66 logger.error(next.isInMemory()+""); 67 }else{ 68 logger.error(next.getFieldName()); 69 logger.error(next.getName()); 70 logger.error(next.getContentType()); 71 logger.error(next.getSize()+""); 72 logger.error(next.isInMemory()+""); 73 InputStream inputStream = next.getInputStream(); 74 OutputStream out=new FileOutputStream(new File("/app/aaa.png")); 75 out.write(IOUtils.toByteArray(inputStream)); 76 } 77 } 78 } catch (FileUploadException e) { 79 e.printStackTrace(); 80 } 81 82 83 } 84 return null; 85 } 86 87 88 @RequestMapping(value="/file",method=RequestMethod.POST) 89 @ResponseBody 90 public String uploadFile(HttpServletRequest request,HttpServletResponse response){ 91 String parameter = request.getParameter("file"); 92 logger.error(parameter); 93 return "OK"; 94 95 } 96 }
dao
1 package com.fh.test.dao; 2 3 import java.util.List; 4 5 import org.apache.ibatis.annotations.Select; 6 import org.springframework.stereotype.Repository; 7 8 import com.fh.test.model.User; 9 10 @Repository("testDao") 11 public interface TestNameDao { 12 13 String SELECT_USER_BY_ID="select id as id,name as name,age as age from name where id=#{id}"; 14 15 // @Select(SELECT_USER_BY_ID) 16 public List<User> selectUserById(int id); 17 18 public int insertUser(User user); 19 20 public int updateUser(User user); 21 22 public int deleteUser(int id); 23 24 }
excetors
1 package com.fh.test.excetors; 2 3 import java.util.concurrent.Callable; 4 import java.util.concurrent.Executors; 5 import java.util.concurrent.ScheduledExecutorService; 6 import java.util.concurrent.TimeUnit; 7 8 import org.apache.log4j.chainsaw.Main; 9 10 public class ThreadPoolTest { 11 12 public static void main(String[] args) { 13 ScheduledExecutorService service = Executors.newScheduledThreadPool(10); 14 task ta=new task(); 15 service.scheduleWithFixedDelay(ta, 10, 10,TimeUnit.SECONDS); 16 } 17 } 18 class task implements Runnable{ 19 20 @Override 21 public void run() { 22 System.out.println("开始了!!!"); 23 } 24 25 }
model
1 package com.fh.test.model.adapter; 2 3 import java.text.SimpleDateFormat; 4 import java.util.Date; 5 6 import javax.xml.bind.annotation.adapters.XmlAdapter; 7 8 public class DateTypeAdapter extends XmlAdapter<String, Date> { 9 10 private ThreadLocal<SimpleDateFormat> local=new ThreadLocal<SimpleDateFormat>(); 11 12 public DateTypeAdapter(){ 13 SimpleDateFormat format = local.get(); 14 if(format==null){ 15 local.set(new SimpleDateFormat("yyyy-MM-dd hh:MM:ss")); 16 } 17 } 18 19 @Override 20 public Date unmarshal(String v) throws Exception { 21 SimpleDateFormat format = local.get(); 22 return format.parse(v); 23 } 24 25 @Override 26 public String marshal(Date v) throws Exception { 27 SimpleDateFormat format = local.get(); 28 return format.format(v); 29 } 30 31 }
1 package com.fh.test.model.adapter; 2 3 import javax.xml.bind.annotation.XmlAccessType; 4 import javax.xml.bind.annotation.XmlAccessorType; 5 import javax.xml.bind.annotation.XmlAttribute; 6 import javax.xml.bind.annotation.XmlValue; 7 8 @XmlAccessorType(XmlAccessType.FIELD) 9 public class KeyValue { 10 11 @XmlAttribute(name="key") 12 private String key; 13 14 @XmlValue 15 private String value; 16 17 public String getKey() { 18 return key; 19 } 20 21 public void setKey(String key) { 22 this.key = key; 23 } 24 25 public String getValue() { 26 return value; 27 } 28 29 public void setValue(String value) { 30 this.value = value; 31 } 32 33 public KeyValue(String key, String value) { 34 super(); 35 this.key = key; 36 this.value = value; 37 } 38 39 public KeyValue() { 40 super(); 41 // TODO Auto-generated constructor stub 42 } 43 44 45 }
1 package com.fh.test.model.adapter; 2 3 import java.util.HashMap; 4 import java.util.List; 5 import java.util.Map; 6 7 import javax.xml.bind.annotation.adapters.XmlAdapter; 8 9 import com.fh.test.model.adapter.MapConvertor.MapEntry; 10 11 public class MapAdater extends XmlAdapter<MapConvertor, Map<String,String>> { 12 13 @Override 14 public Map<String, String> unmarshal(MapConvertor v) throws Exception { 15 List<MapEntry> entry = v.getEntry(); 16 if(entry!=null && entry.size()>0){ 17 Map<String,String> data=new HashMap<String,String>(); 18 for (MapEntry en : entry) { 19 data.put(en.getKey(), en.getValue()); 20 } 21 return data; 22 } 23 return null; 24 } 25 26 @Override 27 public MapConvertor marshal(Map<String, String> v) throws Exception { 28 MapConvertor con=new MapConvertor(); 29 for (Map.Entry<String, String> en : v.entrySet()) { 30 con.addEntry(new MapConvertor.MapEntry(en)); 31 } 32 return con; 33 } 34 35 }
1 package com.fh.test.model.adapter; 2 3 import java.util.ArrayList; 4 import java.util.List; 5 import java.util.Map; 6 7 import javax.xml.bind.annotation.XmlAccessType; 8 import javax.xml.bind.annotation.XmlAccessorType; 9 import javax.xml.bind.annotation.XmlType; 10 11 @XmlType(name="MapConvertor") 12 @XmlAccessorType(XmlAccessType.FIELD) 13 public class MapConvertor { 14 15 private List<MapEntry> entries=new ArrayList<MapConvertor.MapEntry>(){ 16 17 }; 18 19 public void addEntry(MapEntry entry){ 20 entries.add(entry); 21 } 22 23 public List<MapEntry> getEntry(){ 24 return entries; 25 } 26 /** 27 * 静态内部类 28 * @author fenghao 29 * 30 */ 31 public static class MapEntry{ 32 private String key; 33 private String value; 34 public String getKey() { 35 return key; 36 } 37 public void setKey(String key) { 38 this.key = key; 39 } 40 public String getValue() { 41 return value; 42 } 43 public void setValue(String value) { 44 this.value = value; 45 } 46 public MapEntry(String key, String value) { 47 super(); 48 this.key = key; 49 this.value = value; 50 } 51 public MapEntry() { 52 super(); 53 } 54 public MapEntry(Map.Entry<String, String> entry) { 55 this.key = entry.getKey(); 56 this.value = entry.getValue(); 57 } 58 } 59 60 }
1 package com.fh.test.model; 2 3 import java.util.Date; 4 import java.util.List; 5 import java.util.Map; 6 7 import javax.xml.bind.annotation.XmlAccessType; 8 import javax.xml.bind.annotation.XmlAccessorType; 9 import javax.xml.bind.annotation.XmlElement; 10 import javax.xml.bind.annotation.XmlElementWrapper; 11 import javax.xml.bind.annotation.XmlRootElement; 12 import javax.xml.bind.annotation.XmlType; 13 import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; 14 import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapters; 15 16 import com.fh.test.model.adapter.DateTypeAdapter; 17 import com.fh.test.model.adapter.KeyValue; 18 import com.fh.test.model.adapter.MapAdater; 19 20 /** 21 * @XmlTransient 注释对于解决 JavaBean 属性名称与字段名称之间的名称冲突,或者用于防止字段/属性的映射。 22 * @author fenghao 23 * 24 *@XmlJavaTypeAdapter(class) 25 用来描述自定义的adapter,需要继承XmlAdapter,用来对自定义序列化的格式。如我们对时间的格式化输出 26 */ 27 @XmlAccessorType(XmlAccessType.FIELD) 28 @XmlRootElement(name="name") 29 @XmlType(propOrder={"id","name","age","sex","list","data","order","date","keyValue"}) 30 public class Name { 31 32 @XmlElement(name="id") 33 private String id; 34 35 @XmlElement(name="name") 36 private String name; 37 38 @XmlElement(name="age") 39 private String age; 40 41 @XmlElement(name="sex") 42 private String sex; 43 44 @XmlElementWrapper(name="lists") 45 @XmlElement(name="list") 46 private List<String> list; 47 48 @XmlJavaTypeAdapter(value=MapAdater.class) 49 private Map<String,String> data; 50 51 52 @XmlElement(name="order",type=Order.class) 53 private Order order; 54 55 @XmlJavaTypeAdapter(value = DateTypeAdapter.class) 56 private Date date; 57 58 @XmlElement(name="key",type=KeyValue.class) 59 private KeyValue keyValue; 60 61 public String getId() { 62 return id; 63 } 64 65 public void setId(String id) { 66 this.id = id; 67 } 68 69 public String getName() { 70 return name; 71 } 72 73 public void setName(String name) { 74 this.name = name; 75 } 76 77 public String getAge() { 78 return age; 79 } 80 81 public void setAge(String age) { 82 this.age = age; 83 } 84 85 public String getSex() { 86 return sex; 87 } 88 89 public void setSex(String sex) { 90 this.sex = sex; 91 } 92 93 public List<String> getList() { 94 return list; 95 } 96 97 public void setList(List<String> list) { 98 this.list = list; 99 } 100 101 public Map<String, String> getData() { 102 return data; 103 } 104 105 public void setData(Map<String, String> data) { 106 this.data = data; 107 } 108 109 public Order getOrder() { 110 return order; 111 } 112 113 public void setOrder(Order order) { 114 this.order = order; 115 } 116 117 public Date getDate() { 118 return date; 119 } 120 121 public void setDate(Date date) { 122 this.date = date; 123 } 124 125 public KeyValue getKeyValue() { 126 return keyValue; 127 } 128 129 public void setKeyValue(KeyValue keyValue) { 130 this.keyValue = keyValue; 131 } 132 133 public Name(String id, String name, String age, String sex, List<String> list, Map<String, String> data, 134 Order order, Date date, KeyValue keyValue) { 135 super(); 136 this.id = id; 137 this.name = name; 138 this.age = age; 139 this.sex = sex; 140 this.list = list; 141 this.data = data; 142 this.order = order; 143 this.date = date; 144 this.keyValue = keyValue; 145 } 146 147 public Name() { 148 super(); 149 // TODO Auto-generated constructor stub 150 } 151 152 153 }
1 package com.fh.test.model; 2 3 import javax.xml.bind.annotation.XmlAccessType; 4 import javax.xml.bind.annotation.XmlAccessorType; 5 import javax.xml.bind.annotation.XmlElement; 6 7 @XmlAccessorType(XmlAccessType.FIELD) 8 public class Order { 9 10 @XmlElement(name="oid") 11 private int id; 12 13 public int getId() { 14 return id; 15 } 16 17 public void setId(int id) { 18 this.id = id; 19 } 20 21 public Order(int id) { 22 super(); 23 this.id = id; 24 } 25 26 public Order() { 27 super(); 28 // TODO Auto-generated constructor stub 29 } 30 31 32 33 }
1 package com.fh.test.model; 2 3 public class User { 4 5 private int id; 6 private String name; 7 private String age; 8 public int getId() { 9 return id; 10 } 11 public void setId(int id) { 12 this.id = id; 13 } 14 public String getName() { 15 return name; 16 } 17 public void setName(String name) { 18 this.name = name; 19 } 20 public String getAge() { 21 return age; 22 } 23 public void setAge(String age) { 24 this.age = age; 25 } 26 public User(int id, String name, String age) { 27 super(); 28 this.id = id; 29 this.name = name; 30 this.age = age; 31 } 32 public User() { 33 super(); 34 // TODO Auto-generated constructor stub 35 } 36 @Override 37 public String toString() { 38 return "User [id=" + id + ", name=" + name + ", age=" + age + "]"; 39 } 40 41 42 43 }
servie
1 package com.fh.test.service; 2 3 import com.fh.test.model.User; 4 5 public interface TestService { 6 7 public User getUserName(String id); 8 9 public int insertName(User user); 10 11 public int updateName(User user); 12 13 public int deleteName(int id); 14 15 public String test(String key); 16 17 18 }
1 package com.fh.test.service.impl; 2 3 import java.util.HashMap; 4 import java.util.List; 5 import java.util.Map; 6 7 import org.slf4j.Logger; 8 import org.slf4j.LoggerFactory; 9 import org.springframework.beans.factory.annotation.Autowired; 10 import org.springframework.beans.factory.annotation.Qualifier; 11 import org.springframework.stereotype.Service; 12 13 import com.fh.test.dao.TestNameDao; 14 import com.fh.test.model.User; 15 import com.fh.test.service.TestService; 16 17 @Service("testServiceImpl") 18 public class TestServiceImpl implements TestService { 19 20 private static final Logger logger=LoggerFactory.getLogger(TestServiceImpl.class); 21 22 @Autowired 23 @Qualifier("testDao") 24 private TestNameDao testDao; 25 public User getUserName(String id) { 26 logger.debug(" service"); 27 List<User> user = testDao.selectUserById(Integer.parseInt(id)); 28 return user.get(0); 29 } 30 public int insertName(User user) { 31 logger.debug(" service"); 32 return testDao.insertUser(user); 33 } 34 public int updateName(User user) { 35 logger.debug(" service"); 36 return testDao.updateUser(user); 37 } 38 public int deleteName(int id) { 39 logger.debug(" service"); 40 int deleteUser = testDao.deleteUser(id); 41 return deleteUser; 42 } 43 /** 44 * DataBase 45 */ 46 public String test(String key) { 47 Map<String,String> data=new HashMap<String,String>(4){ 48 { 49 put("1", "A"); 50 put("2", "B"); 51 } 52 }; 53 return data.get(key); 54 } 55 56 57 58 }
util
1 package com.fh.test.util; 2 3 4 import java.text.SimpleDateFormat; 5 import java.util.Date; 6 7 import org.junit.Test; 8 9 public class DateUtilsFormatThreadLocal { 10 11 12 private static ThreadLocal<SimpleDateFormat> format=new ThreadLocal<SimpleDateFormat>(); 13 14 15 public static String parseDate(Date date 16 ){ 17 SimpleDateFormat sim = format.get(); 18 if(sim==null){ 19 sim=new SimpleDateFormat("yyyy-MM-dd hh:MM:ss"); 20 } 21 return sim.format(date); 22 } 23 24 @Test 25 public void test(){ 26 String parseDate = DateUtilsFormatThreadLocal.parseDate(new Date()); 27 System.out.println(parseDate); 28 } 29 30 31 32 }
1 package com.fh.test.util; 2 3 import java.io.StringReader; 4 import java.io.StringWriter; 5 import java.util.ArrayList; 6 import java.util.HashMap; 7 import java.util.List; 8 import java.util.Map; 9 10 import javax.xml.bind.JAXBContext; 11 import javax.xml.bind.JAXBException; 12 import javax.xml.bind.Marshaller; 13 import javax.xml.bind.Unmarshaller; 14 15 import org.junit.Test; 16 17 import com.fh.test.model.Name; 18 import com.fh.test.model.Order; 19 20 public class JAXBUtil { 21 22 public static String marshal(Object obj) throws JAXBException { 23 JAXBContext context = JAXBContext.newInstance(obj.getClass()); 24 Marshaller marshaller = context.createMarshaller(); 25 marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); 26 marshaller.setProperty(Marshaller.JAXB_ENCODING, "utf-8"); 27 StringWriter writer = new StringWriter(); 28 marshaller.marshal(obj, writer); 29 return writer.toString(); 30 } 31 32 33 public static <T> T unmarshal(String xml,Class<T> c) throws JAXBException{ 34 JAXBContext context = JAXBContext.newInstance(c); 35 Unmarshaller unmarshaller = context.createUnmarshaller(); 36 @SuppressWarnings("unchecked") 37 T unmarshal =(T) unmarshaller.unmarshal(new StringReader(xml)); 38 return unmarshal; 39 } 40 41 42 @Test 43 public void test(){ 44 Name name=new Name(); 45 List<String> a=new ArrayList<String>(); 46 Map<String,String> date=new HashMap<String,String>(); 47 date.put("1", "1"); 48 a.add("aaaa"); 49 a.add("bbbb"); 50 a.add("cccc"); 51 Order or=new Order(); 52 or.setId(1); 53 name.setOrder(or); 54 name.setList(a); 55 name.setData(date); 56 try { 57 String marshal = JAXBUtil.marshal(name); 58 System.out.println(marshal); 59 } catch (JAXBException e) { 60 e.printStackTrace(); 61 } 62 } 63 }
5、下面是src/test/java下面的
1 package com.fh.test; 2 3 import org.junit.Test; 4 import org.springframework.http.MediaType; 5 import org.springframework.http.ResponseEntity; 6 import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; 7 import org.springframework.web.client.RestTemplate; 8 9 import com.fh.test.model.User; 10 11 public class RestTest { 12 13 @Test 14 public void restTest(){ 15 RestTemplate rest=new RestTemplate(); 16 // rest.getMessageConverters().add(new MappingJackson2HttpMessageConverter()); 17 User user=new User(3,"xu","30"); 18 ResponseEntity<User> response = rest.postForEntity("http://localhost:8080/com.fh.test/rest/r", user,User.class); 19 User us = rest.postForObject("http://localhost:8080/com.fh.test/rest/r", user,User.class); 20 System.out.println(us.getName()); 21 } 22 23 }
1 package com.fh.test; 2 3 import java.io.IOException; 4 5 import java.util.ArrayList; 6 import java.util.List; 7 8 import org.apache.http.HttpEntity; 9 import org.apache.http.NameValuePair; 10 import org.apache.http.ParseException; 11 12 import org.apache.http.client.entity.UrlEncodedFormEntity; 13 import org.apache.http.client.methods.CloseableHttpResponse; 14 import org.apache.http.client.methods.HttpPost; 15 import org.apache.http.entity.StringEntity; 16 import org.apache.http.impl.client.CloseableHttpClient; 17 18 import org.apache.http.impl.client.HttpClients; 19 import org.apache.http.message.BasicNameValuePair; 20 import org.apache.http.util.EntityUtils; 21 22 23 import com.alibaba.fastjson.JSONObject; 24 import com.fh.test.model.User; 25 26 public class Test { 27 28 public static void main(String[] args) { 29 CloseableHttpClient client = HttpClients.createDefault(); 30 String url="http://localhost:8080//com.fh.test/test/t"; 31 HttpPost post=new HttpPost(url); 32 List<NameValuePair> param=new ArrayList<NameValuePair>(); 33 param.add(new BasicNameValuePair("id","2")); 34 UrlEncodedFormEntity body=null; 35 CloseableHttpResponse response=null; 36 try { 37 body = new UrlEncodedFormEntity(param,"utf-8"); 38 post.setEntity(body); 39 response = client.execute(post); 40 } catch (IOException e) { 41 e.printStackTrace(); 42 } 43 HttpEntity entity = response.getEntity(); 44 try { 45 String string = EntityUtils.toString(entity); 46 System.out.println("result is "+string); 47 } catch (ParseException e) { 48 e.printStackTrace(); 49 } catch (IOException e) { 50 e.printStackTrace(); 51 } 52 } 53 54 @SuppressWarnings("deprecation") 55 @org.junit.Test 56 public void insert(){ 57 CloseableHttpClient client = HttpClients.createDefault(); 58 String url="http://localhost:8080//com.fh.test/test/insert"; 59 HttpPost post=new HttpPost(url); 60 List<NameValuePair> param=new ArrayList<NameValuePair>(); 61 User user=new User(2,"xuxiaoxiao","23"); 62 String jsonString = JSONObject.toJSONString(user); 63 System.out.println(jsonString); 64 // param.add(new BasicNameValuePair("message","jsonString")); 65 StringEntity body=null; 66 CloseableHttpResponse response=null; 67 try { 68 // body = new UrlEncodedFormEntity(param,"utf-8"); 69 body = new StringEntity(jsonString,"utf-8"); 70 body.setContentEncoding("UTF-8"); 71 body.setContentType("application/json"); 72 // post.addHeader("contextType", "application/json;charset=utf-8"); 73 // post.setHeader("Accept", "application/json"); 74 post.setEntity(body); 75 response = client.execute(post); 76 } catch (IOException e) { 77 e.printStackTrace(); 78 } 79 HttpEntity entity = response.getEntity(); 80 try { 81 String string = EntityUtils.toString(entity); 82 System.out.println("result is "+string); 83 } catch (ParseException e) { 84 e.printStackTrace(); 85 } catch (IOException e) { 86 e.printStackTrace(); 87 } 88 } 89 90 @org.junit.Test 91 public void delete(){ 92 CloseableHttpClient client = HttpClients.createDefault(); 93 String url="http://localhost:8080//com.fh.test/test/delete"; 94 HttpPost post=new HttpPost(url); 95 List<NameValuePair> param=new ArrayList<NameValuePair>(); 96 param.add(new BasicNameValuePair("id","2")); 97 UrlEncodedFormEntity body=null; 98 CloseableHttpResponse response=null; 99 try { 100 body = new UrlEncodedFormEntity(param,"utf-8"); 101 post.setEntity(body); 102 response = client.execute(post); 103 } catch (IOException e) { 104 e.printStackTrace(); 105 } 106 HttpEntity entity = response.getEntity(); 107 try { 108 String string = EntityUtils.toString(entity); 109 System.out.println("result is "+string); 110 } catch (ParseException e) { 111 e.printStackTrace(); 112 } catch (IOException e) { 113 e.printStackTrace(); 114 } 115 } 116 117 118 @org.junit.Test 119 public void testAspect(){ 120 CloseableHttpClient client = HttpClients.createDefault(); 121 String url="http://localhost:8080//com.fh.test/test/asp"; 122 HttpPost post=new HttpPost(url); 123 List<NameValuePair> param=new ArrayList<NameValuePair>(); 124 param.add(new BasicNameValuePair("key","1")); 125 UrlEncodedFormEntity body=null; 126 CloseableHttpResponse response=null; 127 try { 128 body = new UrlEncodedFormEntity(param,"utf-8"); 129 post.setEntity(body); 130 response = client.execute(post); 131 } catch (IOException e) { 132 e.printStackTrace(); 133 } 134 HttpEntity entity = response.getEntity(); 135 try { 136 String string = EntityUtils.toString(entity); 137 System.out.println("result is "+string); 138 } catch (ParseException e) { 139 e.printStackTrace(); 140 } catch (IOException e) { 141 e.printStackTrace(); 142 } 143 } 144 145 146 @org.junit.Test 147 public void testRest(){ 148 CloseableHttpClient client = HttpClients.createDefault(); 149 String url="http://localhost:8080/com.fh.test/rest/r"; 150 HttpPost post=new HttpPost(url); 151 User user=new User(3,"haha","aa"); 152 List<NameValuePair> param=new ArrayList<NameValuePair>(); 153 param.add(new BasicNameValuePair("user",JSONObject.toJSONString(user))); 154 155 UrlEncodedFormEntity body=null; 156 CloseableHttpResponse response=null; 157 try { 158 body = new UrlEncodedFormEntity(param,"utf-8"); 159 body.setContentType("application/json"); 160 body.setContentEncoding("UTF-8"); 161 post.addHeader("Accept", "application/json"); 162 // post.setEntity(body); 163 response = client.execute(post); 164 } catch (IOException e) { 165 e.printStackTrace(); 166 } 167 HttpEntity entity = response.getEntity(); 168 try { 169 String string = EntityUtils.toString(entity); 170 System.out.println("result is "+string); 171 } catch (ParseException e) { 172 e.printStackTrace(); 173 } catch (IOException e) { 174 e.printStackTrace(); 175 } 176 177 } 178 }
1 package com.fh.test; 2 3 import java.io.File; 4 import java.io.FileInputStream; 5 import java.io.FileNotFoundException; 6 import java.io.IOException; 7 import java.io.InputStream; 8 import java.nio.charset.Charset; 9 import java.util.ArrayList; 10 import java.util.List; 11 12 import org.apache.commons.io.IOUtils; 13 import org.apache.http.HttpEntity; 14 import org.apache.http.*; 15 import org.apache.http.client.ClientProtocolException; 16 import org.apache.http.client.entity.UrlEncodedFormEntity; 17 import org.apache.http.client.methods.CloseableHttpResponse; 18 import org.apache.http.client.methods.HttpPost; 19 import org.apache.http.entity.ContentType; 20 import org.apache.http.entity.mime.MultipartEntityBuilder; 21 import org.apache.http.impl.client.CloseableHttpClient; 22 import org.apache.http.impl.client.HttpClients; 23 import org.apache.http.message.BasicNameValuePair; 24 import org.apache.http.util.EntityUtils; 25 import org.junit.Test; 26 import org.springframework.util.Base64Utils; 27 import org.springframework.web.multipart.MultipartException; 28 29 import sun.misc.BASE64Encoder; 30 31 public class UploadFileTest { 32 33 @Test 34 public void test(){ 35 CloseableHttpClient client = HttpClients.createDefault(); 36 String URI="http://localhost:8080/com.fh.test/test/upload"; 37 HttpPost post=new HttpPost(URI); 38 HttpEntity entity=null; 39 MultipartEntityBuilder builder=MultipartEntityBuilder.create(); 40 builder.addBinaryBody("a", new File("/home/fenghao/aaa.png"), ContentType.APPLICATION_FORM_URLENCODED, "aaa.png"); 41 builder.addTextBody("b", "aaaaaaa", ContentType.TEXT_PLAIN); 42 builder.setCharset(Charset.forName("iso-8859-1")); 43 entity=builder.build(); 44 post.setEntity(entity); 45 try { 46 CloseableHttpResponse response = client.execute(post); 47 HttpEntity entity2 = response.getEntity(); 48 System.out.println(EntityUtils.toString(entity2)); 49 } catch (ClientProtocolException e) { 50 e.printStackTrace(); 51 } catch (IOException e) { 52 e.printStackTrace(); 53 } 54 } 55 56 @Test 57 public void file(){ 58 CloseableHttpClient client = HttpClients.createDefault(); 59 String URI="http://localhost:8080/com.fh.test/test/file"; 60 HttpPost post=new HttpPost(URI); 61 try { 62 InputStream in=new FileInputStream(new File("/home/fenghao/aaa.png")); 63 BASE64Encoder encoder=new BASE64Encoder(); 64 try { 65 byte[] byteArray = IOUtils.toByteArray(in); 66 String encode = encoder.encode(byteArray); 67 System.out.println(encode); 68 List<NameValuePair> data=new ArrayList<NameValuePair>(); 69 data.add(new BasicNameValuePair("file",encode)); 70 UrlEncodedFormEntity entity=new UrlEncodedFormEntity(data,"utf-8"); 71 post.setEntity(entity); 72 CloseableHttpResponse execute = client.execute(post); 73 HttpEntity entity2 = execute.getEntity(); 74 System.out.println(EntityUtils.toString(entity2)); 75 } catch (IOException e) { 76 // TODO Auto-generated catch block 77 e.printStackTrace(); 78 } 79 } catch (FileNotFoundException e) { 80 e.printStackTrace(); 81 } 82 } 83 84 }
以上只是一些框架的简单代码,后续还会如果学到还会继续添加