Spring經常使用工具類

Spring 的優秀工具類盤點:html

 

( http://www.ibm.com/developerworks/cn/java/j-lo-spring-utils1/index.html )java

 

文件資源操做web

 

Spring 定義了一個 org.springframework.core.io.Resource 接口,Resource 接口是爲了統一各類類型不一樣的資源而定義的,Spring 提供了若干 Resource 接口的實現類,spring

 

這些實現類能夠輕鬆地加載不一樣類型的底層資源,並提供了獲取文件名、URL 地址以及資源內容的操做方法緩存

 

訪問文件資源服務器

 

  • 經過 FileSystemResource 以文件系統絕對路徑的方式進行訪問;app

  • 經過 ClassPathResource 以類路徑的方式進行訪問;框架

  • 經過 ServletContextResource 以相對於 Web 應用根目錄的方式進行訪問。webapp

 

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);

HtmlUtils.htmlEscape(String str);①轉換爲HTML轉義字符表示

HtmlUtils.htmlEscapeDecimal(String str); ②轉換爲數據轉義表示

HtmlUtils.htmlEscapeHex(String str); ③轉換爲十六進制數據轉義表示

HtmlUtils.htmlUnescape(String str);將通過轉義內容還原

 

Spring框架下自帶了豐富的工具類,在咱們開發時能夠簡化不少工做:

 

1.Resource訪問文件資源:

 

具體有:

 

ResourceUtils.getFile(url);

FileSystemResource(); ClassPathResource();

ServletContextResource(application,url);

 

2.文件操做 FileCopyUtils

 

具體有:

 

FileCopyUtils.copy(Resource.getFile,new File(Resource.getFile(),getParent()+'目標文件名'));

 

3.屬性文件操做 PropertiesLoaderUtils

 

具體有:

 

PropertiesLoaderUtils.loadAllProperties("屬性文件名");  --基於類路徑

 

4.EncodedResource(Resource對象,」UTF-8″) 編碼資源(特殊的);

 

5.WebApplicationContextUtils

 

6.StringEscapeutils 編碼解碼

相關文章
相關標籤/搜索