AntPathMatcher
- package org.springframework.util
public class AntPathMatcher extends Object implements PathMatcher - 路径匹配器,可用来匹配路径,如:过滤请求路径,支持通配符
?
匹配一个字符*
匹配零个或多个字符**
匹配路径中零个或多个目录(常用
){spring:[a-z]+}
将正则表达式匹配为名为“spring”的路径变量[a-z]+
- 构造方法
构造方法 | 描述 |
---|---|
AntPathMatcher() | 使用 DEFAULT_PATH_SEPARATOR 创建一个新实例。 |
AntPathMatcher(String pathSeparator) | 一个方便的替代构造函数,可与自定义路径分隔符一起使用 |
- 主要方法
返回值 | 方法 | 描述 |
---|---|---|
boolean | match(String pattern, String path) | 将给定的路径与给定的模式pattern支持通配符 进行匹配 |
public class Test{
public static void main(String[] args) {
AntPathMatcher antPathMatcher = new AntPathMatcher();
//定义不需要拦截的路径(即:登录,退出,静态资源等)
String[] urls = {
"/employee/login",
"/employee/logout",
"/backend/**",
"/front/**",
"/common/**",
"/user/sendMsg",
"/user/login"
};
//2.判断是否是不需要拦截的路径
//requestURI为请求路径的一部分: String requestURI = request.getRequestURI();
Boolean notCheck = checkPath(urls, requestURI);
if(notCheck){
log.info("本次请求 {} 不需要处理",requestURI);
//放行
return;
}
//反之,拦截
}
public Boolean checkPath(String[] urls,String requestUrl){
for (String url : urls) {
boolean match = antPathMatcher.match(url, requestUrl);
if(match){
return true;
}
}
return false;
}
}
String Utils
此部分引用的是二哥的文章------->沉默王二
- 在我们的代码中经常需要对字符串判空,截取字符串、转换大小写、分隔字符串、比较字符串、去掉多余空格、拼接字符串、使用正则表达式等等,而org.apache.commons.lang3包下的StringUtils工具类,给我们提供了非常丰富的选择。
- 导入依赖
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>version</version>
</dependency>
可以看出StringUtils的方法很多,这里说一些常用的
String str1 = null;
String str2 = "";
String str3 = " ";
String str4 = "abc";
System.out.println(StringUtils.isEmpty(str1)); //true
System.out.println(StringUtils.isEmpty(str2)); //true
System.out.println(StringUtils.isEmpty(str3)); //false
System.out.println(StringUtils.isEmpty(str4)); //false
System.out.println("=====");
System.out.println(StringUtils.isNotEmpty(str1)); //false
System.out.println(StringUtils.isNotEmpty(str2)); //false
System.out.println(StringUtils.isNotEmpty(str3)); //true
System.out.println(StringUtils.isNotEmpty(str4)); //true
System.out.println("=====");
System.out.println(StringUtils.isBlank(str1)); //true
System.out.println(StringUtils.isBlank(str2)); //true
System.out.println(StringUtils.isBlank(str3)); //true
System.out.println(StringUtils.isBlank(str4)); //false
System.out.println("=====");
System.out.println(StringUtils.isNotBlank(str1)); //false
System.out.println(StringUtils.isNotBlank(str2)); //false
System.out.println(StringUtils.isNotBlank(str3)); //false
System.out.println(StringUtils.isNotBlank(str4)); //true
示例中的:isEmpty、isNotEmpty、isBlank和isNotBlank,这 4 个判空方法你们可以根据实际情况使用。
优先推荐使用isNotEmpty,isBlank和isNotBlank方法,因为它会把" "也考虑进去。
分隔字符串是常见需求,如果直接使用 String 类的 split 方法,就可能会出现空指针异常。
String str1 = null;
System.out.println(StringUtils.split(str1,","));
System.out.println(str1.split(","));
执行结果
null
Exception in thread "main" java.lang.NullPointerException
\tat com.sue.jump.service.test1.UtilTest.main(UtilTest.java:21)
使用 StringUtils 的 split 方法会返回 null,而使用 String 的 split 方法会报指针异常
给定一个字符串,判断它是否为纯数字,可以使用isNumeric方法。例如:
String str1 = "123";
String str2 = "123q";
String str3 = "0.33";
System.out.println(StringUtils.isNumeric(str1)); //true
System.out.println(StringUtils.isNumeric(str2)); //false
System.out.println(StringUtils.isNumeric(str3)); //false
有时候,我们需要将某个集合的内容,拼接成一个字符串,然后输出,这时可以使用join方法。例如:
List<String> list = Lists.newArrayList("a", "b", "c");
List<Integer> list2 = Lists.newArrayList(1, 2, 3);
System.out.println(StringUtils.join(list, ",")); //a,b,bc
System.out.println(StringUtils.join(list2, " ")); //1 2 3
这里再列举一些,其他的方法可以自己去研究一下。
- trim(String str):去除字符串首尾的空白字符。
- trimToEmpty(String str):去除字符串首尾的空白字符,如果字符串为 null,则返回空字符串。
- trimToNull(String str):去除字符串首尾的空白字符,如果结果为空字符串,则返回 null。
- equals(String str1, String str2):比较两个字符串是否相等。
- equalsIgnoreCase(String str1, String str2):比较两个字符串是否相等,忽略大小写。
- startsWith(String str, String prefix):检查字符串是否以指定的前缀开头。
- endsWith(String str, String suffix):检查字符串是否以指定的后缀结尾。
- contains(String str, CharSequence seq):检查字符串是否包含指定的字符序列。
- indexOf(String str, CharSequence seq):返回指定字符序列在字符串中首次出现的索引,如果没有找到,则返回 -1。
- lastIndexOf(String str, CharSequence seq):返回指定字符序列在字符串中最后一次出现的索引,如果没有找到,则返回 -1。
- substring(String str, int start, int end):截取字符串中指定范围的子串。
- replace(String str, String searchString, String replacement):替换字符串中所有出现的搜索字符串为指定的替换字符串。
- replaceAll(String str, String regex, String replacement):使用正则表达式替换字符串中所有匹配的部分。
- join(Iterable<?> iterable, String separator):使用指定的分隔符将可迭代对象中的元素连接为一个字符串。
- split(String str, String separator):使用指定的分隔符将字符串分割为一个字符串数组。
- capitalize(String str):将字符串的第一个字符转换为大写。
- uncapitalize(String str):将字符串的第一个字符转换为小写。
文件上传和下载 MultipartFile
- 可用于
图片
,视频
,音频
等 - 对
form表单
的要求:- method = “
post
” - enctype = “
multipart/form-data
” - type = “``file”
- method = “
- spring框架在spring-web包中对文件上传进行了封装,大大简化了服务端代码,只需要在controller层声明一个参数为
MultipartFile
类型的方法即可接受上传文件
代码演示
/**
* 文件上传
* @param file
* @return
*/
@PostMapping("/upload")
public Result<String> upload(MultipartFile file){ //此形参名不能随便起,要与表单的属性名称对应
//file是一个临时文件,需要转存到指定位置,否则当本次请求结束后该临时文件会自动删除
//获取原始文件名
String originalFilename = file.getOriginalFilename(); //此方法不够友好,若原始文件名重复,将会覆盖文件
//获取文件的后缀
//从字符 “.” 索引位置开始向后截取字符串(包括".")
//substring需要一个索引做参数 , lastIndexOf需要String,int,等参数获取当前位置的索引
String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
//使用UUID重新生成文件名,防止文件名重复造成文件覆盖(Java.Util包下)
String fileNam = UUID.randomUUID().toString(); //获取一个随机字符串,并添加文件后缀
String fileName = fileNam + suffix;
//dishPath是一个目录
File files = new File(dishPath);
if (!files.exists())
files.mkdirs();
//使用配置的形式定义文件路径
try {
file.transferTo(new File(dishPath + fileName));
} catch (IOException e) {
e.printStackTrace();
}
return Result.success(fileName);
}
transferTo()
方法将上传的文件写到服务器上指定的文件中(将临时文件转存到指定位置),输入完毕关闭流
UUID.randdomUUID()
随机生成一个不重复的字符串作为文件名,防止文件名重复(这里主要上传图片)
- 文件下载
- 通过浏览器进行文件下载
- 以附件形式下载,弹出保存对话框,将文件保存到指定磁盘中
- 直接在浏览器中打开,本质:服务器将文件以流 的方式写回浏览器的过程
- 通过浏览器进行文件下载
代码演示
/**
* 文件下载
* @param name
* @param response
*/
@GetMapping("/download")
public void download(String name, HttpServletResponse response){
try {
//输入流,读取文件内容 , 使用的路径为自定义路径与文件名结合的路径
FileInputStream inputStream = new FileInputStream(new File(dishPath+name));
//输出流,将文件内容写回浏览器,这样浏览器就可以显示图片了
ServletOutputStream outputStream = response.getOutputStream();
//设置响应格式(jpeg)
response.setContentType("image/jpeg");
/*int len = 0;
byte[] bytes = new byte[1024];
while ((len = inputStream.read(bytes)) != -1) {
outputStream.write(bytes,0,len);
outputStream.flush();
}*/
//使用common-io 工具类 的 copy方法,直接将输入流传给输出流
IOUtils.copy(inputStream,outputStream);
outputStream.flush();
//关闭文件
inputStream.close();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
common-io
工具包中的IOUtils 工具类 下的 copy()
方法简化文件传输代码