Spring应用最常用的工具类汇总

发布时间 2023-12-26 17:59:53作者: 残城碎梦

文件资源访问

假设有一个文件地址位于 Web 应用的类路径下,您可以通过以下方式对这个文件资源进行访问:

  • FileSystemResource 以文件系统绝对路径的方式进行访问;
  • ClassPathResource 以类路径的方式进行访问;
  • ServletContextResource 以相对于 Web 应用根目录的方式进行访问。
  • ResourceUtils 它支持“classpath:”和“file:”的地址前缀,它能够从指定的地址加载文件资源,常用方法:getFile()

示例:

// 从Web Context下的WEB-INF路径下读取name.txt资源
WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
ServletContext servletContext = webApplicationContext.getServletContext();
//ServletContextResource resource = new ServletContextResource(servletContext, "WEB-INF/name.txt");

// 绝对路径
//FileSystemResource resource = new FileSystemResource("D:\\ideawork\\springboot-samples\\changyong\\src\\main\\resources\\name.txt");
// 类路径
ClassPathResource resource = new ClassPathResource("name.txt");
// 获取文件名
System.out.println("resource.getFileName = " + resource.getFilename());
// 获取文件描述
System.out.println("resource.getDescription = " + resource.getDescription());
// 获取文件内容
//File file = ResourceUtils.getFile("classpath:name.txt");
File file = ResourceUtils.getFile("file:D:\\ideawork\\springboot-samples\\changyong\\src\\main\\resources\\name.txt");
InputStream in = new FileInputStream(file);
//InputStream in = resource.getInputStream();
byte[] b = new byte[1024];
while (in.read(b) != -1) {
    System.out.println(new String(b));
}

本地化文件资源 LocalizedResourceHelper

本地化文件资源是一组通过本地化标识名进行特殊命名的文件,Spring 提供的 LocalizedResourceHelper 允许通过文件资源基名和本地化实体获取匹配的本地化文件资源并以 Resource 对象返回。假设在类路径的 i18n 目录下,拥有一组基名为 message 的本地化文件资源。

LocalizedResourceHelper lrHalper = new LocalizedResourceHelper();
// ① 获取对应美国的本地化文件资源
Resource msg_us = lrHalper.findLocalizedResource("i18n/message", ".properties", Locale.US);
// ② 获取对应中国大陆的本地化文件资源
Resource msg_cn = lrHalper.findLocalizedResource("i18n/message", ".properties", Locale.CHINA);

文件操作 FileCopyUtils

FileCopyUtils,它提供了许多一步式的静态操作方法,能够将文件内容拷贝到一个目标 byte[]、String 甚至一个输出流或输出文件中。

示例:

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

属性文件操作 PropertiesLoaderUtils

通过 java.util.Properties的load(InputStream inStream) 方法从一个输入流中加载属性资源。Spring 提供的 PropertiesLoaderUtils 允许您直接通过基于类路径的文件地址加载属性资源。

示例:

// ① jdbc.properties 是位于类路径下的文件
Properties props = PropertiesLoaderUtils.loadAllProperties("jdbc.properties");
  • static Properties loadProperties(Resource resource) -->从 Resource 中加载属性
  • static void fillProperties(Properties props, Resource resource)-->将 Resource 中的属性数据添加到一个已经存在的 Properties 对象中。

特殊编码的资源 EncodedResource

当您使用 Resource 实现类加载文件资源时,它默认采用操作系统的编码格式。如果文件资源采用了特殊的编码格式(如 UTF-8),则在读取资源内容时必须事先通过 EncodedResource 指定编码格式,否则将会产生中文乱码的问题。

Resource res = new ClassPathResource("conf/file1.txt");
// ① 指定文件资源对应的编码格式(UTF-8)
EncodedResource encRes = new EncodedResource(res,"UTF-8");
String content  = FileCopyUtils.copyToString(encRes.getReader());

WebApplicationContextUtils 

WebApplicationContextUtils 工具类获取 WebApplicationContext 对象

WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletContext sc);

我们也可以通过WebApplicationContext获取ServletContext:

WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
ServletContext servletContext = webApplicationContext.getServletContext();

WebUtils

  • getCookie(HttpServletRequest request, String name) 获取 HttpServletRequest 中特定名字的 Cookie 对象。如果您需要创建 Cookie, Spring 也提供了一个方便的 CookieGenerator 工具类
  • getSessionAttribute(HttpServletRequest request, String name) 获取 HttpSession 特定属性名的对象,否则您必须通过 request.getHttpSession.getAttribute(name) 完成相同的操作
  • getRequiredSessionAttribute(HttpServletRequest request, String name) 和上一个方法类似,只不过强制要求 HttpSession 中拥有指定的属性,否则抛出异常;
  • getSessionId(HttpServletRequest request) 获取 Session ID 的值;void exposeRequestAttributes(ServletRequest request, Map attributes) 将 Map 元素添加到 ServletRequest 的属性列表中,当请求被导向(forward)到下一个处理程序时,这些请求属性就可以被访问到了;

中文乱码过滤器 CharacterEncodingFilter 

通过表单向服务器提交数据时,一个经典的问题就是中文乱码问题。虽然我们所有的 JSP 文件和页面编码格式都采用 UTF-8,但这个问题还是会出现。解决的办法很简单,我们只需要在 web.xml 中配置一个 Spring 的编码转换过滤器就可以了。

请求跟踪日志过滤器 ServletContextRequestLoggingFilter

在日志级别为 DEBUG 时才会起作用。

请求工具类 ServletRequestUtils

//取请求参数的整数值
public static Integer getIntParameter(ServletRequest request, String name)
public static int getIntParameter(ServletRequest request, String name, int defaultVal)  //单个值
public static int[] getIntParameters(ServletRequest request, String name) //数组

还有譬如long、float、double、boolean、String的相关处理方法。

目录复制 FileSystemUtils 

递归复制、删除一个目录。