Simple understanding of common tool classes in spring
File resource operation
Spring defines an org springframework. core. io. Resource interface. Resource interface is defined to unify different types of resources. Spring provides several implementation classes of resource interface. These implementation classes can easily load different types of underlying resources, and provide operation methods to obtain file name, URL address and resource content
Access file resources
*Access through filesystemresource in the form of file system absolute path;
*Access by classpath through classpathresource;
*The servletcontextresource is accessed relative to the web application root directory.
After obtaining the resource, you can access the file 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 at the relative address of the resource.
In a web application, you can also access file resources relative to the web application root directory through servletcontextresource
Spring provides a resourceutils tool class, which supports the address prefixes of "classpath:" and "file:". It can load file resources from the specified address.
File operation
After using the implementation classes of various resource interfaces to load file resources, it is often necessary to read, copy, transfer and other different types of operations on file resources.
FileCopyUtils
It provides many one-step static operation methods, which can copy the file content to a target byte [], string, or even an output stream or output file.
Static void copy (byte [] in, file out) copies byte [] to a file
Static void copy (byte [] in, OutputStream out) copies byte [] into an output stream
Static int copy (file in, file out) copies a file 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 contents read by the reader to the target output pointed by the writer
Static void copy (string in, writer out) copies a string to a target pointed to by the writer
Property file operation
The properties loaderutils provided by spring allows you to load property resources directly through the classpath based file address
Specially coded resources
When you use the resource implementation class to load file resources, it defaults to the encoding format of the operating system. If the file resource adopts a special encoding format (such as UTF-8), the encoding format must be specified through encodedresource in advance when reading the resource content, otherwise Chinese garbled code will occur.
Access the spring container, get the bean in the container, and use the webapplicationcontextutils tool class
Filters and listeners provided by spring
Delay load filter
Hibernate allows delayed loading of associated objects and attributes, but it must be ensured that the operation of delayed loading is limited to the same hibernate session. If the service layer returns a domain object with delayed loading enabled to the web layer, when the web layer accesses the data that needs delayed loading, the hibernate session that loads the domain object has been closed, which leads to the access exception of delayed loading data.
Spring specifically provides an opensessioninview filter for this purpose. Its main function is to bind a hibernate session to each request process. Even if the initial transaction has been completed, the delayed loading operation can be carried out in the web layer.
Chinese garbled code filter
In general, you must set the log4j log configuration file to log4j Properties is the file name and saved in 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
② Use this listener to initialize the log4j log engine
Some web application servers (such as Tomcat) does not use independent system parameters for different web applications, that is, all web applications on the application server share the same system parameter object. In this case, you must specify different attribute names for different web applications through the webapprootkey context parameter: for example, the first web application uses webapp1.root and the second web application uses webapp2 Root, etc., so that the latter will not overwrite the former. In addition, webapprootlistener and log4jconfiglistener can only be applied to the web application server where the war file will be unpacked after web application deployment. Some web application servers will not unpack the war file of the web application. The whole web application exists as a war package (such as Weblogic). At this time, because the web application root directory of the corresponding file system cannot be specified, problems will occur with using these two listeners.
Special character escape
Web developers often face special character types that need escape: * HTML special characters* JavaScript special characters; HTML special character escape * &: & * ":" * <: < * >: >
JavaScript special character escape
*': /' * ': / / / / / / * paper feed and page change: / f * line feed: / N * column change character: / T * enter: / R * fallback character: / b
Tool class
JavaScriptUtils. javaScriptEscape(String str); Convert to JavaScript escape characters to represent htmlutils htmlEscape(String str); ① Convert to HTML escape character to represent htmlutils htmlEscapeDecimal(String str); ② Convert to data escape representation htmlutils htmlEscapeHex(String str); ③ Convert to hexadecimal data and escape to represent htmlutils htmlUnescape(String str); Restore escaped content
Spring provides us with many tool classes, which should be well used in our daily work It can greatly reduce the length of our usual code Because we just want to use spring's tool class,
Instead of bringing in a big spring project Here's what I learned from spring 3 Tool classes extracted from 0.5
At the end, I give the jar package made of the spring code I extracted
The concept of resource in spring is very useful when dealing with io Please refer to the spring manual for details
Built in resource type
UrlResource ClassPathResource FileSystemResource ServletContextResource InputStreamResource ByteArrayResource
Encoded resource, that is, resource plus encoding, can be regarded as a coded resource
Vfsresource (often used in JBoss and corresponding tool class vfsutils)
org. springframework. util. xml. Resourceutils is a tool used to express resource string prefixes and describe resources For example: "classpath:" There are geturl, GetFile, isfileurl, isjarurl and extractjarfileurl
Tool class
org. springframework. core. annotation. Annotationutils handles annotations org springframework. core. io. support. Pathmatchingresortternresolver is used to process ant matching wind (COM / *. JSP, COM / * * / *. JSP), find out all resources, and use it in combination with the above resource concept. It is very useful for traversing files Please check javadoc.org for details springframework. core. io. support. Propertiesloaderutils loads the properties resource tool class and combines it with resource. Org springframework. core. Bridgemethodresolver bridge method analyzer For bridging methods, refer to: http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.12.4.5 org. springframework. core. Generictyperesolver paradigm analyzer is used for paradigm method and parameter 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 toolsets
org. springframework. util. xml. Antpathmatcherant style processing org springframework. util. xml. AntPathStringMatcher org. springframework. util. xml. Assert asserts that we should often use org. Org when judging our parameters springframework. util. xml. CachingMapDecorator org. springframework. util. xml. Classutils is used for class processing org springframework. util. xml. Collectionutils is a tool 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 summary processing, here is the org. Org for MD5 processing information springframework. util. xml. The copying of filecopyutils files is handled in combination with the concept of resource. Org springframework. util. xml. FileSystemUtils org. springframework. util. xml. The linkedcaseinsensivemap key value is case insensitive linkedmap org springframework. util. xml. Linkedmultivaluemap a key can store linkedmap org. Of multiple values springframework. util. xml. Log4jconfigurer starts a log4j and loads the tool class org. Of the specified configuration file springframework. util. xml. Numberutils is a tool class for processing numbers. Parsenumber can process strings into the number format specified by us. It also supports format format. Convertnumbertotargetclass can realize the conversion of number type org. springframework. util. xml. Objectutils has many ways to handle null objects Useful methods such as nullsafehashcode, nullsafeequals, isarray, containselement, addobjecttoarray, etc. org springframework. util. xml. Patternmatchutilsspring is used to handle simple matching For example, spring's typical "XXX *", "* XXX" and "* XXX *" pattern styles org springframework. util. xml. Propertyplaceholderhelper is used to handle placeholder replacement org springframework. util. xml. Reflectionutils reflect common tools and methods There are useful methods such as findfield, setfield, getfield, findmethod and invokemethod. Org springframework. util. xml. Serializationutils is used for serialization and deserialization of Java Serialize and deserialize methods org springframework. util. xml. Stopwatch is a good tool class for recording execution time, and can be used for task phased test time Finally, it supports a nice print format This class should often use org springframework. util. xml. StringUtils org. springframework. util. xml. SystemPropertyUtils org. springframework. util. xml. Typeutils is used to judge the compatibility of types 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 class is used to build URL with string template. It will automatically process Chinese characters and other related codes in URL When reading URL resources provided by others, you should often use string url =“ http://localhost/myapp/ {name}/{id} "Org.springframework.web.util.javascript utils org.springframework.web.util.log4jconfiglistener configures the initialization of log4j in the web environment in the form of listener. Org.springframework.web.util.uritemplate org.springframework.web.util.uriutils handles the encoding of special characters in URI org.springframework.web.util.webutils org.springframework.web.util. 4. Encoded re Source (resource object, "UTF-8") encodes resources (special); 5.WebApplicationContextUtils 6. Encoding and decoding of stringescape utils
summary
The above is all about simply understanding the common tool classes in spring. I hope it will be helpful to you. Interested friends can refer to: introduction to the commonly used tool classes under the Java language Lang package, talking about the advantages of springboot to spring, Java spring annotation configuration bean instance code analysis, etc. you can leave a message at any time if you have any questions, and the editor will reply to you in time.