简单了解Spring中常用工具类
文件资源操作
Spring定义了一个org.springframework.core.io.Resource接口,Resource接口是为了统一各种类型不同的资源而定义的,Spring提供了若干Resource接口的实现类,这些实现类可以轻松地加载不同类型的底层资源,并提供了获取文件名、URL地址以及资源内容的操作方法
访问文件资源
*通过FileSystemResource以文件系统绝对路径的方式进行访问;
*通过ClassPathResource以类路径的方式进行访问;
*通过ServletContextResource以相对于Web应用根目录的方式进行访问。
packagecom.baobaotao.io; importjava.io.IOException; importjava.io.InputStream; importorg.springframework.core.io.ClassPathResource; importorg.springframework.core.io.FileSystemResource; importorg.springframework.core.io.Resource; publicclassFileSourceExample{ publicstaticvoidmain(String[]args){ try{ StringfilePath= "D:/masterSpring/chapter23/webapp/WEB-INF/classes/conf/file1.txt"; //①使用系统文件路径方式加载文件 Resourceres1=newFileSystemResource(filePath); //②使用类路径方式加载文件 Resourceres2=newClassPathResource("conf/file1.txt"); InputStreamins1=res1.getInputStream(); InputStreamins2=res2.getInputStream(); System.out.println("res1:"+res1.getFilename()); System.out.println("res2:"+res2.getFilename()); }catch(IOExceptione){ e.printStackTrace(); } } }
在获取资源后,您就可以通过Resource接口定义的多个方法访问文件的数据和其它的信息
getFileName()获取文件名,
getFile()获取资源对应的File对象,
getInputStream()直接获取文件的输入流。
createRelative(StringrelativePath)在资源相对地址上创建新的资源。
在Web应用中,您还可以通过ServletContextResource以相对于Web应用根目录的方式访问文件资源
Spring提供了一个ResourceUtils工具类,它支持“classpath:”和“file:”的地址前缀,它能够从指定的地址加载文件资源。
FileclsFile=ResourceUtils.getFile("classpath:conf/file1.txt"); System.out.println(clsFile.isFile()); StringhttpFilePath="file:D:/masterSpring/chapter23/src/conf/file1.txt"; FilehttpFile=ResourceUtils.getFile(httpFilePath);
文件操作
在使用各种Resource接口的实现类加载文件资源后,经常需要对文件资源进行读取、拷贝、转存等不同类型的操作。
FileCopyUtils
它提供了许多一步式的静态操作方法,能够将文件内容拷贝到一个目标byte[]、String甚至一个输出流或输出文件中。
packagecom.baobaotao.io; importjava.io.ByteArrayOutputStream; importjava.io.File; importjava.io.FileReader; importjava.io.OutputStream; importorg.springframework.core.io.ClassPathResource; importorg.springframework.core.io.Resource; importorg.springframework.util.FileCopyUtils; publicclassFileCopyUtilsExample{ publicstaticvoidmain(String[]args)throwsThrowable{ Resourceres=newClassPathResource("conf/file1.txt"); //①将文件内容拷贝到一个byte[]中 byte[]fileData=FileCopyUtils.copyToByteArray(res.getFile()); //②将文件内容拷贝到一个String中 StringfileStr=FileCopyUtils.copyToString(newFileReader(res.getFile())); //③将文件内容拷贝到另一个目标文件 FileCopyUtils.copy(res.getFile(), newFile(res.getFile().getParent()+"/file2.txt")); //④将文件内容拷贝到一个输出流中 OutputStreamos=newByteArrayOutputStream(); FileCopyUtils.copy(res.getInputStream(),os); } }
staticvoidcopy(byte[]in,Fileout)将byte[]拷贝到一个文件中
staticvoidcopy(byte[]in,OutputStreamout)将byte[]拷贝到一个输出流中
staticintcopy(Filein,Fileout)将文件拷贝到另一个文件中
staticintcopy(InputStreamin,OutputStreamout)将输入流拷贝到输出流中
staticintcopy(Readerin,Writerout)将Reader读取的内容拷贝到Writer指向目标输出中
staticvoidcopy(Stringin,Writerout)将字符串拷贝到一个Writer指向的目标中
属性文件操作
Spring提供的PropertiesLoaderUtils允许您直接通过基于类路径的文件地址加载属性资源
packagecom.baobaotao.io; importjava.util.Properties; importorg.springframework.core.io.support.PropertiesLoaderUtils; publicclassPropertiesLoaderUtilsExample{ publicstaticvoidmain(String[]args)throwsThrowable{ //①jdbc.properties是位于类路径下的文件 Propertiesprops=PropertiesLoaderUtils.loadAllProperties("jdbc.properties"); System.out.println(props.getProperty("jdbc.driverClassName")); } }
特殊编码的资源
当您使用Resource实现类加载文件资源时,它默认采用操作系统的编码格式。如果文件资源采用了特殊的编码格式(如UTF-8),则在读取资源内容时必须事先通过EncodedResource指定编码格式,否则将会产生中文乱码的问题。
packagecom.baobaotao.io; importorg.springframework.core.io.ClassPathResource; importorg.springframework.core.io.Resource; importorg.springframework.core.io.support.EncodedResource; importorg.springframework.util.FileCopyUtils; publicclassEncodedResourceExample{ publicstaticvoidmain(String[]args)throwsThrowable{ Resourceres=newClassPathResource("conf/file1.txt"); //①指定文件资源对应的编码格式(UTF-8) EncodedResourceencRes=newEncodedResource(res,"UTF-8"); //②这样才能正确读取文件的内容,而不会出现乱码 Stringcontent=FileCopyUtils.copyToString(encRes.getReader()); System.out.println(content); } }
访问Spring容器,获取容器中的Bean,使用WebApplicationContextUtils工具类
ServletContextservletContext=request.getSession().getServletContext(); WebApplicationContextwac=WebApplicationContextUtils.getWebApplicationContext(servletContext);
Spring所提供的过滤器和监听器
延迟加载过滤器
Hibernate允许对关联对象、属性进行延迟加载,但是必须保证延迟加载的操作限于同一个HibernateSession范围之内进行。如果Service层返回一个启用了延迟加载功能的领域对象给Web层,当Web层访问到那些需要延迟加载的数据时,由于加载领域对象的HibernateSession已经关闭,这些导致延迟加载数据的访问异常。
Spring为此专门提供了一个OpenSessionInViewFilter过滤器,它的主要功能是使每个请求过程绑定一个HibernateSession,即使最初的事务已经完成了,也可以在Web层进行延迟加载的操作。
hibernateFilter org.springframework.orm.hibernate3.support.OpenSessionInViewFilter hibernateFilter *.html
中文乱码过滤器
encodingFilter org.springframework.web.filter.CharacterEncodingFilter①Spring编辑过滤器 ②编码方式 encoding UTF-8 ③强制进行编码转换 forceEncoding true ②过滤器的匹配URL encodingFilter *.html
一般情况下,您必须将Log4J日志配置文件以log4j.properties为文件名并保存在类路径下。Log4jConfigListener
允许您通过log4jConfigLocationServlet上下文参数显式指定Log4J配置文件的地址,如下所示:
①指定Log4J配置文件的地址
log4jConfigLocation /WEB-INF/log4j.properties
②使用该监听器初始化Log4J日志引擎
Introspector缓存清除监听器,防止内存泄露 org.springframework.web.util.Log4jConfigListener org.springframework.web.util.IntrospectorCleanupListener
一些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特殊字符转义
*&:&
*":"
*<:<
*>:>
JavaScript特殊字符转义
*':/'
*":/"
*/://
*走纸换页:/f
*换行:/n
*换栏符:/t
*回车:/r
*回退符:/b
工具类
JavaScriptUtils.javaScriptEscape(Stringstr);转换为javaScript转义字符表示
HtmlUtils.htmlEscape(Stringstr);①转换为HTML转义字符表示
HtmlUtils.htmlEscapeDecimal(Stringstr);②转换为数据转义表示
HtmlUtils.htmlEscapeHex(Stringstr);③转换为十六进制数据转义表示
HtmlUtils.htmlUnescape(Stringstr);将经过转义内容还原
Spring给我们提供了很多的工具类,应该在我们的日常工作中很好的利用起来.它可以大大的减轻我们的平时编写代码的长度.因我们只想用spring的工具类,
而不想把一个大大的spring工程给引入进来.下面是我从spring3.0.5里抽取出来的工具类.
在最后给出我提取出来的spring代码打成的jar包
spring的里的resouce的概念,在我们处理io时很有用.具体信息请参考spring手册
内置的resouce类型
UrlResource
ClassPathResource
FileSystemResource
ServletContextResource
InputStreamResource
ByteArrayResource
EncodedResource也就是Resource加上encoding,可以认为是有编码的资源
VfsResource(在jboss里经常用到,相应还有工具类VfsUtils)
org.springframework.util.xml.ResourceUtils用于处理表达资源字符串前缀描述资源的工具.如:"classpath:".
有getURL,getFile,isFileURL,isJarURL,extractJarFileURL
工具类
org.springframework.core.annotation.AnnotationUtils处理注解
org.springframework.core.io.support.PathMatchingResourcePatternResolver用于处理ant匹配风(com/*.jsp,com/**/*.jsp),找出所有的资源,结合上面的resource的概念一起使用,对于遍历文件很有用.具体请详细查看javadoc
org.springframework.core.io.support.PropertiesLoaderUtils加载Properties资源工具类,和Resource结合
org.springframework.core.BridgeMethodResolver桥接方法分析器.关于桥接方法请参考:http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.12.4.5
org.springframework.core.GenericTypeResolver范型分析器,在用于对范型方法,参数分析.
org.springframework.core.NestedExceptionUtils
xml工具
org.springframework.util.xml.AbstractStaxContentHandler
org.springframework.util.xml.AbstractStaxXMLReader
org.springframework.util.xml.AbstractXMLReader
org.springframework.util.xml.AbstractXMLStreamReader
org.springframework.util.xml.DomUtils
org.springframework.util.xml.SimpleNamespaceContext
org.springframework.util.xml.SimpleSaxErrorHandler
org.springframework.util.xml.SimpleTransformErrorListener
org.springframework.util.xml.StaxUtils
org.springframework.util.xml.TransformerUtils
其它工具集
org.springframework.util.xml.AntPathMatcherant风格的处理
org.springframework.util.xml.AntPathStringMatcher
org.springframework.util.xml.Assert断言,在我们的参数判断时应该经常用
org.springframework.util.xml.CachingMapDecorator
org.springframework.util.xml.ClassUtils用于Class的处理
org.springframework.util.xml.CollectionUtils用于处理集合的工具
org.springframework.util.xml.CommonsLogWriter
org.springframework.util.xml.CompositeIterator
org.springframework.util.xml.ConcurrencyThrottleSupport
org.springframework.util.xml.CustomizableThreadCreator
org.springframework.util.xml.DefaultPropertiesPersister
org.springframework.util.xml.DigestUtils摘要处理,这里有用于md5处理信息的
org.springframework.util.xml.FileCopyUtils文件的拷贝处理,结合Resource的概念一起来处理,真的是很方便
org.springframework.util.xml.FileSystemUtils
org.springframework.util.xml.LinkedCaseInsensitiveMap
key值不区分大小写的LinkedMap
org.springframework.util.xml.LinkedMultiValueMap一个key可以存放多个值的LinkedMap
org.springframework.util.xml.Log4jConfigurer一个log4j的启动加载指定配制文件的工具类
org.springframework.util.xml.NumberUtils处理数字的工具类,有parseNumber可以把字符串处理成我们指定的数字格式,还支持format格式,convertNumberToTargetClass可以实现Number类型的转化.
org.springframework.util.xml.ObjectUtils有很多处理nullobject的方法.如nullSafeHashCode,nullSafeEquals,isArray,containsElement,addObjectToArray,等有用的方法
org.springframework.util.xml.PatternMatchUtilsspring里用于处理简单的匹配.如Spring'stypical"xxx*","*xxx"and"*xxx*"patternstyles
org.springframework.util.xml.PropertyPlaceholderHelper用于处理占位符的替换
org.springframework.util.xml.ReflectionUtils反映常用工具方法.有findField,setField,getField,findMethod,invokeMethod等有用的方法
org.springframework.util.xml.SerializationUtils用于java的序列化与反序列化.serialize与deserialize方法
org.springframework.util.xml.StopWatch一个很好的用于记录执行时间的工具类,且可以用于任务分阶段的测试时间.最后支持一个很好看的打印格式.这个类应该经常用
org.springframework.util.xml.StringUtils
org.springframework.util.xml.SystemPropertyUtils
org.springframework.util.xml.TypeUtils用于类型相容的判断.isAssignable
org.springframework.util.xml.WeakReferenceMonitor弱引用的监控
和web相关的工具
org.springframework.web.util.CookieGenerator
org.springframework.web.util.HtmlCharacterEntityDecoder
org.springframework.web.util.HtmlCharacterEntityReferences
org.springframework.web.util.HtmlUtils
org.springframework.web.util.HttpUrlTemplate
这个类用于用字符串模板构建url,它会自动处理url里的汉字及其它相关的编码.在读取别人提供的url资源时,应该经常用
Stringurl="http://localhost/myapp/{name}/{id}"
org.springframework.web.util.JavaScriptUtils
org.springframework.web.util.Log4jConfigListener
用listener的方式来配制log4j在web环境下的初始化
org.springframework.web.util.UriTemplate
org.springframework.web.util.UriUtils处理uri里特殊字符的编码
org.springframework.web.util.WebUtils
org.springframework.web.util.
4.EncodedResource(Resource对象,"UTF-8")编码资源(特殊的);
5.WebApplicationContextUtils
6.StringEscapeutils编码解码
总结
以上就是本文关于简单了解Spring中常用工具类的全部内容,希望对大家有所帮助。感兴趣的朋友可以参阅:Java语言Lang包下常用的工具类介绍、浅谈Springboot之于Spring的优势、Java之Spring注解配置bean实例代码解析等,有什么问题可以随时留言,小编会及时回复大家的。