文章出處

文件資源操作
     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 編碼解碼

 

相關:ApplicationContextAware接口的作用

       新手上路之Hibernate(5):繼承映射


文章列表


不含病毒。www.avast.com
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()