各种工具类的使用1

AntPathMatcher

  1. package org.springframework.util
    public class AntPathMatcher extends Object implements PathMatcher
  2. 路径匹配器,可用来匹配路径,如:过滤请求路径,支持通配符
    • ?匹配一个字符
    • *匹配零个或多个字符
    • **匹配路径中零个或多个目录(常用)
    • {spring:[a-z]+}将正则表达式匹配为名为“spring”的路径变量[a-z]+
  3. 构造方法
构造方法描述
AntPathMatcher()使用 DEFAULT_PATH_SEPARATOR 创建一个新实例。
AntPathMatcher(String pathSeparator)一个方便的替代构造函数,可与自定义路径分隔符一起使用
  1. 主要方法
返回值方法描述
booleanmatch(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

此部分引用的是二哥的文章------->沉默王二

  1. 在我们的代码中经常需要对字符串判空截取字符串转换大小写分隔字符串比较字符串去掉多余空格拼接字符串、使用正则表达式等等,而org.apache.commons.lang3包下的StringUtils工具类,给我们提供了非常丰富的选择。
  2. 导入依赖
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>version</version>
</dependency>

在这里插入图片描述
可以看出StringUtils的方法很多,这里说一些常用的

  1. 判空

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方法,因为它会把" "也考虑进去。

  1. 分割字符串

分隔字符串是常见需求,如果直接使用 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 方法会报指针异常

  1. 判断是否是纯数字

给定一个字符串,判断它是否为纯数字,可以使用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
  1. 将集合拼接成字符串

有时候,我们需要将某个集合的内容,拼接成一个字符串,然后输出,这时可以使用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
  1. 其他方法

这里再列举一些,其他的方法可以自己去研究一下。

  • 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

  1. 可用于图片视频音频
  2. form表单的要求:
    • method = “post
    • enctype = “multipart/form-data
    • type = “``file”
  3. 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()随机生成一个不重复的字符串作为文件名,防止文件名重复(这里主要上传图片)

  1. 文件下载
    • 通过浏览器进行文件下载
      • 以附件形式下载,弹出保存对话框,将文件保存到指定磁盘中
      • 直接在浏览器中打开,本质:服务器将文件以 的方式写回浏览器的过程

代码演示

    /**
     * 文件下载
     * @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()方法简化文件传输代码

  • 8
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小胖子S

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值