spring 下的一些Utils

07年的文章,對Spring提供的工具類提供了介紹,可以安排時間看下相應的源碼

Spring 爲 HTML 和 JavaScript 特殊字符提供了轉義操作工具類,它們分別是 HtmlUtils 和 JavaScriptUtils。
org.springframework.web.util.HtmlUtils 提供對HTML字符串中的符號進行過濾
JavaScriptUtils 對Js提供過濾
spring/lib/jakarta-commons/commons-lang.jar)的 StringEscapeUtils提供了更高級的功能,包括了對sql的過濾,防止被注入 , 似乎就是提供了字符串的""與''的轉義

org.springframework.util.Assert; 下面提供一些對內容判斷的方法,類似xUnit類,如果驗證不通過,將直接拋出異常,主要允許定製異常信息

org.springframework.core.io.Resource 接口 ,爲訪問資源提供了統一的接口
Resource res2 = new ClassPathResource("conf/file1.txt");
Resource res1 = new FileSystemResource("d:/filePath");

在界面中,也可以通過
Resource res3 = new ServletContextResource(application, "/WEB-INF/classes/conf/file1.txt");

ResourceUtils 工具類,支持帶classpath: file:的路徑訪問模式
File clsFile = ResourceUtils.getFile("classpath:conf/file1.txt");
String httpFilePath = "file:D:/masterSpring/chapter23/src/conf/file1.txt";
File httpFile = ResourceUtils.getFile(httpFilePath);

LocalizedResourceHelper 也可以用於提供對不同區域的資源文件自動加載
LocalizedResourceHelper lrHalper = new LocalizedResourceHelper();
// ① 獲取對應美國的本地化文件資源
Resource msg_us = lrHalper.findLocalizedResource("i18n/message", ".properties",
Locale.US);
// ② 獲取對應中國大陸的本地化文件資源
Resource msg_cn = lrHalper.findLocalizedResource("i18n/message", ".properties",
Locale.CHINA);
System.out.println("fileName(us):"+msg_us.getFilename());
System.out.println("fileName(cn):"+msg_cn.getFilename());

相對 java.util.ResourceBundle提供的獲取資源文件的方式,spring提供了更加面向接口的工具類

FileCopyUtils 提供了許多一步式的靜態操作方法,能夠將文件內容拷貝到一個目標 byte[]、String 甚至一個輸出流或輸出文件中
byte[] fileData = FileCopyUtils.copyToByteArray(res.getFile());
String fileStr = FileCopyUtils.copyToString(new FileReader(res.getFile()));
FileCopyUtils.copy(res.getFile(), new File(res.getFile().getParent()+ "/file2.txt"));
主要便利就是提供了異常和io開關的處理
OutputStream os = new ByteArrayOutputStream();
FileCopyUtils.copy(res.getInputStream(), os);

PropertiesLoaderUtils 允許您直接通過基於類路徑的文件地址加載屬性資源
Properties props = PropertiesLoaderUtils.loadAllProperties("jdbc.properties") //節約了代碼的調用
此外,PropertiesLoaderUtils 還可以直接從 Resource 對象中加載屬性資源

這裏注意編碼的問題,需要對resource進行編碼處理
Resource res = new ClassPathResource("conf/file1.txt");
// ① 指定文件資源對應的編碼格式(UTF-8)
EncodedResource encRes = new EncodedResource(res,"UTF-8");

Spring 容器在啓動時將 WebApplicationContext 保存在 ServletContext的屬性列表中,通過 WebApplicationContextUtils 工具類可以方便地獲取 WebApplicationContext 對象
WebApplicationContext wac = (WebApplicationContext)servletContext.
getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);

但通過位於 org.springframework.web.context.support 包中的 WebApplicationContextUtils 工具類獲取 WebApplicationContext 更方便:
WebApplicationContext wac =WebApplicationContextUtils.
getWebApplicationContext(servletContext);

WebUtils 提供了大量servlet api的調用,縮短了原有調用的代碼量

IntrospectorCleanupListener 監聽器 用於處理使用了 JavaBean Introspector 分析應用中的類,ntrospector 緩存會保留這些類的引用,從而導致的GC異常

ServletRequestUtils下也提供了對請求的參數獲取的處理方式
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章