import org.springframework.util.StringUtils;
StringUtils.hasLength(null); // false
StringUtils.hasLength(""); // false
StringUtils.hasLength(" "); // false
StringUtils.hasLength("Hello"); // true
StringUtils.hasText(null); // false
StringUtils.hasText(""); // false
StringUtils.hasText(" "); // false
StringUtils.hasText("12345"); // true
StringUtils.hasText(" 12345 "); // true
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
char char3 = '/';
StringUtils.matchesCharacter("/", char3); // true
StringUtils.matchesCharacter("hello", char3); // false
StringUtils.startsWithIgnoreCase("Aabz", "a"); // true
StringUtils.startsWithIgnoreCase("babz", "ba"); // true
StringUtils.startsWithIgnoreCase("babz", "a"); // false
StringUtils.endsWithIgnoreCase("AaBz", "bz"); // true
StringUtils.substringMatch("aabbccdd", 1, "abb"); // true
StringUtils.substringMatch("aabbccdd", 0, "aabb"); // true
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";
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"
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 "
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"
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"
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"
StringUtils.delete("ababaabab", "ab"); // "a"
// 原字符串中包含了子字符串中的a和b,因此删除之后只会剩下z
StringUtils.deleteAny("ababaababz", "bar"); // "z"
StringUtils.countOccurrencesOf("ababaabab", "ab"); // 4
// 参数1:原字符串 参数2:待替换的字符串 参数3:要替换成的字符串
StringUtils.replace("ababaabab", "ab", "cd"); // "cdcdacdcd"
StringUtils.quote("hello"); // "'hello'"
StringUtils.quoteIfString("hello"); // "'hello'"
StringUtils.capitalize("wolfcode"); // "Wolfcode"
StringUtils.uncapitalize("Java"); // "java"
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"
collectionToDelimitedString(coll, ",");
的简写String[] arrs=new String[]{"aa","bb","cc","dd"};
StringUtils.collectionToDelimitedString(Arrays.asList(arrs));
// "aa,bb,cc,dd"
.
分割的最后一个值,常用来获取类名或者文件后缀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"
StringUtils.getFilename("mypath/myfile.txt"); // "myfile.txt"
StringUtils.getFilenameExtension("mypath/myfile.txt"); // "txt"
StringUtils.stripFilenameExtension("mypath/myfile.txt"); // "mypath/myfile"
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
StringUtils.pathEquals("d:\\java\\other\\Some.java", "d:/java/other/Some.java"); // true
List<String> strings = Arrays.asList("1", "2");
String[] result_toStringArray = StringUtils.toStringArray(strings);
// {"1", "2"}
StringUtils.addStringToArray(new String[] { "a", "b", "c" }, "d");
// { "a", "b", "c", "d"}
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"]
StringUtils.sortStringArray(new String[]{"d","c","b","a"}); // ["a", "b", "c", "d"]
StringUtils.trimArrayElements(new String[]{"d "," c"}); // ["d", "c"]
StringUtils.removeDuplicateStrings(new String[]{"a", "a", "b" ,"a", "c"});
// ["a", "b", "c"]
StringUtils.split("www.wolfcode.cn", ".");
// ["www", "wolfcode.cn"]
StringUtils.delimitedListToStringArray("aa,ba,ca,da", "a,");
// ["a", "b", "c", "da"]
StringUtil.delimitedListToStringArray("h,e,l,l,o", ",");
// ["h", "e", "l", "l", "o"]
,
分隔字符串,是StringUtil.delimitedListToStringArray(XXX, ",");
的简单写法StringUtils.commaDelimitedListToStringArray("h,e,l,l,o"); // ["h", "e", "l", "l", "o"]
import org.springframework.util.CollectionUtils;
CollectionUtils.isEmpty(new HashMap<>()); // true
CollectionUtils.isEmpty(new ArrayList<>()); // true
将数组转换为List
==注意:==该方法内部用Arrays.asList(ObjectUtils.toObjectArray(source));
进行的转换,
如果向转换之后的List进行元素的增删操作,会报错
String[] arr = {"1", "2"};
List objects = CollectionUtils.arrayToList(arr); // ["1", "2"]
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"]
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
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
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"
ArrayList<Object> list = new ArrayList<Object>() {{
add("1");
// 如果把下面的注释解开,结果就变为了false
// add("2");
}};
boolean result = CollectionUtils.hasUniqueObject(list2);
System.out.println(result); // true
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
ArrayList<Object> list2 = new ArrayList<Object>() {{
add(123);
add(22);
add(234);
}};
Object o = CollectionUtils.firstElement(list2);
System.out.println(o); // 123
import org.springframework.util.NumberUtils;
Integer integer = NumberUtils.convertNumberToTargetClass(1.256, Integer.class);
System.out.println(integer); // 1
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
import org.springframework.util.ObjectUtils;
Student student = null;
Map map = null;
System.out.println(ObjectUtils.isEmpty(student)); // true
System.out.println(ObjectUtils.isEmpty(map)); // true
Map map = null;
System.out.println(ObjectUtils.isArray(map)); // false
String[] arr = {"1", "2"};
System.out.println(ObjectUtils.isArray(arr)); // true
String[] arr = {"1", "2"};
System.out.println(ObjectUtils.containsElement(arr, "1")); // true
System.out.println(ObjectUtils.containsElement(arr, "3")); // false
String[] arr = {"1", "2"};
// 返回一个新数组
String[] strings = ObjectUtils.addObjectToArray(arr, "111");
System.out.println(Arrays.toString(strings)); // [1, 2, 111]
import org.springframework.util.FileCopyUtils;
FileCopyUtils.copy(
new File("E:\\copyTest\\from\\a.txt"),
new File("E:\\copyTest\\to\\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());
Reader fileReader = new FileReader("E:\\copyTest\\from\\a.txt");
Writer fileWriter = new FileWriter(new File("E:\\copyTest\\to\\b.txt"));
FileCopyUtils.copy(fileReader, fileWriter);
Writer fileWriter = new FileWriter(new File("E:\\copyTest\\to\\b.txt"));
FileCopyUtils.copy("hello world", fileWriter);
byte[] bytes = "hello java".getBytes(StandardCharsets.UTF_8);
FileCopyUtils.copy(bytes, new File("E:\\copyTest\\to\\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);
import org.springframework.util.FileSystemUtils;
File file = new File("C:\\Users\\XXX\\Desktop\\Test0426");
boolean result = FileSystemUtils.deleteRecursively(file);
System.out.println(result); // true
Path path = Paths.get("C:\\Users\\XXX\\Desktop\\Test0426");
boolean result = FileSystemUtils.deleteRecursively(path);
System.out.println(result); // true
File file1 = new File("C:\\Users\\XXX\\Desktop\\Test0426");
File file2 = new File("C:\\Users\\XXX\\Desktop\\Test");
FileSystemUtils.copyRecursively(file1, file2);
Path path1 = Paths.get("C:\\Users\\XXX\\Desktop\\Test0426");
Path path2 = Paths.get("C:\\Users\\XXX\\Desktop\\123");
FileSystemUtils.copyRecursively(path1, path2);
import org.springframework.util.StreamUtils;
String str = "hello world";
String path = "C:\\Users\\XXX\\Desktop\\Test0426\\新建文本文档.txt";
// 将字节拷贝到输出流中
StreamUtils.copy(str.getBytes(), new FileOutputStream(path));
String str = "hello world";
String path = "C:\\Users\\XXX\\Desktop\\Test0426\\新建文本文档.txt";
StreamUtils.copy(str, StandardCharsets.UTF_8, new FileOutputStream(path));
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);
String path1 = "C:\\Users\\XXX\\Desktop\\Test0426\\新建文本文档1.txt";
InputStream fileInputStream = new FileInputStream(path1);
byte[] bytes = StreamUtils.copyToByteArray(fileInputStream);
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
InputStream inputStream = StreamUtils.emptyInput();
import org.springframework.util.ReflectionUtils;
import org.springframework.util.Base64Utils;
import org.springframework.web.util.UriUtils;
import org.springframework.web.util.WebUtils;
参考资料
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
}
对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
}
@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
}
@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
}
@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
}
参考资料
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);
}
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);
}
@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-贾飞天
}
// locale?address=山东
@Autowired
private HttpServletRequest request;
private void test() {
String address = WebUtils.findParameterValue(request, "address");
System.out.println(address); // 山东
}
// locale?test-address1=山东&test-address2=山西
Map<String, Object> map = WebUtils.getParametersStartingWith(request, "test-");
System.out.println(map); // {address1=山东, address2=山西}
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的引用
<script th:src="@{js/jquery.min.js}">script>
发送ajax请求
// http://localhost:8082/wjec/api/locale/abc/123
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
}
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
}
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
}
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
}
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
}
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
}
参考资料
1.一个用于匹配正则表达式的工具类AntPathMatcher
2.spring中的AntPathMatcher路径匹配规则
3.Spring之AntPathMatcher
4.Spring工具篇(1)- AntPathMatcher&&UrlPathHelper(针对URL进行处理)
作用
多用来对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
}
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 | 结果 |
---|---|---|
null | null | null |
/hotels | null | /hotels |
null | /hotels | /hotels |
/hotels | /bookings | /hotels/bookings |
/hotels | bookings | /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 | /*.txt | IllegalArgumentException |
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.util.ClassUtils;
import org.springframework.core.io.support.PropertiesLoaderUtils;
参考资料
1.Spring中的各种Utils(一):PropertiesLoaderUtils
配置文件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"));
}
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
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
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
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
配置文件
# 端口号设置
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
}
用于获取WebApplicationContext上下文对象
配置文件
# 端口号设置
server.port: 8082
# 应用程序的上下文设置
server.servlet.context-path: /wjec
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
}
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"));
}
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
}
实体类对象的拷贝
import org.springframework.beans.BeanUtils;
BeanUtils.copyProperties(fromBean, toBean, ignores);
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[] 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"