Spring Common tool Classes

Source: Internet
Author: User

Http://www.ibm.com/developerworks/cn/java/j-lo-spring-utils1/index.html
File Resource Operations
Spring defines a org.springframework.core.io.Resource interface that is defined for unifying various types of resources, and Spring provides implementation classes for several Resource interfaces. These implementation classes can easily load different types of underlying resources and provide a way to get the file name, URL address, and resource content
accessing File Resources
* Access via Filesystemresource to the absolute path of the file system;
* Access by Classpathresource in a classpath manner;
* Accessed through Servletcontextresource in a way that is relative to the Web application's root directory.
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";
① loading files using the System file path method
Resource res1 = new Filesystemresource (FilePath);
② loading files with classpath mode
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 ();
}
}
}
Once the resource has been obtained, you can access the file's data and other information through multiple methods defined by the Resource interface
GetFileName () Gets the file name,
GetFile () Gets the File object corresponding to the resource,
getInputStream () gets the input stream of the file directly.
Createrelative (String relativepath) creates a new resource on the relative address of the resource.
In a web app, you can also access file resources by Servletcontextresource in a way that is relative to the Web app's root directory
Spring provides a resourceutils tool class that supports the address prefixes of "classpath:" and "File:", which can load file resources from a specified address.
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);
File operations
After loading the file resources with the implementation classes of various Resource interfaces, it is often necessary to read, copy, and dump the file resources.

Filecopyutils
It provides a number of one-step, static operations that can copy the contents of a file to a target byte[], String, or even an output stream or output file.
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");
① Copy the contents of the file to a byte[]
byte[] FileData = Filecopyutils.copytobytearray (Res.getfile ());
② copying the contents of a file into a String
String filestr = filecopyutils.copytostring (New FileReader (Res.getfile ()));
③ copying the contents of a file to another destination file
Filecopyutils.copy (Res.getfile (),
New File (Res.getfile (). GetParent () + "/file2.txt"));
④ copying the contents of a file into an output stream
OutputStream OS = new Bytearrayoutputstream ();
Filecopyutils.copy (Res.getinputstream (), OS);
}
}
static void Copy (byte[] in, file out) copies byte[] to a file
static void Copy (byte[] in, outputstream out) copies byte[] to an output stream
static int copy (file in, document out) copies files to another file
static int copy (InputStream in, outputstream out) copies the input stream to the output stream
static int copy (reader in, writer out) copies the content read by reader to Writer pointing to the target output
static void Copy (string in, writer out) copies the string to a target that the writer points to
Properties file Operations
Spring provides propertiesloaderutils that allow you to load property resources directly from a file address based on a classpath
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 is a file located under the Classpath
Properties props = propertiesloaderutils.loadallproperties ("jdbc.properties");
System.out.println (Props.getproperty ("Jdbc.driverclassname"));
}
}
Specially coded resources
When you use the Resource implementation class to load a file resource, it defaults to the encoding format of the operating system. If the file resource takes a special encoding format (such as UTF-8), it is necessary to specify the encoding format in advance by Encodedresource when reading the resource content, otherwise the problem of garbled Chinese will be generated.
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");
① the encoding format for the specified file resource (UTF-8)
Encodedresource encres = new Encodedresource (res, "UTF-8");
② so that the contents of the file can be read correctly without garbled
String content = filecopyutils.copytostring (Encres.getreader ());
SYSTEM.OUT.PRINTLN (content);
}
}
Access the Spring container, get the beans in the container, use the Webapplicationcontextutils tool class
ServletContext ServletContext = Request.getsession (). Getservletcontext ();
Webapplicationcontext WAC = webapplicationcontextutils. Getwebapplicationcontext (ServletContext);
The filters and listeners provided by Spring
Delay Load Filter
Hibernate allows lazy loading of associated objects, properties, but must ensure that deferred loading is limited to the same Hibernate Session range. If the Service layer returns a domain object that has the lazy load feature enabled to the Web layer, when the Web tier accesses data that requires lazy loading, the Hibernate Session that loads the realm object is closed, which results in an access exception that delays loading the data.
Spring specifically provides a opensessioninviewfilter filter, which is designed to bind each request process to a Hibernate Session, even if the initial transaction is complete, and can be deferred loading at the WEB layer.
<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>
Chinese garbled filter
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>
Org.springframework.web.filter.characterencodingfilter①spring Edit Filter
</filter-class>
<init-param>② Encoding method
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>③ forcing the encoding conversion
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
Match URL for <filter-mapping>② filter
<filter-name>encodingFilter</filter-name>
<url-pattern>*.html</url-pattern>
</filter-mapping>
In general, you must use the Log4j log profile as a log4j.properties file name and save it under the classpath. Log4jconfiglistener allows you to explicitly specify the address of the log4j configuration file through the Log4jconfiglocation Servlet context parameter, as follows:
① Specify the address of the log4j configuration file
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/log4j.properties</param-value>
</context-param>
② using this listener to initialize the log4j log engine
<listener>
<listener-class>
Org.springframework.web.util.Log4jConfigListener
</listener-class>
</listener>
Introspector cache cleanup Listener to prevent memory leaks
<listener>
<listener-class>
Org.springframework.web.util.IntrospectorCleanupListener
</listener-class>
</listener>
Some Web application servers, such as Tomcat, do not use separate system parameters for different Web applications, that is, all Web applications on the application server share the same system parameter object. At this point, you must specify different property names for different Web apps through the Webapprootkey context parameter: For example, the first web app uses Webapp1.root and the second web app uses Webapp2.root, and so on, so there's no problem with the latter covering the former. In addition, Webapprootlistener and Log4jconfiglistener can only be applied on Web application servers that are unpacked by the WAR file after the Web app is deployed. Some Web application servers do not unpack the war file for the Web app, and the entire Web application exists as a war package (such as Weblogic), because the web app root of the corresponding file system cannot be specified, and using both listeners will cause problems.

Special character escapes
Web developers are most often confronted with special character types that need to be escaped:
* HTML special characters;
* JavaScript special characters;

HTML Special Character escapes
* &:&amp;
* ":&quot;
* <:&lt;
* >:&gt;

JavaScript Special Character escapes
* ‘ :/‘
* " :/"
* / ://
* Paper page change:/F
* Line break:/n
* Box break:/t
* Enter:/R
* Fallback character:/b

Tool class

Javascriptutils.javascriptescape (String str);

Htmlutils.htmlescape (String str); ① converted to HTML escape character representation

Htmlutils.htmlescapedecimal (String str); ② conversion to data escape representation

Htmlutils.htmlescapehex (String str); ③ conversion to hexadecimal data escape representation

Htmlutils.htmlunescape (String str); restore escaped content

The spring framework comes with a rich toolset that simplifies a lot of work as we develop:
1.Resource access to File resources:
Specific: Resourceutils.getfile (URL);
Filesystemresource (); Classpathresource ();
Servletcontextresource (Application,url);

2. File Operation Filecopyutils
Specific: filecopyutils.copy (resource.getfile,new file (Resource.getfile (), getParent () + ' target filename '));

3. property file Operation Propertiesloaderutils
Specific: propertiesloaderutils.loadallproperties ("attribute file name"); --Based on class path

4.EncodedResource (Resource object, "UTF-8") encoded resources (special);

5.WebApplicationContextUtils

6.StringEscapeutils encoding and decoding

Spring Common tool Classes

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.