hutool工具

Hutool是一个Java工具包

对文件、流、加密解密、转码、正则、线程、XML 等 JDK 方法进行封装,组成各种 Util 工具类,同时提供以下组件:

  • hutool-aop JDK 动态代理封装,提供非IOC下的切面支持
  • hutool-bloomFilter 布隆过滤,提供一些Hash算法的布隆过滤
  • hutool-cache 缓存
  • hutool-core 核心,包含Bean操作、日期、各种Util等
  • hutool-cron 定时任务模块,提供类Crontab表达式的定时任务
  • hutool-crypto 加密解密模块
  • hutool-db JDBC封装后的数据操作,基于ActiveRecord思想
  • hutool-dfa 基于DFA模型的多关键字查找
  • hutool-extra 扩展模块,对第三方封装(模板引擎、邮件等)
  • hutool-http 基于HttpUrlConnection的Http客户端封装
  • hutool-log自动识别日志实现的日志门面
  • hutool-script脚本执行封装,例如javascript
  • hutool-setting功能更强大的Setting配置文件和Properties封装
  • hutool-system系统参数调用封装(JVM信息等)
  • hutool-json JSON实现
  • hutool-captcha图片验证码实现

参考:https://www.hutool.cn/

<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>4.6.3</version>
</dependency>

Convert类型转换工具类

//转换为字符串
int a = 1;
String aStr = Convert.toStr(a);
//转换为指定类型数组
String[] b = {"1", "2", "3", "4"};
Integer[] bArr = Convert.toIntArray(b);
//转换为日期对象
String dateStr = "2017-05-06";
Date date = Convert.toDate(dateStr);
//转换为列表
String[] strArr = {"a", "b", "c", "d"};
List<String> strList = Convert.toList(String.class, strArr);

DateUtil日期时间工具类

//Date、long、Calendar之间的相互转换
//当前时间
Date date = DateUtil.date();
//Calendar转Date
date = DateUtil.date(Calendar.getInstance());
//时间戳转Date
date = DateUtil.date(System.currentTimeMillis());
//自动识别格式转换
String dateStr = "2017-03-01";
date = DateUtil.parse(dateStr);
//自定义格式化转换
date = DateUtil.parse(dateStr, "yyyy-MM-dd");
//格式化输出日期
String format = DateUtil.format(date, "yyyy-MM-dd");
//获得年的部分
int year = DateUtil.year(date);
//获得月份,从0开始计数
int month = DateUtil.month(date);
//获取某天的开始、结束时间
Date beginOfDay = DateUtil.beginOfDay(date);
Date endOfDay = DateUtil.endOfDay(date);
//计算偏移后的日期时间
Date newDate = DateUtil.offset(date, DateField.DAY_OF_MONTH, 2);
//计算日期时间之间的偏移量
long betweenDay = DateUtil.between(date, newDate, DateUnit.DAY);

StrUtil字符串工具类

//判断是否为空字符串
String str = "test";
StrUtil.isEmpty(str);
StrUtil.isNotEmpty(str);
//去除字符串的前后缀
StrUtil.removeSuffix("a.jpg", ".jpg");
StrUtil.removePrefix("a.jpg", "a.");
//格式化字符串
String template = "这只是个占位符:{}";
String str2 = StrUtil.format(template, "我是占位符");
LOGGER.info("/strUtil format:{}", str2);

ClassPathResource获取classPath下的文件

//获取定义在src/main/resources文件夹中的配置文件
ClassPathResource resource = new ClassPathResource("generator.properties");
Properties properties = new Properties();
properties.load(resource.getStream());
LOGGER.info("/classPath:{}", properties);

ReflectUtilJava反射工具类

//获取某个类的所有方法
Method[] methods = ReflectUtil.getMethods(PmsBrand.class);
//获取某个类的指定方法
Method method = ReflectUtil.getMethod(PmsBrand.class, "getId");
//使用反射来创建对象
PmsBrand pmsBrand = ReflectUtil.newInstance(PmsBrand.class);
//反射执行对象的方法
ReflectUtil.invoke(pmsBrand, "setId", 1);

NumberUtil数字处理工具类

double n1 = 1.234;
double n2 = 1.234;
double result;
//对float、double、BigDecimal做加减乘除操作
result = NumberUtil.add(n1, n2);
result = NumberUtil.sub(n1, n2);
result = NumberUtil.mul(n1, n2);
result = NumberUtil.div(n1, n2);
//保留两位小数
BigDecimal roundNum = NumberUtil.round(n1, 2);
String n3 = "1.234";
//判断是否为数字、整数、浮点数
NumberUtil.isNumber(n3);
NumberUtil.isInteger(n3);
NumberUtil.isDouble(n3);

BeanUtil JavaBean的工具类

PmsBrand brand = new PmsBrand();
brand.setId(1L);
brand.setName("小米");
brand.setShowStatus(0);
//Bean转Map
Map<String, Object> map = BeanUtil.beanToMap(brand);
LOGGER.info("beanUtil bean to map:{}", map);
//Map转Bean
PmsBrand mapBrand = BeanUtil.mapToBean(map, PmsBrand.class, false);
LOGGER.info("beanUtil map to bean:{}", mapBrand);
//Bean属性拷贝
PmsBrand copyBrand = new PmsBrand();
BeanUtil.copyProperties(brand, copyBrand);
LOGGER.info("beanUtil copy properties:{}", copyBrand);

CollUtil集合操作的工具类

//数组转换为列表
String[] array = new String[]{"a", "b", "c", "d", "e"};
List<String> list = CollUtil.newArrayList(array);
//join:数组转字符串时添加连接符号
String joinStr = CollUtil.join(list, ",");
LOGGER.info("collUtil join:{}", joinStr);
//将以连接符号分隔的字符串再转换为列表
List<String> splitList = StrUtil.split(joinStr, ',');
LOGGER.info("collUtil split:{}", splitList);
//创建新的Map、Set、List
HashMap<Object, Object> newMap = CollUtil.newHashMap();
HashSet<Object> newHashSet = CollUtil.newHashSet();
ArrayList<Object> newList = CollUtil.newArrayList();
//判断列表是否为空
CollUtil.isEmpty(list);

MapUtil Map操作工具类

//将多个键值对加入到Map中
Map<Object, Object> map = MapUtil.of(new String[][]{
    {"key1", "value1"},
    {"key2", "value2"},
    {"key3", "value3"}
});
//判断Map是否为空
MapUtil.isEmpty(map);
MapUtil.isNotEmpty(map);

AnnotationUtil注解工具类

//获取指定类、方法、字段、构造器上的注解列表
Annotation[] annotationList = AnnotationUtil.getAnnotations(HutoolController.class, false);
LOGGER.info("annotationUtil annotations:{}", annotationList);
//获取指定类型注解
Api api = AnnotationUtil.getAnnotation(HutoolController.class, Api.class);
LOGGER.info("annotationUtil api value:{}", api.description());
//获取指定类型注解的值
Object annotationValue = AnnotationUtil.getAnnotationValue(HutoolController.class, RequestMapping.class);

SecureUtil加密解密工具类

主要是在登录的时候还有修改密码的时候用到的
因为数据库里面的密码是md5加密处理的,所以登录的时候需要先加密之后再到数据库进行查询
使用Hutool只需要SecureUtil的md5方法就可以了

//MD5加密
String str = "123456";
String md5Str = SecureUtil.md5(str);
LOGGER.info("secureUtil md5:{}", md5Str);
user = userService.userLoginByName(loginName,SecureUtil.md5(loginPwd))

CaptchaUtil验证码工具类,可用于生成图形验证码

//生成验证码图片
LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);
try {
    request.getSession().setAttribute("CAPTCHA_KEY", lineCaptcha.getCode());
    response.setContentType("image/png");//告诉浏览器输出内容为图片
    response.setHeader("Pragma", "No-cache");//禁止浏览器缓存
    response.setHeader("Cache-Control", "no-cache");
    response.setDateHeader("Expire", 0);
    lineCaptcha.write(response.getOutputStream());
} catch (IOException e) {
    e.printStackTrace();
}

HtmlUtil(HTML工具类)

将一些字符转化为安全字符,防止 xss 注入和 SQL 注入

comment.setCommentAuthor(HtmlUtil.encode(comment.getCommentAuthor()));

防止写一些可执行的 js 代码,然后提交评论,在后台面板就会执行这一段代码,比较危险,使用 encode 方法就可以将 标签给转化成,这样转化之后,js 代码就不会执行了。

其他方法:

  • HtmlUtil.restoreEscaped 还原被转移的HTML特殊字符
  • HtmlUtil.encode 转移文本中的HTML字符为安全的字符
  • HtmlUtil.cleanHtmlTag 清除所有的HTML标签
  • HtmlUtil.removeHtmlTag 清除指定HTML标签和被标签包围的内容
  • HtmlUtil.unwrapHtmlTag 清除指定HTML,不包括内容
  • HtmlUtil.removeHtmlAttr 去除HTML标签中的属性
  • HtmlUtil.removeAllHtmlAttr 去除指定标签的所有属性
  • HtmlUtil.filter 过滤HTML文本,防止XSS攻击

CronUtil(定时任务)

完全不需要类似 quartz 这样的框架来做定时任务,而且 CronUtil 也不需要任何其他依赖,只需要在 resources 下建一个配置文件,然后在程序启动的时候将定时任务开启就行了

cron.setting

cc.ryanc.halo.web.controller.admin.BackupController.backupResources = 0 0 1 * * ?
cc.ryanc.halo.web.controller.admin.BackupController.backupDatabase = 0 0 1 * * ?
cc.ryanc.halo.web.controller.admin.BackupController.backupPosts = 0 0 1 * * ?
@Override
public void onApplicationEvent(ContextRefreshedEvent event){
 this.loadActiveTheme();
 this.loadOptions();
 this.loadFiles();
 this.loadThemes();
 //启动定时任务
 CronUtil.start();
 log.info("定时任务启动成功!");
}

判断是否是手机号

Validator.isMobile(form.getMobile())
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值