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 in the absolute path of the file system;
- Access by Classpathresource in a classpath manner;
- Access is done through Servletcontextresource in a way that is relative to the Web Application's root directory.
packagecom.baobaotao.io;Importjava.io.IOException;Importjava.io.InputStream;Importorg.springframework.core.io.ClassPathResource;Importorg.springframework.core.io.FileSystemResource;Importorg.springframework.core.io.Resource; public classFilesourceexample { public Static voidmain (string[] Args) {Try{String FilePath= "d:/masterspring/chapter23/webapp/web-inf/classes/conf/file1.txt"; //① loading files using the System file path methodResource res1 =NewFilesystemresource (filePath); //② loading files with classpath modeResource Res2 =NewClasspathresource ("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"); = "file:d:/masterspring/chapter23/src/conf/file1.txt"= 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.
packagecom.baobaotao.io;Importjava.io.ByteArrayOutputStream;Importjava.io.File;Importjava.io.FileReader;Importjava.io.OutputStream;Importorg.springframework.core.io.ClassPathResource;Importorg.springframework.core.io.Resource;Importorg.springframework.util.FileCopyUtils; public classFilecopyutilsexample { public Static voidMain (string[] Args)throwsthrowable {Resource Res=NewClasspathresource ("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 StringString filestr = filecopyutils.copytostring (NewFileReader (res.getfile ())); //③ Copying the contents of a file to another destination filefilecopyutils.copy (res.getfile (),NewFile (res.getfile (). getParent () + "/file2.txt")); //④ Copying the contents of a file into an output streamOutputStream OS =NewBytearrayoutputstream (); Filecopyutils.copy (res.getinputstream (), os); }}Static voidCopybyte[] in, File Out) willbyte[] Copy to a fileStatic voidCopybyte[] in, OutputStream Out) willbyte[] Copy to an output streamStatic intcopy (file, file out) copies files to another fileStatic intcopy (inputstream in, OutputStream out) copies the input stream to the output streamStatic intcopy (reader in, Writer Out) copies the content read by reader to Writer pointing to the target outputStatic voidcopy (string in, Writer Out) copies the string to a target in which writer points a property file operation Spring provides a propertiesloaderutils that allows you to load directly from a file address based on a classpath Sexual Resources packagecom.baobaotao.io;Importjava.util.Properties;Importorg.springframework.core.io.support.PropertiesLoaderUtils; public classPropertiesloaderutilsexample { public Static voidMain (string[] Args)throwsThrowable {//①jdbc.properties is a file located under the ClasspathProperties 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.
packagecom.baobaotao.io;Importorg.springframework.core.io.ClassPathResource;Importorg.springframework.core.io.Resource;Importorg.springframework.core.io.support.EncodedResource;Importorg.springframework.util.FileCopyUtils; public classEncodedresourceexample { public Static voidMain (string[] Args)throwsthrowable {Resource Res=NewClasspathresource ("conf/file1.txt"); //① the encoding format for the specified file resource (UTF-8)Encodedresource encres =NewEncodedresource (res, "UTF-8"); //② so that the contents of the file can be read correctly without garbledString 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 == webapplicationcontextutils. Getwebapplicationcontext (servletcontext);
Spring provides filter and listener delay load filters
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 < Param-name>encoding</param-name> <param-value>UTF-8</param-value></init-param>< Init-param>③ Force encoding conversion <param-name>forceEncoding</param-name> & Lt;param-value>true </param-value></init-param></filter ><filter-mapping>② filter match URL <filter-name>encodingfilter</ Filter-name> <url-pattern>*.html</url-pattern></filter-mapping>
In general, you must log4j.properties the log4j log profile to a file name and save it under the Classpath. The
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 profile <context-param> <param-name> Log4jconfiglocation</param-name> <param-value>/web-inf/log4j.properties</param-value></ Context-param>② Use this listener to initialize 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,
This will not occur when the latter covers the former Problem. 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 most often face special types of characters that need to be escaped:
* HTML 特殊字符;
* JavaScript 特殊字符;
HTML Special Character escapes
* & :&
* " :"
* < :<
* > :>
JavaScript Special Character escapes
*
‘ :/‘
*
" :/"
* / :
//
* 走纸换页: /f
* 换行:/n
* 换栏符:/t
* 回车:/r
* 回退符:/b
Tool class
JavaScriptUtils.javaScriptEscape(String str);
HtmlUtils.htmlEscape(String str);①转换为HTML转义字符表示
HtmlUtils.htmlEscapeDecimal(String str); ②转换为数据转义表示
HtmlUtils.htmlEscapeHex(String str); ③转换为十六进制数据转义表示
HtmlUtils.htmlUnescape(String str);将经过转义内容还原
The spring framework comes with a rich toolset that simplifies much of the work as we develop: 1.Resource access to file Resources:
ResourceUtils.getFile(url);
FileSystemResource(); ClassPathResource();
ServletContextResource(application,url);
2. File Operation Filecopyutils
Filecopyutils.copy (resource.getfile,new file (resource.getfile (), getParent () + ' target filename '));
3. Property file Operation Propertiesloaderutils
Specifically:
Propertiesloaderutils.loadallproperties ("attribute File name"); --based on class Path 4. Encodedresource (resource object, "utf-8″") encoded resource (special); 5.webapplicationcontextutils6.stringescapeutils encoding decoding
Spring Common tool Classes