http://www.cnblogs.com/langtianya/p/3875103.html

文件资源操作
     Spring 定义了一个 org.springframework.core.io.Resource 接口,Resource 接口是为了统一各种类型不同的资源而定义的,Spring 提供了若干 Resource 接口的实现类,这些实现类可以轻松地加载不同类型的底层资源,并提供了获取文件名、URL 地址以及资源内容的操作方法

访问文件资源
* 通过 FileSystemResource 以文件系统绝对路径的方式进行访问;
* 通过 ClassPathResource 以类路径的方式进行访问;
* 通过 ServletContextResource 以相对于 Web 应用根目录的方式进行访问。

package com.baobaotao.io;
import java.io.IOException;
import java.io.InputStream;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
public class FileSourceExample {
public static void main(String[] args) {
try {
String filePath =
"D:/masterSpring/chapter23/webapp/WEB-INF/classes/conf/file1.txt";
// ① 使用系统文件路径方式加载文件
Resource res1 = new FileSystemResource(filePath);
// ② 使用类路径方式加载文件
Resource res2 = new ClassPathResource("conf/file1.txt");
InputStream ins1 = res1.getInputStream();
InputStream ins2 = res2.getInputStream();
System.out.println("res1:"+res1.getFilename());
System.out.println("res2:"+res2.getFilename());
} catch (IOException e) {
e.printStackTrace();
}
}
}

在获取资源后,您就可以通过 Resource 接口定义的多个方法访问文件的数据和其它的信息

getFileName() 获取文件名,
getFile() 获取资源对应的 File 对象,
getInputStream() 直接获取文件的输入流。
createRelative(String relativePath) 在资源相对地址上创建新的资源。

在 Web 应用中,您还可以通过 ServletContextResource 以相对于 Web 应用根目录的方式访问文件资源
Spring 提供了一个 ResourceUtils 工具类,它支持“classpath:”和“file:”的地址前缀 ,它能够从指定的地址加载文件资源。

File clsFile = ResourceUtils.getFile("classpath:conf/file1.txt");
System.out.println(clsFile.isFile());
String httpFilePath = "file:D:/masterSpring/chapter23/src/conf/file1.txt";
File httpFile = ResourceUtils.getFile(httpFilePath);

文件操作
在使用各种 Resource 接口的实现类加载文件资源后,经常需要对文件资源进行读取、拷贝、转存等不同类型的操作。

FileCopyUtils
它提供了许多一步式的静态操作方法,能够将文件内容拷贝到一个目标 byte[]、String 甚至一个输出流或输出文件中。

package com.baobaotao.io;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileReader;
import java.io.OutputStream;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.FileCopyUtils;
public class FileCopyUtilsExample {
public static void main(String[] args) throws Throwable {
Resource res = new ClassPathResource("conf/file1.txt");
// ① 将文件内容拷贝到一个 byte[] 中
byte[] fileData = FileCopyUtils.copyToByteArray(res.getFile());
// ② 将文件内容拷贝到一个 String 中
String fileStr = FileCopyUtils.copyToString(new FileReader(res.getFile()));
// ③ 将文件内容拷贝到另一个目标文件
FileCopyUtils.copy(res.getFile(),
new File(res.getFile().getParent()+ "/file2.txt"));
// ④ 将文件内容拷贝到一个输出流中
OutputStream os = new ByteArrayOutputStream();
FileCopyUtils.copy(res.getInputStream(), os);
}
}
static void copy(byte[] in, File out) 将 byte[] 拷贝到一个文件中
static void copy(byte[] in, OutputStream out) 将 byte[] 拷贝到一个输出流中
static int copy(File in, File out) 将文件拷贝到另一个文件中
static int copy(InputStream in, OutputStream out) 将输入流拷贝到输出流中
static int copy(Reader in, Writer out) 将 Reader 读取的内容拷贝到 Writer 指向目标输出中
static void copy(String in, Writer out) 将字符串拷贝到一个 Writer 指向的目标中

属性文件操作
Spring 提供的 PropertiesLoaderUtils 允许您直接通过基于类路径的文件 地址加载属性资源

package com.baobaotao.io;
import java.util.Properties;
import org.springframework.core.io.support.PropertiesLoaderUtils;
public class PropertiesLoaderUtilsExample {
public static void main(String[] args) throws Throwable {
// ① jdbc.properties 是位于类路径下的文件
Properties props = PropertiesLoaderUtils.loadAllProperties("jdbc.properties");
System.out.println(props.getProperty("jdbc.driverClassName"));
}
}

特殊编码的资源
当您使用 Resource 实现类加载文件资源时,它默认采用操作系统的编码格式。如果文件资源采用了特殊的编码格式(如 UTF-8),则在读取资源内容时必须事先通过 EncodedResource 指定编码格式,否则将会产生中文乱码的问题。

package com.baobaotao.io;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.util.FileCopyUtils;
public class EncodedResourceExample {
public static void main(String[] args) throws Throwable {
Resource res = new ClassPathResource("conf/file1.txt");
// ① 指定文件资源对应的编码格式(UTF-8)
EncodedResource encRes = new EncodedResource(res,"UTF-8");
// ② 这样才能正确读取文件的内容,而不会出现乱码
String content = FileCopyUtils.copyToString(encRes.getReader());
System.out.println(content);
}
}

访问 Spring 容器,获取容器中的 Bean,使用 WebApplicationContextUtils 工具类

ServletContext servletContext = request.getSession().getServletContext();
WebApplicationContext wac = WebApplicationContextUtils. getWebApplicationContext(servletContext);

Spring 所提供的过滤器和监听器

延迟加载过滤器
Hibernate 允许对关联对象、属性进行延迟加载,但是必须保证延迟加载的操作限于同一个 Hibernate Session 范围之内进行。如果 Service 层返回一个启用了延迟加载功能的领域对象给 Web 层,当 Web 层访问到那些需要延迟加载的数据时,由于加载领域对象的 Hibernate Session 已经关闭,这些导致延迟加载数据的访问异常。
Spring 为此专门提供了一个 OpenSessionInViewFilter 过滤器,它的主要功能是使每个请求过程绑定一个 Hibernate Session,即使最初的事务已经完成了,也可以在 Web 层进行延迟加载的操作。

<filter>
<filter-name>hibernateFilter</filter-name>
<filter-class>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>hibernateFilter</filter-name>
<url-pattern>*.html</url-pattern>
</filter-mapping> 中文乱码过滤器
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>
org.springframework.web.filter.CharacterEncodingFilter ① Spring 编辑过滤器
</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> ② 过滤器的匹配 URL
<filter-name>encodingFilter</filter-name>
<url-pattern>*.html</url-pattern>
</filter-mapping>

一般情况下,您必须将 Log4J 日志配置文件以 log4j.properties 为文件名并保存在类路径下。Log4jConfigListener 允许您通过 log4jConfigLocation Servlet 上下文参数显式指定 Log4J 配置文件的地址,如下所示:

① 指定 Log4J 配置文件的地址
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/log4j.properties</param-value>
</context-param>
② 使用该监听器初始化 Log4J 日志引擎
<listener>
<listener-class>
org.springframework.web.util.Log4jConfigListener
</listener-class>
</listener>

Introspector 缓存清除监听器,防止内存泄露

<listener>
<listener-class>
org.springframework.web.util.IntrospectorCleanupListener
</listener-class>
</listener>

一些 Web 应用服务器(如 Tomcat)不会为不同的 Web 应用使用独立的系统参数,也就是说,应用服务器上所有的 Web 应用都共享同一个系统参数对象。这时,您必须通过 webAppRootKey 上下文参数为不同 Web 应用指定不同的属性名:如第一个 Web 应用使用 webapp1.root 而第二个 Web 应用使用 webapp2.root 等,这样才不会发生后者覆盖前者的问题。此外,WebAppRootListener 和 Log4jConfigListener 都只能应用在 Web 应用部署后 WAR 文件会解包的 Web 应用服务器上。一些 Web 应用服务器不会将 Web 应用的 WAR 文件解包,整个 Web 应用以一个 WAR 包的方式存在(如 Weblogic),此时因为无法指定对应文件系统的 Web 应用根目录,使用这两个监听器将会发生问题。

特殊字符转义
Web 开发者最常面对需要转义的特殊字符类型:
* HTML 特殊字符;
* JavaScript 特殊字符;

HTML 特殊字符转义
* & :&amp;
* " :&quot;
* < :&lt;
* > :&gt;

JavaScript 特殊字符转义
* ' :/'
* " :/"
* / ://
* 走纸换页: /f
* 换行:/n
* 换栏符:/t
* 回车:/r
* 回退符:/b

工具类

JavaScriptUtils.javaScriptEscape(String str);转换为javaScript转义字符表示

HtmlUtils.htmlEscape(String str);①转换为HTML转义字符表示

HtmlUtils.htmlEscapeDecimal(String str); ②转换为数据转义表示

HtmlUtils.htmlEscapeHex(String str); ③转换为十六进制数据转义表示

HtmlUtils.htmlUnescape(String str);将经过转义内容还原

Spring给我们提供了很多的工具类, 应该在我们的日常工作中很好的利用起来. 它可以大大的减轻我们的平时编写代码的长度. 因我们只想用spring的工具类,

而不想把一个大大的spring工程给引入进来. 下面是我从spring3.0.5里抽取出来的工具类.

在最后给出我提取出来的spring代码打成的jar包

spring的里的resouce的概念, 在我们处理io时很有用. 具体信息请参考spring手册

内置的resouce类型

  1. UrlResource
  2. ClassPathResource
  3. FileSystemResource
  4. ServletContextResource
  5. InputStreamResource
  6. ByteArrayResource
  7. EncodedResource 也就是Resource加上encoding, 可以认为是有编码的资源
  8. VfsResource(在jboss里经常用到, 相应还有 工具类 VfsUtils)
  9. org.springframework.util.xml.ResourceUtils 用于处理表达资源字符串前缀描述资源的工具. 如: &quot;classpath:&quot;. 
    有 getURL, getFile, isFileURL, isJarURL, extractJarFileURL

工具类

  1. org.springframework.core.annotation.AnnotationUtils   处理注解
  2. org.springframework.core.io.support.PathMatchingResourcePatternResolver  用 于处理 ant 匹配风格(com/*.jsp, com/**/*.jsp),找出所有的资源, 结合上面的resource的概念一起使用,对于遍历文件很有用. 具体请详细查看javadoc
  3. org.springframework.core.io.support.PropertiesLoaderUtils 加载Properties资源工具类,和Resource结合
  4. org.springframework.core.BridgeMethodResolver  桥接方法分析器.  关于桥接方法请参考: http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.12.4.5
  5. org.springframework.core.GenericTypeResolver  范型分析器, 在用于对范型方法, 参数分析.
  6. org.springframework.core.NestedExceptionUtils

xml工具

  1. org.springframework.util.xml.AbstractStaxContentHandler
  2. org.springframework.util.xml.AbstractStaxXMLReader
  3. org.springframework.util.xml.AbstractXMLReader
  4. org.springframework.util.xml.AbstractXMLStreamReader
  5. org.springframework.util.xml.DomUtils
  6. org.springframework.util.xml.SimpleNamespaceContext
  7. org.springframework.util.xml.SimpleSaxErrorHandler
  8. org.springframework.util.xml.SimpleTransformErrorListener
  9. org.springframework.util.xml.StaxUtils
  10. org.springframework.util.xml.TransformerUtils

其它工具集

  1. org.springframework.util.xml.AntPathMatcherant风格的处理
  2. org.springframework.util.xml.AntPathStringMatcher
  3. org.springframework.util.xml.Assert断言,在我们的参数判断时应该经常用
  4. org.springframework.util.xml.CachingMapDecorator
  5. org.springframework.util.xml.ClassUtils用于Class的处理
  6. org.springframework.util.xml.CollectionUtils用于处理集合的工具
  7. org.springframework.util.xml.CommonsLogWriter
  8. org.springframework.util.xml.CompositeIterator
  9. org.springframework.util.xml.ConcurrencyThrottleSupport
  10. org.springframework.util.xml.CustomizableThreadCreator
  11. org.springframework.util.xml.DefaultPropertiesPersister
  12. org.springframework.util.xml.DigestUtils摘要处理, 这里有用于md5处理信息的
  13. org.springframework.util.xml.FileCopyUtils文件的拷贝处理, 结合Resource的概念一起来处理, 真的是很方便
  14. org.springframework.util.xml.FileSystemUtils
  15. org.springframework.util.xml.LinkedCaseInsensitiveMap
    key值不区分大小写的LinkedMap
  16. org.springframework.util.xml.LinkedMultiValueMap一个key可以存放多个值的LinkedMap
  17. org.springframework.util.xml.Log4jConfigurer一个log4j的启动加载指定配制文件的工具类
  18. org.springframework.util.xml.NumberUtils处理数字的工具类, 有parseNumber 可以把字符串处理成我们指定的数字格式, 还支持format格式, convertNumberToTargetClass 可以实现Number类型的转化.
  19. org.springframework.util.xml.ObjectUtils有很多处理null object的方法. 如nullSafeHashCode, nullSafeEquals, isArray, containsElement, addObjectToArray, 等有用的方法
  20. org.springframework.util.xml.PatternMatchUtilsspring里用于处理简单的匹配. 如 Spring's typical &quot;xxx*&quot;, &quot;*xxx&quot; and &quot;*xxx*&quot; pattern styles
  21. org.springframework.util.xml.PropertyPlaceholderHelper用于处理占位符的替换
  22. org.springframework.util.xml.ReflectionUtils反映常用工具方法. 有 findField, setField, getField, findMethod, invokeMethod等有用的方法
  23. org.springframework.util.xml.SerializationUtils用于java的序列化与反序列化. serialize与deserialize方法
  24. org.springframework.util.xml.StopWatch一个很好的用于记录执行时间的工具类, 且可以用于任务分阶段的测试时间. 最后支持一个很好看的打印格式. 这个类应该经常用
  25. org.springframework.util.xml.StringUtils
  26. org.springframework.util.xml.SystemPropertyUtils
  27. org.springframework.util.xml.TypeUtils用于类型相容的判断. isAssignable
  28. org.springframework.util.xml.WeakReferenceMonitor弱引用的监控

和web相关的工具

    1. org.springframework.web.util.CookieGenerator
    2. org.springframework.web.util.HtmlCharacterEntityDecoder
    3. org.springframework.web.util.HtmlCharacterEntityReferences
    4. org.springframework.web.util.HtmlUtils
    5. org.springframework.web.util.HttpUrlTemplate
      这个类用于用字符串模板构建url, 它会自动处理url里的汉字及其它相关的编码. 在读取别人提供的url资源时, 应该经常用 
      String url = &quot;http://localhost/myapp/{name}/{id}&quot;
    6. org.springframework.web.util.JavaScriptUtils
    7. org.springframework.web.util.Log4jConfigListener
      用listener的方式来配制log4j在web环境下的初始化
    8. org.springframework.web.util.UriTemplate
    9. org.springframework.web.util.UriUtils处理uri里特殊字符的编码
    10. org.springframework.web.util.WebUtils
    11. org.springframework.web.util.

4.EncodedResource(Resource对象,"UTF-8") 编码资源(特殊的);

5.WebApplicationContextUtils

6.StringEscapeutils 编码解码

spring中常用工具类介绍的更多相关文章

  1. 简单了解Spring中常用工具类_java - JAVA

    文章来源:嗨学网 敏而好学论坛www.piaodoo.com 欢迎大家相互学习 文件资源操作 Spring 定义了一个 org.springframework.core.io.Resource 接口, ...

  2. Spark中常用工具类Utils的简明介绍

    <深入理解Spark:核心思想与源码分析>一书前言的内容请看链接<深入理解SPARK:核心思想与源码分析>一书正式出版上市 <深入理解Spark:核心思想与源码分析> ...

  3. Spring中常用注解的介绍

    spring中使用注解时配置文件的写法: <?xml version="1.0" encoding="UTF-8"?> <span style ...

  4. Spring的常用工具类

    官方文档 http://projects.spring.io/spring-framework https://docs.spring.io/spring/docs/current/javadoc-a ...

  5. java反射的补充:桥接方法以及Spring中一些工具类

    在上一篇博文中:http://www.cnblogs.com/guangshan/p/4660564.html 源码中有些地方用到了 this.bridgedMethod = BridgeMethod ...

  6. java中常用工具类

    目录 一. org.apache.commons.io.IOUtils 二. org.apache.commons.io.FileUtils 三. org.apache.commons.lang.St ...

  7. JQuery中的工具类(五)

    一:1.serialize()序列表表格内容为字符串.返回值jQuery示例序列表表格内容为字符串,用于 Ajax 请求. HTML 代码:<p id="results"&g ...

  8. commons-lang3-3.2.jar中的常用工具类的使用

    这个包中的很多工具类可以简化我们的操作,在这里简单的研究其中的几个工具类的使用. 1.StringUtils工具类 可以判断是否是空串,是否为null,默认值设置等操作: /** * StringUt ...

  9. Java语言Lang包下常用的工具类介绍_java - JAVA

    文章来源:嗨学网 敏而好学论坛www.piaodoo.com 欢迎大家相互学习 无论你在开发哪中 Java 应用程序,都免不了要写很多工具类/工具函数.你可知道,有很多现成的工具类可用,并且代码质量都 ...

随机推荐

  1. 利用nodejs+phantomjs+casperjs采集淘宝商品的价格

    因为一些业务需求需要采集淘宝店铺商品的销售价格,但是淘宝详情页面的价格显示是通过js动态调用显示的.所以就没法通过普通的获取页面html然后通过正则或者xpath的方式获取到想到的信息了. 所幸我们现 ...

  2. CISA 信息系统审计知识点 [第一章. 信息系统审计过程 ]

    对有志成为审计师或者IT管理者de朋友, 第一章. 信息系统审计过程 1. IS 审计和保障标准.指南.工具.职业道德规范 信息技术保证框架(ITAF,Information Technology A ...

  3. 自己封装的android客户端http网络框架

    整个框架是基于阿帕奇的httpclient搭建的,框架类图如下,我是用Astah Professional画出来,将项目导入,自动生成所有类关系图,还是挺方便的: 核心类是HttpManager和Ht ...

  4. POJ 1804 Brainman

    Brainman Time Limit: 1000MS   Memory Limit: 30000K Total Submissions: 7787   Accepted: 4247 Descript ...

  5. python 字符串截取

    我们可以通过索引来提取想要获取的字符,可以把python的字符串也做为字符串的列表就更好理解 python的字串列表有2种取值顺序1是从左到右索引默认0开始的,最大范围是字符串长度少1s = 'ilo ...

  6. java 动态创建数据库和动态连接数据库

    项目中有一个需求要动态创建数据库并且要动态连接数据库,本来以为还很难实现呢,在网上找了好久,都不是很理想,最后看到有人说创建数据库时,先连接到任意一个数据库,获得连接后用createStatement ...

  7. H5+CSS3实现手指滑动切换图片

    包含3个文件:html.slider-H5.js.jquery.js(自行下载).在html中可配置滑动参数.具体代码如下: HTML代码: <!DOCTYPE HTML> <htm ...

  8. 轻量级linux CRUX安装笔记

    感谢hrdd的分享,原文出处:http://wxdhrdd.blog.163.com/blog/static/120500564200952592240867/ 以下是对原文进行补充 crux的安装: ...

  9. 如何对excel进行列查重

    学习了excel函数:countif.表达式:COUNTIF(数据区域,条件),作用:对数据区域内符合条件单元格计数 具体应用 在“姓名”(列A)后插入一列(列B),在B2单元格输入公式“=IF(CO ...

  10. css的两种引用方式 link和@import

    学习web开发的最大乐趣就是不断的发现自己以前不曾见过的东西,这些东西对于我来说是那么的新鲜有趣. 比如说今天偶尔研究别人的网站,就发现了有趣的东东. 当点开此网页的css时(这个css文件命名方式就 ...