Spring工具类整理

Spring自带的工具类

1. StringUtils

import org.springframework.util.StringUtils;

字符串判断

1.1 hasLength
  • 判断字符串长度是否大于1
StringUtils.hasLength(null);  // false
StringUtils.hasLength("");  // false
StringUtils.hasLength(" ");  // false

StringUtils.hasLength("Hello");  // true
1.2 hasText
  • 判断字符串中是否有字符
StringUtils.hasText(null);  // false
StringUtils.hasText("");  // false
StringUtils.hasText(" ");  // false

StringUtils.hasText("12345");  // true
StringUtils.hasText(" 12345 ");  // true
1.3 containsWhitespace
  • 判断是否包含空白字符
StringUtils.containsWhitespace(null);  //false
StringUtils.containsWhitespace("");  // false
StringUtils.containsWhitespace("a");  // false
StringUtils.containsWhitespace("abc");  // false
StringUtils.containsWhitespace("abc");  // false

StringUtils.containsWhitespace(" ");  // true
StringUtils.containsWhitespace(" a");  // true
StringUtils.containsWhitespace("abc ");  // true
StringUtils.containsWhitespace("a b");  // true
StringUtils.containsWhitespace("a  b");  // true
1.4 matchesCharacter
  • 判断字符串是否和指定的字符相等
char char3 = '/';
StringUtils.matchesCharacter("/", char3);  // true
StringUtils.matchesCharacter("hello", char3);  // false
1.5 startsWithIgnoreCase
  • 判断字符串是否以指定字符串开头,忽略大小写
StringUtils.startsWithIgnoreCase("Aabz", "a");  // true
StringUtils.startsWithIgnoreCase("babz", "ba");  // true

StringUtils.startsWithIgnoreCase("babz", "a");  // false
1.6 endsWithIgnoreCase
  • 判断字符串是否以指定字符串结尾,忽略大小写
StringUtils.endsWithIgnoreCase("AaBz", "bz");  // true
1.7 substringMatch
  • 判断从指定索引开始,是否匹配子字符串
StringUtils.substringMatch("aabbccdd", 1, "abb");  // true
StringUtils.substringMatch("aabbccdd", 0, "aabb");  // true

字符串删除

1.1 trimWhitespace
  • 去掉字符串中首尾的空白字符
StringUtils.trimWhitespace(null);  // null
StringUtils.trimWhitespace("");  // ""
StringUtils.trimWhitespace(" ");  // ""
StringUtils.trimWhitespace("\t");  // ""

StringUtils.trimWhitespace(" a");  // "a"
StringUtils.trimWhitespace("a ");  // "a"
StringUtils.trimWhitespace(" a ");  // "a"
StringUtils.trimWhitespace(" a b ");  // "a b";
1.2 trimAllWhitespace
  • 去掉字符串中所有的空白字符
StringUtils.trimAllWhitespace("");  // ""
StringUtils.trimAllWhitespace(" ");  // ""
StringUtils.trimAllWhitespace("\t");  // ""

StringUtils.trimAllWhitespace(" a");  // "a"
StringUtils.trimAllWhitespace("a ");  // "a"
StringUtils.trimAllWhitespace(" a ");  // "a"
StringUtils.trimAllWhitespace(" a b ");  // "ab"
StringUtils.trimAllWhitespace(" a b  c ");  // "abc"
1.3 trimLeadingWhitespace
  • 去掉字符串左边的空白字符
StringUtils.trimLeadingWhitespace(null);  // null
StringUtils.trimLeadingWhitespace("");  // ""
StringUtils.trimLeadingWhitespace(" ");  // ""
StringUtils.trimLeadingWhitespace("\t");  // ""

StringUtils.trimLeadingWhitespace(" a");  // "a"
StringUtils.trimLeadingWhitespace("a ");  // "a "
StringUtils.trimLeadingWhitespace(" a ");  // "a "
StringUtils.trimLeadingWhitespace(" a b ");  // "a b "
StringUtils.trimLeadingWhitespace(" a b  c ");  // "a b  c "
1.4 trimTrailingWhitespace
  • 去掉字符串右边边的空白字符
StringUtils.trimTrailingWhitespace(null);  // null
StringUtils.trimTrailingWhitespace(" ");  // ""
StringUtils.trimTrailingWhitespace("\t");  // ""
StringUtils.trimTrailingWhitespace("a ");  // "a"
StringUtils.trimTrailingWhitespace(" a");  // " a"
StringUtils.trimTrailingWhitespace(" a ");  // " a"
StringUtils.trimTrailingWhitespace(" a b ");  // " a b"
StringUtils.trimTrailingWhitespace(" a b  c ");  // " a b  c"
1.5 trimLeadingCharacter
  • 去掉字符串开头的指定字符
String testStr = "/1/h/e/l/lo";
StringUtils.trimLeadingCharacter(testStr, '/');  // "1/h/e/l/lo"

String testStr = "//h/e/l/lo";
StringUtils.trimLeadingCharacter(testStr, '/');  // "h/e/l/lo"
1.6 trimTrailingCharacter
  • 去掉字符串结尾的指定字符
  • 指定字符是char类型的,因此要用单引号’'来包裹
String testStr = "/1/h/e/l/lo";
StringUtils.trimTrailingCharacter(testStr, 'o');  // "/1/h/e/l/l"

String testStr = "/1/h/e/l/looo";
StringUtils.trimTrailingCharacter(testStr, 'o');  // "/1/h/e/l/l"
1.7 delete
  • 删除所有匹配的子字符串
StringUtils.delete("ababaabab", "ab");  // "a"
1.8 deleteAny
  • 删除子字符串中任意出现的字符
// 原字符串中包含了子字符串中的a和b,因此删除之后只会剩下z
StringUtils.deleteAny("ababaababz", "bar");  // "z"

字符串统计

1.14 countOccurrencesOf
  • 判断子字符串在字符串中出现的次数
StringUtils.countOccurrencesOf("ababaabab", "ab");  // 4

字符串转换

1.1 replace
  • 在字符串中使用子字符串替换
// 参数1:原字符串 参数2:待替换的字符串 参数3:要替换成的字符串
StringUtils.replace("ababaabab", "ab", "cd");  // "cdcdacdcd"
1.2 quote
  • 在字符串前后增加单引号,比较适合在日志时候使用
StringUtils.quote("hello");  // "'hello'"
1.3 quoteIfString
  • 如果是字符串的话,就在前后加单引号;如果不是字符串返回原对象
  • 返回值是Object类型
StringUtils.quoteIfString("hello");  // "'hello'"
1.4 capitalize
  • 首字母大写
StringUtils.capitalize("wolfcode");  // "Wolfcode"
1.5 uncapitalize
  • 取消首字母大写
StringUtils.uncapitalize("Java");  // "java"
1.6 collectionToDelimitedString
  • 将一个集合中的元素,使用前缀,后缀,分隔符拼装一个字符串,前缀后后缀是针对每一个字符串的
  • 有重载方法,只使用分隔符即可
String[] arrs=new String[]{"aa","bb","cc","dd"};
StringUtils.collectionToDelimitedString(Arrays.asList(arrs), ",", "{", "}");
// {aa},{bb},{cc},{dd}

String[] arrs=new String[]{"aa","bb","cc","dd"};
StringUtils.collectionToDelimitedString(Arrays.asList(arrs), ",");
// "aa,bb,cc,dd"
1.7 collectionToCommaDelimitedString
  • 集合变成逗号连接的字符串
  • collectionToDelimitedString(coll, ",");的简写
String[] arrs=new String[]{"aa","bb","cc","dd"};
StringUtils.collectionToDelimitedString(Arrays.asList(arrs));
// "aa,bb,cc,dd"

文件路径

1.1 unqualify
  • 得到以.分割的最后一个值,常用来获取类名或者文件后缀
StringUtils.unqualify("cn.wolfcode.java");  // "java"
StringUtils.unqualify("cn/wolfcode/Hello.java");  // "java"
StringUtils.unqualify("cn/wolfcode/Hello.java", File.separatorChar);  // "Hello.java"

// 如果原字符串中没有.的话,就返回原数据
StringUtils.unqualify("Hello", File.separatorChar);  // "Hello"
1.2 getFilename
  • 获取文件名
StringUtils.getFilename("mypath/myfile.txt");  // "myfile.txt"
1.3 getFilenameExtension
  • 获取文件后缀名
StringUtils.getFilenameExtension("mypath/myfile.txt");  // "txt"
1.4 stripFilenameExtension
  • 截取掉文件路径后缀
StringUtils.stripFilenameExtension("mypath/myfile.txt");  // "mypath/myfile"
1.5 applyRelativePath
  • 找到给定的文件,和另一个相对路径的文件,返回第二个文件的全路径
StringUtils.applyRelativePath("d:/java/wolfcode/Test.java", "other/Some.java");
// d:/java/wolfcode/other/Some.java

StringUtils.applyRelativePath("d:/java/wolfcode/Test.java", "Some.java");
// d:/java/wolfcode/Some.java

// 不支持重新定位绝对路径和上级目录等复杂一些的相对路径写法
StringUtils.applyRelativePath("d:/java/wolfcode/Test.java", "../other/Some.java");
// d:/java/wolfcode/../other/Some.java
1.6 cleanPath
1.7 pathEquals
  • 判断两个路径是否相同
StringUtils.pathEquals("d:\\java\\other\\Some.java", "d:/java/other/Some.java");  // true

转换为字符串数组

1.1 toStringArray
  • 字符串集合转换为字符串数组
List<String> strings = Arrays.asList("1", "2");
String[] result_toStringArray = StringUtils.toStringArray(strings);
// {"1", "2"}
1.2 addStringToArray
  • 把一个字符串添加到一个字符串数组中
StringUtils.addStringToArray(new String[] { "a", "b", "c" }, "d");
// { "a", "b", "c", "d"}
1.3 concatenateStringArrays
  • 合并两个字符串数组
String[] arry1 = { "a", "b", "c" };
String[] arry2 ={ "a", "b", "c", "d" };
// 数组不能直接打印,需要通过Arrays.toString()进行转换
System.out.println(Arrays.toString(result_concatenateStringArrays));
// ["a", "b", "c", "a", "b", "c", "d"]
1.4 sortStringArray
  • 字符串数组排序
StringUtils.sortStringArray(new String[]{"d","c","b","a"});  // ["a", "b", "c", "d"]
1.5 trimArrayElements
  • 把字符串数组中所有字符串执行trim功能
StringUtils.trimArrayElements(new String[]{"d  ","   c"});  // ["d", "c"]
1.6 removeDuplicateStrings
  • 去掉给定字符串数组中重复的元素,能保持原顺序
StringUtils.removeDuplicateStrings(new String[]{"a", "a", "b" ,"a", "c"});
// ["a", "b", "c"]
1.7 split
  • 按照指定字符串分割字符串,只分隔第一次
StringUtils.split("www.wolfcode.cn", ".");
// ["www", "wolfcode.cn"]
1.8 delimitedListToStringArray
  • 分割字符串,会把delimiter作为整体分隔符
StringUtils.delimitedListToStringArray("aa,ba,ca,da", "a,");
// ["a", "b", "c", "da"]

StringUtil.delimitedListToStringArray("h,e,l,l,o", ",");
// ["h", "e", "l", "l", "o"]
1.9 commaDelimitedListToStringArray
  • ,分隔字符串,是StringUtil.delimitedListToStringArray(XXX, ",");的简单写法
StringUtils.commaDelimitedListToStringArray("h,e,l,l,o");  // ["h", "e", "l", "l", "o"]

2. CollectionUtils

import org.springframework.util.CollectionUtils;

2.1 isEmpty

  • 判断一个集合是否为空
CollectionUtils.isEmpty(new HashMap<>());  // true
CollectionUtils.isEmpty(new ArrayList<>());  // true

2.2 arrayToList

  • 将数组转换为List

  • ==注意:==该方法内部用Arrays.asList(ObjectUtils.toObjectArray(source));进行的转换,

    如果向转换之后的List进行元素的增删操作,会报错

String[] arr = {"1", "2"};
List objects = CollectionUtils.arrayToList(arr);  // ["1", "2"]

2.3 mergeArrayIntoCollection

  • 将数组添加到集合当中
String[] arr = {"1", "2"};
List<String> list = new ArrayList<String>() {{
    add("A");
    add("B");
    add("C");
}};
CollectionUtils.mergeArrayIntoCollection(arr, list);  // ["A", "B", "C", "1", "2"]

2.4 containsInstance

  • 判断集合中是否包含实例对象
Student student = new Student();
ArrayList<Object> list = new ArrayList<Object>() {{
    add(new Student());
    add(new Student());
    add(student);
}};

// 第二个参数student和第一行被new出来的是一个对象,因此是包含的结果
boolean result = CollectionUtils.containsInstance(list, student);
System.out.println(result);  // true

2.5 containsAny

  • 只要两个集合中有任意一个元素相同,结果就是true
ArrayList<Object> list1 = new ArrayList<Object>() {{
    add("1");
    add("2");
    add("3");
}};

ArrayList<Object> list2 = new ArrayList<Object>() {{
    add("3");
    add("4");
}};


boolean result = CollectionUtils.containsAny(list1, list2);
System.out.println(result);  // true

2.6 findFirstMatch

  • 返回第一个匹配的元素
ArrayList<Object> list1 = new ArrayList<Object>() {{
    add("1");
    add("2");
    add("3");
}};

ArrayList<Object> list2 = new ArrayList<Object>() {{
    add("1");
    add("2");
    add("2");
    add("2");
    add("3");
}};

Object firstMatch = CollectionUtils.findFirstMatch(list1, list2);
System.out.println(firstMatch);  // "1"

2.7 hasUniqueObject

  • 判断集合中是否只有一个对象
ArrayList<Object> list = new ArrayList<Object>() {{
    add("1");
    
    // 如果把下面的注释解开,结果就变为了false
    // add("2");
}};

boolean result = CollectionUtils.hasUniqueObject(list2);
System.out.println(result);  // true

2.8 findCommonElementType

  • 返回集合中元素的类型
  • 如果一个集合中有多种类型的元素的话,会返回null
ArrayList<Object> list2 = new ArrayList<Object>() {{
    
    // 如果把下面的注释解开,集合中就会有多种类型的元素,就会返回null
    // add("1");
    // add("2");
    add(123);
    add(22);
    add(234);
}};

Class<?> commonElementType = CollectionUtils.findCommonElementType(list2);
System.out.println(commonElementType);  // class java.lang.Integer

2.9 firstElement

  • 返回第一个元素
ArrayList<Object> list2 = new ArrayList<Object>() {{
    add(123);
    add(22);
    add(234);
}};

Object o = CollectionUtils.firstElement(list2);
System.out.println(o);  // 123

3. NumberUtils

import org.springframework.util.NumberUtils;

3.1 convertNumberToTargetClass

  • 将Number类型的数字转换为指定类型
Integer integer = NumberUtils.convertNumberToTargetClass(1.256, Integer.class);
System.out.println(integer);  // 1

3.2 parseNumber

  • 将数字型字符串解析为 Number类型的数字
Integer integer = NumberUtils.parseNumber("1", Integer.class);
System.out.println(integer);  // 1

BigDecimal bigDecimal = NumberUtils.parseNumber("958412.2415", BigDecimal.class);
System.out.println(bigDecimal);  // 958412.2415

4. ObjectUtils

import org.springframework.util.ObjectUtils;

4.1 isEmpty

  • 判断一个对象是否为空
Student student = null;
Map map = null;

System.out.println(ObjectUtils.isEmpty(student));  // true
System.out.println(ObjectUtils.isEmpty(map));  // true

4.2 isArray

  • 判断一个对象是否是数组
Map map = null;
System.out.println(ObjectUtils.isArray(map));  // false

String[] arr = {"1", "2"};
System.out.println(ObjectUtils.isArray(arr));  // true

4.3 containsElement

  • 判断数组中是否包含某元素
String[] arr = {"1", "2"};
System.out.println(ObjectUtils.containsElement(arr, "1"));  // true
System.out.println(ObjectUtils.containsElement(arr, "3"));  // false

4.4 addObjectToArray

  • 向数组中添加元素
String[] arr = {"1", "2"};
// 返回一个新数组
String[] strings = ObjectUtils.addObjectToArray(arr, "111");
System.out.println(Arrays.toString(strings));  // [1, 2, 111]

5. FileCopyUtils

import org.springframework.util.FileCopyUtils;

5.1 copy(File in, File out)

  • 将a.txt文件中的内容复制到b.txt中.
  • 如果b.txt不存在,会报错.
  • 如果b.txt中有文本,会被覆盖
FileCopyUtils.copy(
    new File("E:\\copyTest\\from\\a.txt"), 
    new File("E:\\copyTest\\to\\b.txt")
);

5.2 copy(InputStream in, OutputStream out)

  • 如果b.txt不存在,会报错.
  • 如果b.txt中有文本,会被覆盖
File in = new File("E:\\copyTest\\from\\a.txt")
InputStream fileInputStream = new FileInputStream(in);
File out = new File("E:\\copyTest\\to\\b.txt")
OutputStream fileOutputStream = new FileOutputStream(out);

FileCopyUtils.copy(fileInputStream, fileOutputStream);

💥实际应用

@Autowired
private HttpServletResponse response;

// 获取到要下载的文件File对象
Path downloadFilePath = Paths.get("文件夹名称", "要下载的文件名称");
File downloadFile = downloadFilePath.toFile();

/*
	将要下载的文件直接拷贝到响应流中,
	response.getOutputStream()得到的是一个ServletOutputStream,而ServletOutputStream继承了OutputStream
*/ 
FileCopyUtils.copy(new FileInputStream(downloadFile), response.getOutputStream());

5.3 copy(Reader in, Writer out)

  • 如果b.txt不存在,会报错.
  • 如果b.txt中有文本,会被覆盖
Reader fileReader = new FileReader("E:\\copyTest\\from\\a.txt");
Writer fileWriter = new FileWriter(new File("E:\\copyTest\\to\\b.txt"));
FileCopyUtils.copy(fileReader, fileWriter);

5.4 copy(String in, Writer out)

  • 将文本复制到b.txt文件中,若文件中有内容则被覆盖
Writer fileWriter = new FileWriter(new File("E:\\copyTest\\to\\b.txt"));

FileCopyUtils.copy("hello world", fileWriter);

5.5 copy(byte[] in, File out)

  • 将文本复制到b.txt文件中,若文件中有内容则被覆盖
byte[] bytes = "hello java".getBytes(StandardCharsets.UTF_8);
FileCopyUtils.copy(bytes, new File("E:\\copyTest\\to\\b.txt"));

5.6 copy(byte[] in, OutputStream out)

  • 将文本复制到b.txt文件中,若文件中有内容则被覆盖
byte[] bytesObject = "hello mail".getBytes(StandardCharsets.UTF_8);
OutputStream out = new FileOutputStream(new File("E:\\copyTest\\to\\b.txt"));
FileCopyUtils.copy(bytesObject, out);

6. FileSystemUtils

import org.springframework.util.FileSystemUtils;

6.1 deleteRecursively(File root)

  • 递归删除文件夹,即使文件夹中有子文件夹也要被全部删除
File file = new File("C:\\Users\\XXX\\Desktop\\Test0426");
boolean result = FileSystemUtils.deleteRecursively(file);
System.out.println(result);  // true

6.2 deleteRecursively(Path root)

  • 递归删除文件夹,即使文件夹中有子文件夹也要被全部删除
Path path = Paths.get("C:\\Users\\XXX\\Desktop\\Test0426");
boolean result = FileSystemUtils.deleteRecursively(path);
System.out.println(result);  // true

6.3 copyRecursively(File src, File dest)

  • 复制一个文件夹下的所有文件和文件夹到另一个文件夹中
  • 如果目标文件夹中有同名文件会被覆盖,非同名文件则会被保留
  • 该方法无返回值
File file1 = new File("C:\\Users\\XXX\\Desktop\\Test0426");
File file2 = new File("C:\\Users\\XXX\\Desktop\\Test");
FileSystemUtils.copyRecursively(file1, file2);

6.4 copyRecursively(Path src, Path dest)

  • 复制一个文件夹下的所有文件和文件夹到另一个文件夹中
  • 如果目标文件夹中有同名文件会被覆盖,非同名文件则会被保留
  • 该方法无返回值
Path path1 = Paths.get("C:\\Users\\XXX\\Desktop\\Test0426");
Path path2 = Paths.get("C:\\Users\\XXX\\Desktop\\123");
FileSystemUtils.copyRecursively(path1, path2);

7. StreamUtils

import org.springframework.util.StreamUtils;

7.1 copy(byte[] in, OutputStream out)

  • 将字节拷贝到输入流中
String str = "hello world";
String path = "C:\\Users\\XXX\\Desktop\\Test0426\\新建文本文档.txt";

// 将字节拷贝到输出流中
StreamUtils.copy(str.getBytes(), new FileOutputStream(path));

7.2 copy(String in, Charset charset, OutputStream out)

  • 将字符串以特定编码拷贝到输出流中
String str = "hello world";
String path = "C:\\Users\\XXX\\Desktop\\Test0426\\新建文本文档.txt";

StreamUtils.copy(str, StandardCharsets.UTF_8, new FileOutputStream(path));

7.3 copy(InputStream in, OutputStream out)

  • 输入流拷贝到输出流
String path1 = "C:\\Users\\XXX\\Desktop\\Test0426\\新建文本文档1.txt";
String path2 = "C:\\Users\\XXX\\Desktop\\Test0426\\新建文本文档2.txt";

InputStream fileInputStream = new FileInputStream(path1);
OutputStream outputStream = new FileOutputStream(path2);

StreamUtils.copy(fileInputStream, outputStream);

7.4 copyToByteArray(InputStream in)

  • 将输入流拷贝成字节数组
String path1 = "C:\\Users\\XXX\\Desktop\\Test0426\\新建文本文档1.txt";
InputStream fileInputStream = new FileInputStream(path1);

byte[] bytes = StreamUtils.copyToByteArray(fileInputStream);

7.5 copyToString(InputStream in, Charset charset)

  • 输入流按照编码拷贝成字符串
String path1 = "C:\\Users\\XXX\\Desktop\\Test0426\\新建文本文档1.txt";
InputStream fileInputStream = new FileInputStream(path1);

String str = StreamUtils.copyToString(fileInputStream, StandardCharsets.UTF_8);
System.out.println(str); // 123

7.6 emptyInput()

  • 返回一个空的输入流
InputStream inputStream = StreamUtils.emptyInput();

8. ReflectionUtils

import org.springframework.util.ReflectionUtils;

9. Base64Utils

import org.springframework.util.Base64Utils;

10. UriUtils

import org.springframework.web.util.UriUtils;

11. WebUtils

import org.springframework.web.util.WebUtils;

11.1 File getTempDir( )

  • 获取临时文件夹路径
  • 返回由当前servlet容器提供的当前Web应用程序的临时目录

参考资料

1.JAVA基础之ServletContext对象

2.Java ServletContext详解

@Autowired
private HttpServletRequest request;

@Autowired
private ServletContext servletContext;

private void test() {

    // 通过request对象获取ServletContext上下文对象
    // ServletContext代表是一个web应用的环境(上下文)对象,
    // ServletContext对象内部封装是该web应用的信息,ServletContext对象一个web应用只有一个。
    ServletContext servletContext = request.getServletContext();

    // 获取临时文件夹路径
    File tempDir = WebUtils.getTempDir(servletContext);
    // 获取File对象的绝对路径地址
    System.out.println(tempDir.getAbsolutePath());
    // C:\Users\XXX\AppData\Local\Temp\tomcat.8080.34320\work\Tomcat\localhost\ROOT
}

11.2 String getRealPath( )

  • servletContext.getRealPath()的进一步封装

  • 从当前servlet 在tomcat 中的存放文件夹开始计算起

参考资料

1.什么是servletcontext.getRealPath(“/”),以及何时使用它

2.ServletContext.getRealPath() 的输入参数要以"/"开头

@Autowired
private HttpServletRequest request;

private void test() {

    String realPath = WebUtils.getRealPath(request.getServletContext(), "/");
    System.out.println(realPath);
    // C:\Users\XXX\AppData\Local\Temp\tomcat-docbase.8080.6245098134601554483\
    
    String realPath1 = WebUtils.getRealPath(request.getServletContext(), "/add");
    System.out.println(realPath1);
    // C:\Users\XXX\AppData\Local\Temp\tomcat-docbase.8080.6245098134601554483\add
}

11.3 String getSessionId( )

  • 获取项目中的session的id
@Autowired
private HttpServletRequest request;

@Autowired
private HttpServletResponse response;

@GetMapping("/locale")
public String locale(){

    // 自己新建一个cookie
    HttpSession session = request.getSession();
    // 将数据放入session
    session.setAttribute("shainNo", "XXX");
    
    return "locale";
}

private void test() {

    // 获取整个项目工程的session的ID
    String sessionId = WebUtils.getSessionId(request);
    System.out.println(sessionId);  // 0F21EEA34392BD5824AAD686D07892CD
}

11.4 Object getSessionAttribute( )

  • 根据key获取session中的value
@Autowired
private HttpServletRequest request;

@Autowired
private HttpServletResponse response;

@GetMapping("/locale")
public String locale(){

    // 自己新建一个cookie
    HttpSession session = request.getSession();
    // 将数据放入session
    session.setAttribute("shainNo", "XXX");

    return "locale";
}

private void test() {

    // 根据session的key来获取session的value
    Object shainNo = WebUtils.getSessionAttribute(request, "shainNo");
    System.out.println(shainNo);  // XXX
}

11.5 setSessionAttribute( )

  • 向session中放入key所对应的value
@Autowired
private HttpServletRequest request;

@Autowired
private HttpServletResponse response;

private void test() {

    // 向session中放入数据,key为shainNo;value为fengyehong
    WebUtils.setSessionAttribute(request, "shainNo", "fengyehong");
    System.out.println(WebUtils.getSessionAttribute(request, "shainNo"));  // fengyehong
}

11.6 getNativeRequest( )

参考资料

1.【小家Spring】Spring MVC好用工具介绍


  • HttpServletRequest转换为指定的request类型

  • 源码中会判断第二个参数是否为ServletRequestWrapper类型,是的话就进行转换,否则就返回null

  • 原本HttpServletRequest.getInputStream()只能获取一次,现在可以使用 getNativeRequest( )转换为

    ContentCachingRequestWrapper来将请求内容缓存起来,获取多次

import org.springframework.web.context.request.NativeWebRequest;
import javax.servlet.http.HttpServletRequest;

@Autowired
private HttpServletRequest request;

private void test() {

    // 将HttpServletRequest转换为NativeWebRequest类型
    NativeWebRequest nativeRequest = 
        WebUtils.getNativeRequest(request, NativeWebRequest.class);
    
    // 将HttpServletRequest转换为MultipartHttpServletRequest类型
    MultipartHttpServletRequest newRequest1 = 
        WebUtils.getNativeRequest(request, MultipartHttpServletRequest.class);
    
    // 将HttpServletRequest转换为ContentCachingRequestWrapper类型
    ContentCachingRequestWrapper newRequest2 =
               WebUtils.getNativeRequest(request, ContentCachingRequestWrapper.class);
}

11.7 getNativeResponse( )

  • 作用同上,将HttpServletResponse转化为指定的类型
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.util.ContentCachingResponseWrapper;

@Autowired
private HttpServletResponse response;

private void test() {

    // 将HttpServletResponse相应类型转换为ContentCachingResponseWrapper类型
    ContentCachingResponseWrapper nativeResponse = 
        WebUtils.getNativeResponse(response, ContentCachingResponseWrapper.class);
}

11.8 Cookie getCookie( )

  • 根据cookie的key,获取指定的cookie
@Autowired
private HttpServletRequest request;

@Autowired
private HttpServletResponse response;

@GetMapping("/locale")
public String locale(){

    // 自己新建一个cookie
    Cookie cookie = new Cookie("name","贾飞天");
    response.addCookie(cookie);

    return "locale";
}

// 测试用类
private void test() {

    // 根据key来获取整个cookie对象
    Cookie cookie = WebUtils.getCookie(request, "name");
    System.out.println(cookie.getName() + "-" + cookie.getValue());  // name-贾飞天
}

11.9 String findParameterValue( )

  • 寻找URL中参数对应的值
// locale?address=山东

@Autowired
private HttpServletRequest request;

private void test() {

    String address = WebUtils.findParameterValue(request, "address");
    System.out.println(address);  // 山东
}

11.10 Map<String, Object> getParametersStartingWith( )

  • 获取指定前缀的参数集合
// locale?test-address1=山东&test-address2=山西

Map<String, Object> map = WebUtils.getParametersStartingWith(request, "test-");
System.out.println(map);  // {address1=山东, address2=山西}

12. UrlPathHelper

import org.springframework.web.util.UrlPathHelper;

参考资料

1.Spring工具篇(1)- AntPathMatcher&&UrlPathHelper(针对URL进行处理)

项目URL配置

application.properties配置文件

# 端口号设置
server.port: 8082
# 应用程序的上下文设置
server.servlet.context-path: /wjec

配置类

@Bean
public ServletRegistrationBean dispatcherRegistration(DispatcherServlet dispatcherServlet) {
    return new ServletRegistrationBean(dispatcherServlet,"/api/*");
}

HTML中js的引用

<!--
当我们采用下面这种方式引用js文件的时候,thymeleaf会解析为 <script src="js/jquery.min.js"></script>
也就是 http://localhost:8082/wjec/api/js/jquery.min.js,从而可以引用成功
-->
<script th:src="@{js/jquery.min.js}"></script>

<!--
如果我们将js的引用写成下面的这种方式
<script th:src="@{/js/jquery.min.js}"></script>
thymeleaf会解析为
<script src="/wjec/js/jquery.min.js"></script>
因为我们还在配置类中添加了 /api/* 这个URL,因此会造成404
-->

发送ajax请求

// http://localhost:8082/wjec/api/locale/abc/123

getPathWithinServletMapping

import org.springframework.web.util.UrlPathHelper;

@Autowired
private HttpServletRequest request;

private void test(){

    // 创建一个UrlPathHelper的实例
    UrlPathHelper urlPathHelper = UrlPathHelper.defaultInstance;
    String path = urlPathHelper.getPathWithinServletMapping(request);
    System.out.println(path);  // /locale/abc/123
}

getPathWithinApplication

import org.springframework.web.util.UrlPathHelper;

@Autowired
private HttpServletRequest request;

private void test(){

    // 创建一个UrlPathHelper的实例
    UrlPathHelper urlPathHelper = UrlPathHelper.defaultInstance;
    String path = urlPathHelper.getPathWithinApplication(request);
    System.out.println(path);  // /api/locale/abc/123
}

getRequestUri

  • 获取请求的url
import org.springframework.web.util.UrlPathHelper;

@Autowired
private HttpServletRequest request;

private void test(){

    // 创建一个UrlPathHelper的实例
    UrlPathHelper urlPathHelper = UrlPathHelper.defaultInstance;
    String path = urlPathHelper.getRequestUri(request);
    System.out.println(path);  // /wjec/api/locale/abc/123
}

getContextPath

  • 获取应用程序上下文的路径
import org.springframework.web.util.UrlPathHelper;

@Autowired
private HttpServletRequest request;

private void test(){

    // 创建一个UrlPathHelper的实例
    UrlPathHelper urlPathHelper = UrlPathHelper.defaultInstance;
    String contextPath = urlPathHelper.getContextPath(request);
    System.out.println(contextPath);  // /wjec
}

getServletPath

  • 获取Servlet的路径
import org.springframework.web.util.UrlPathHelper;

@Autowired
private HttpServletRequest request;

private void test(){

    // 创建一个UrlPathHelper的实例
    UrlPathHelper urlPathHelper = UrlPathHelper.defaultInstance;
    String path = urlPathHelper.getServletPath(request);
    System.out.println(path);  // /api
}

getLookupPathForRequest

  • 根据请求查询路径
import org.springframework.web.util.UrlPathHelper;

@Autowired
private HttpServletRequest request;

private void test(){

    // 创建一个UrlPathHelper的实例
    UrlPathHelper urlPathHelper1 = new UrlPathHelper();
    // 设置AlwaysUseFullPath的值为false,则相当于getPathWithinServletMapping
    urlPathHelper1.setAlwaysUseFullPath(false);
    String path1 = urlPathHelper1.getLookupPathForRequest(request);
    System.out.println(path1);  // /locale/abc/123

    // 创建一个UrlPathHelper的实例
    UrlPathHelper urlPathHelper2 = new UrlPathHelper();
    // 设置AlwaysUseFullPath的值为true,则相当于getPathWithinApplication
    urlPathHelper2.setAlwaysUseFullPath(true);
    String path2 = urlPathHelper1.getLookupPathForRequest(request);
    System.out.println(path2);  // /api/locale/abc/123
}

13. AntPathMatcher

参考资料

1.一个用于匹配正则表达式的工具类AntPathMatcher

2.spring中的AntPathMatcher路径匹配规则

3.Spring之AntPathMatcher

4.Spring工具篇(1)- AntPathMatcher&&UrlPathHelper(针对URL进行处理)

13.1 match()

作用

多用来对URL进行匹配判断

  • 匹配一个字符

    /trip/a/a?x    匹配 /trip/a/abx; 但不匹配 /trip/a/ax,/trip/a/abcx
    
  • *匹配0个或多个字符

    /trip/api/*x   匹配 /trip/api/x,/trip/api/ax,/trip/api/abx; 但不匹配 /trip/abc/x
    
  • **匹配0个或多个目录

    /**/api/alie   匹配 /trip/api/alie,/trip/dax/api/alie; 但不匹配 /trip/a/api
    
import org.springframework.util.AntPathMatcher;

public static void main(String[] args) {
    AntPathMatcher antPathMatcher = new AntPathMatcher();
    boolean match1 = antPathMatcher.match("/freebytes/**", "/freebytes/1getA");
    boolean match2 = antPathMatcher.match("/freebytes/*/get*", "/freebytes/te/getA");
    boolean match3 = antPathMatcher.match("/freebytes/*/get*", "/freebytes/te/1getA");
    System.out.println(match1);  // true
    System.out.println(match2);  // true
    System.out.println(match3);  // false
}

13.2 combine( )

  • 用于URL的拼接
import org.springframework.web.util.UrlPathHelper;
import org.springframework.web.util.AntPathMatcher;

@Autowired
private HttpServletRequest request;

private void test(){

    AntPathMatcher antPathMatcher = new AntPathMatcher();
    // 通过UrlPathHelper获取当前程序的Servlet路径
    String servletPath = UrlPathHelper.defaultInstance.getServletPath(request);

    String combinedUrl1 = antPathMatcher.combine("/hotels/*", servletPath);
    System.out.println(combinedUrl1);  // /hotels/api

    String combinedUrl2 = antPathMatcher.combine("/hotels/**", servletPath);
    System.out.println(combinedUrl2);  // /hotels/**/api
}

具体使用参照下表

模式1模式2结果
nullnullnull
/hotelsnull/hotels
null/hotels/hotels
/hotels/bookings/hotels/bookings
/hotelsbookings/hotels/bookings
/hotels/*/bookings/hotels/bookings
/hotels/**/bookings/hotels/**/bookings
/hotels{hotel}/hotels/{hotel}
/hotels/*{hotel}/hotels/{hotel}
/hotels/**{hotel}/hotels/**/{hotel}
/*.html/hotels.html/hotels.html
/*.html/hotels/hotels.html
/*.html/*.txtIllegalArgumentException

14. AnnotationUtils

import org.springframework.core.annotation.AnnotationUtils;

15. ClassUtils

import org.springframework.util.ClassUtils;

16. PropertiesLoaderUtils

import org.springframework.core.io.support.PropertiesLoaderUtils;

参考资料

1.Spring中的各种Utils(一):PropertiesLoaderUtils

16.1 loadProperties( )

  • 多用于从properties配置文件中读取配置信息

配置文件test.properties

test.name=jiafeitian

读取配置文件中的配置信息

import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.core.io.ClassPathResource;

private void test() throws Exception {
    
    // 构造ClassPathResource对象
    ClassPathResource classPathResource = new ClassPathResource("test.properties");
    // 将配置文件中的配置信息构造为Properties对象
    Properties properties = PropertiesLoaderUtils.loadProperties(classPathResource);
    
    // 从Properties对象中根据key来获取value
    System.out.println(properties.getProperty("test.name"));
}

17. UriComponentsBuilder

  • Spring 提供的一个 UriComponents 类的构建类,通过它可以方便的构建URI地址

17.1 构造简单的URL

import org.springframework.web.util.UriComponentsBuilder;

// 构建一个UriComponents对象
UriComponents uriComponents =
    UriComponentsBuilder.newInstance()
    // 可以通过链式编程的方法,细粒度的指定url的每一个部分
    .scheme("http")
    .host("www.baidu.com")
    .port("8080")
    .path("/junit-5")
    .build();

System.out.println(uriComponents.toUriString()); // http://www.baidu.com:8080/junit-5
System.out.println(uriComponents.toString());  // http://www.baidu.com:8080/junit-5

17.2 构造模板URL

import org.springframework.web.util.UriComponentsBuilder;

// 构建一个UriComponents对象
UriComponents uriComponents = 
    UriComponentsBuilder.newInstance()
    .scheme("http")
    .host("www.baeldung.com")
    // 我们可以在path()里面添加URL模板,必须要用{}进行包裹
    .path("/{article-name}")
    .path("/{test}")
    // 向path中的模板添加参数
    .buildAndExpand("fengyehong", "jiafeitian");

System.out.println(uriComponents.toUriString()); 
// http://www.baeldung.com/fengyehong/jiafeitian

17.3 构造查询URL

import org.springframework.web.util.UriComponentsBuilder;

UriComponents uriComponents = UriComponentsBuilder.newInstance()
    .scheme("http")
    .host("www.baeldung.com")
    .path("/")
    .query("q={keyword}")
    .buildAndExpand("baeldung");

System.out.println(uriComponents.toUriString()); // http://www.baeldung.com/?q=baeldung

17.4 fromHttpUrl构造查询URL

import org.springframework.web.util.UriComponentsBuilder;
import org.springframework.util.LinkedMultiValueMap;

MultiValueMap<String, String> mapParam = new LinkedMultiValueMap<String, String>();
o1.add("jia","feitian");
o1.add("hello","java" );

UriComponents uriComponents = UriComponentsBuilder
    // 最简单粗暴的UriComponents构造方式
    .fromHttpUrl("http://localhost:8080//hello")
    // 构造查询参数,参数是一个Map
    .queryParams(mapParam)
    .build();

System.out.println(uriComponents.toUriString()); 
// http://localhost:8080/hello?jia=feitian&hello=java

18. RequestContextUtils

配置文件

# 端口号设置
server.port: 8082
# 应用程序的上下文设置
server.servlet.context-path: /wjec

多用来获取WebApplicationContext上下文对象

import org.springframework.web.servlet.support.RequestContextUtils;

@Autowired
private HttpServletRequest request;

private void test(){

    WebApplicationContext obj = RequestContextUtils.findWebApplicationContext(request);
    System.out.println(obj.getApplicationName());  // /wjec
}

19. WebApplicationContextUtils

用于获取WebApplicationContext上下文对象

配置文件

# 端口号设置
server.port: 8082
# 应用程序的上下文设置
server.servlet.context-path: /wjec

19.1 getApplicationName( )

  • 获取应用程序名称
import org.springframework.web.servlet.support.WebApplicationContextUtils;

// ServletContext上下文对象在WEB程序初始化完成之后就被加载到容器当中
@Autowired
private ServletContext servletContext;

private void test(){

    WebApplicationContext obj = WebApplicationContextUtils.findWebApplicationContext(servletContext);
    System.out.println(obj.getApplicationName());  // /wjec
}

19.2 containsBean( )

  • 判断容器中是否有指定的Bean
import org.springframework.web.servlet.support.WebApplicationContextUtils;

@Autowired
private ServletContext servletContext;

@Bean("testBean")  // 给Bean取一个别名
public Student addStudentToBean() {
    return  new Student("fengyehong", "13");
}

private void test() {

    WebApplicationContext webApplicationContext = WebApplicationContextUtils.findWebApplicationContext(servletContext);
    // 判断IOC容器中是否有名称为testBean的Bean对象
    System.out.println(webApplicationContext.containsBean("testBean"));
}

19.3 getBean( )

  • 获取IOC容器中的Bean对象
  • 有多个重载方法,除了可以根据Bean名称获取对象外,还可以根据Bean对象的class或者注解来获取Bean对象
import org.springframework.web.servlet.support.WebApplicationContextUtils;

@Autowired
private ServletContext servletContext;

@Bean("testBean")  // 给Bean取一个别名
public Student addStudentToBean() {
    return  new Student("fengyehong", "13");
}

private void test() {

    WebApplicationContext webApplicationContext = WebApplicationContextUtils.findWebApplicationContext(servletContext);
    
    // 根据别名获取存放在IOC容器中的bean
    Student student = (Student)webApplicationContext.getBean("testBean");
    System.out.println(student.getName());  // fengyehong
}

20. BeanUtils

实体类对象的拷贝

import org.springframework.beans.BeanUtils;

BeanUtils.copyProperties(fromBean, toBean, ignores);

Java自带工具类

UUID的获取

import java.util.UUID;

UUID.randomUUID();

校验上传的是否是图片

import org.springframework.web.multipart.MultipartFile;
import org.apache.commons.lang.StringUtils;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;

public void uploadImage(MultipartFile file) {

    // 获取上传的文件对象
    String originalFilename = file.getOriginalFilename();
    // 使用工具类来获取后缀
    String ext = StringUtils.substringAfterLast(originalFilename, ".");
    // 获取上传的文件的类型
    String contentType = file.getContentType();

    // 校验图片的内容,我们使用工具类ImageIO来校验是否为图片
    // ImageIO.read() ==> 把图片转换为二进制的图片
    BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
    if (bufferedImage == null){
        System.out.println("文件内容不合法:{}" + originalFilename);
    }
}

String.join的使用

  • 将集合中的每个元素添加特定的字符,转换为字符串
String[] text = {"hello", "world","are","you","ok","?"};
System.out.println(String.join(",", text));  // "hello,world,are,you,ok,?"

List<String> sList = new ArrayList<>();
sList.add("a");
sList.add("b");
sList.add("c");
System.out.println(String.join("-", sList));  // "a-b-c"

System.out.println(String.join("\t","I","am","a","student"));  // "I	am	a	student"
System.out.println(String.join("-","I","am","a","student"));  // "I-am-a-student"
  • 7
    点赞
  • 47
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值