Spring常用工具类

简介: Spring框架下自带了丰富的工具类,在我们开发时可以简化很多工作: 1.Resource访问文件资源: 具体有: ResourceUtils.getFile(url); FileSystemResource(); ClassPathResource(); ServletContextResource(application,url); 2.

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 编码解码

文件资源操作

  1. 通过 FileSystemResource 以文件系统绝对路径的方式进行访问;
  2. 通过 ClassPathResource 以类路径的方式进行访问;
  3. 通过 ServletContextResource 以相对于 Web 应用根目录的方式进行访问。
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 甚至一个输出流或输出文件中。

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 指定编码格式,否则将会产生中文乱码的问题。

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

中文乱码过滤器

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

特殊字符转义

Web 开发者最常面对需要转义的特殊字符类型:
HTML 特殊字符;  
JavaScript 特殊字符;

HTML 特殊字符转义
& :&amp;  
" :&quot;< :&lt;  
>&gt;

JavaScript 特殊字符转义
' :/' 
" :/" 
/ ://  
走纸换页: /f  
换行:/n  
换栏符:/t  
回车:/r  
回退符:/b

 

目录
相关文章
|
9月前
|
XML 存储 Java
Spring重要类解析
Spring重要类解析
61 0
|
9月前
|
Java 数据库 数据安全/隐私保护
基于SSM框架实现管科类考研自我管理系统(分前后台spring+springmvc+mybatis+maven+jsp+jquery)
基于SSM框架实现管科类考研自我管理系统(分前后台spring+springmvc+mybatis+maven+jsp+jquery)
|
2月前
|
Java Spring
【Spring】方法注解@Bean,配置类扫描路径
@Bean方法注解,如何在同一个类下面定义多个Bean对象,配置扫描路径
181 73
|
2月前
|
Java Spring
【Spring配置相关】启动类为Current File,如何更改
问题场景:当我们切换类的界面的时候,重新启动的按钮是灰色的,不能使用,并且只有一个Current File 项目,下面介绍两种方法来解决这个问题。
|
4月前
|
Java 测试技术 Spring
springboot学习三:Spring Boot 配置文件语法、静态工具类读取配置文件、静态工具类读取配置文件
这篇文章介绍了Spring Boot中配置文件的语法、如何读取配置文件以及如何通过静态工具类读取配置文件。
313 0
springboot学习三:Spring Boot 配置文件语法、静态工具类读取配置文件、静态工具类读取配置文件
|
9月前
|
Java 调度 Maven
Spring Task 自定义定时任务类
Spring Task 自定义定时任务类
80 0
|
6月前
|
缓存 Java 开发者
Spring高手之路22——AOP切面类的封装与解析
本篇文章深入解析了Spring AOP的工作机制,包括Advisor和TargetSource的构建与作用。通过详尽的源码分析和实际案例,帮助开发者全面理解AOP的核心技术,提升在实际项目中的应用能力。
82 0
Spring高手之路22——AOP切面类的封装与解析
|
7月前
|
Java Spring
idea新建spring boot 项目右键无package及java类的选项
idea新建spring boot 项目右键无package及java类的选项
282 5
|
7月前
|
Java Spring
spring restTemplate 进行http请求的工具类封装
spring restTemplate 进行http请求的工具类封装
293 3
|
7月前
|
Java 数据库连接 API
Spring事务管理嵌套事务详解 : 同一个类中,一个方法调用另外一个有事务的方法
Spring事务管理嵌套事务详解 : 同一个类中,一个方法调用另外一个有事务的方法
522 1