Introduction to common tool classes in spring

Source: Internet
Author: User
Tags file copy print format throwable log4j

Introduction to common tool classes in spring

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); Convert to JavaScript escape character representation

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

Spring provides us with a lot of tools that should be used well in our daily work. It can greatly reduce the length of our usual code writing. Because we just want to use spring's tool class,

Instead of bringing in a big Spring project. Here is the tool class I extracted from the spring3.0.5.

At the end of the jar package I extracted the spring code into

The concept of resouce in spring is useful when we are working with IO. Please refer to the Spring Manual for specific information.

Built-in Resouce type


Urlresource
Classpathresource
Filesystemresource
Servletcontextresource
Inputstreamresource
Bytearrayresource
Encodedresource, resource plus encoding, can be thought of as a coded resource.
Vfsresource (often used in JBoss, and corresponding tools vfsutils)
Org.springframework.util.xml.ResourceUtils is a tool used to describe resources that represent resource string prefixes. such as: &quot;classpath:&quot;.
GetURL, GetFile, Isfileurl, Isjarurl, Extractjarfileurl


Tool class


Org.springframework.core.annotation.AnnotationUtils Handling annotations
Org.springframework.core.io.support.PathMatchingResourcePatternResolver for working with ant matching styles (com/*.jsp, com/**/*.jsp), Finding all the resources, combined with the concept of resource above, is useful for traversing files. For details, please see Javadoc
Org.springframework.core.io.support.PropertiesLoaderUtils Load Properties Resource Tool class, combined with resource
Org.springframework.core.BridgeMethodResolver Bridging Method Analyzer. For bridging methods Please refer to: http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.12.4.5
The Org.springframework.core.GenericTypeResolver Paradigm Analyzer, which is used in the paradigm-based method, parameters analysis.
Org.springframework.core.NestedExceptionUtils


XML tools

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

Other tool sets

Org.springframework.util.xml.AntPathMatcherant-style handling
Org.springframework.util.xml.AntPathStringMatcher
Org.springframework.util.xml.Assert asserts that it should be used frequently when our arguments are judged.
Org.springframework.util.xml.CachingMapDecorator
Org.springframework.util.xml.ClassUtils for class processing
Org.springframework.util.xml.CollectionUtils tools for working with collections
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 Digest processing, here are for MD5 processing information
Org.springframework.util.xml.FileCopyUtils file copy processing, combined with the concept of resource together to deal with, really is very convenient
Org.springframework.util.xml.FileSystemUtils
Org.springframework.util.xml.LinkedCaseInsensitiveMap
The key value is case-insensitive linkedmap
Org.springframework.util.xml.LinkedMultiValueMap A key can hold multiple values of Linkedmap
Org.springframework.util.xml.Log4jConfigurer a log4j boot Load tool class that specifies the configuration file
Org.springframework.util.xml.NumberUtils the tool class that handles numbers, there are parsenumber that can manipulate strings into the number format we specify, and also support format format, Convertnumbertotargetclass can achieve conversions of type number.
Org.springframework.util.xml.ObjectUtils has many methods for handling null object. Useful methods such as Nullsafehashcode, Nullsafeequals, IsArray, containselement, Addobjecttoarray, etc.
Org.springframework.util.xml.PatternMatchUtilsspring is used to handle simple matches. such as Spring's typical &quot;xxx*&quot;, & quot;*xxx&quot; &quot;*xxx*&quot; Pattern styles
Org.springframework.util.xml.PropertyPlaceholderHelper for handling placeholder replacements
Org.springframework.util.xml.ReflectionUtils reflects common tool methods. FindField, SetField, GetField, FindMethod, InvokeMethod and other useful methods.
Org.springframework.util.xml.SerializationUtils for serialization and deserialization of Java. Serialize and Deserialize methods
Org.springframework.util.xml.StopWatch a good tool class for recording execution time, and can be used to test the task in a phased time. Finally, a good-looking print format is supported. This class should always be used
Org.springframework.util.xml.StringUtils
Org.springframework.util.xml.SystemPropertyUtils
Org.springframework.util.xml.TypeUtils used for type-compatible judgments. isassignable
Org.springframework.util.xml.WeakReferenceMonitor monitoring of weak references


Web-related tools


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
This class is used to construct a URL using a string template that automatically handles Chinese characters and other related encodings in the URL. When reading URL resources provided by others, you should always use the
String URL = &quot;http://localhost/myapp/{name}/{id}&quot;
Org.springframework.web.util.JavaScriptUtils
Org.springframework.web.util.Log4jConfigListener
Using listener to formulate log4j in web environment
Org.springframework.web.util.UriTemplate
Org.springframework.web.util.UriUtils encoding of special characters in URIs
Org.springframework.web.util.WebUtils
Org.springframework.web.util.

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


5.WebApplicationContextUtils


6.StringEscapeutils encoding and decoding

Introduction to common tool classes in spring

Related Article

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.