Skip to content

添加依赖

/pom.xml 文件中写入以下代码

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

使用

/src/main/java/com/example/xys1/controller/XysController.java 文件中写入以下代码

java
package com.example.xys1.controller;

import cn.hutool.core.util.IdUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;

// 标识为控制器,且所有方法返回值直接转为 JSON(无需视图解析)
@RestController
@RequestMapping("/xys")
public class XysController {
    @PostMapping("/test1")
    public Map<String, Object> test1() {
        Map<String, Object> result = new HashMap<>();
        result.put("name", "/xys/test1");
        result.put("str-str", StrUtil.format("{}-{}", "a", "b"));
        result.put("md5", SecureUtil.md5("123456"));
        result.put("sha256", SecureUtil.sha256("123456"));
        return result;
    }

    @PostMapping("/test2")
    public Map<String, Object> test2() {
        String pwd = "e10adc3949ba59abbe56e057f20f883e";

        // AES对称加密(自定义密钥)
        AES aes = SecureUtil.aes("1234567890123456".getBytes()); // 密钥必须16/24/32位
        String encryptStr = aes.encryptHex(pwd); // 加密为16进制字符串
        String decryptStr = aes.decryptStr(encryptStr); // 解密回原字符串

        Map<String, Object> result = new HashMap<>();
        result.put("name", "/xys/test2");
        result.put("encryptStr", encryptStr);
        result.put("decryptStr", decryptStr);
        return result;
    }

    @PostMapping("/test3")
    public Map<String, Object> test3() {

        // 1. 生成标准 UUID(带横线,36位):如 550e8400-e29b-41d4-a716-446655440000
        String uuidWithLine = IdUtil.randomUUID();

        // 2. 生成简化 UUID(无横线,32位):最常用,如 550e8400e29b41d4a716446655440000
        String uuidWithoutLine = IdUtil.simpleUUID();

        // 3. 生成纯数字 UUID(基于雪花算法,Long类型,分布式唯一):如 1758924789012345678
        // 注意:雪花算法需要初始化,Hutool 会自动处理,适合分布式系统
        long snowflakeId = IdUtil.getSnowflakeNextId();

        // 4. 生成纯数字 UUID(字符串形式)
        String snowflakeIdStr = IdUtil.getSnowflakeNextIdStr();

        Map<String, Object> result = new HashMap<>();
        result.put("name", "/xys/test3");
        result.put("a.生成标准 UUID(带横线,36位)", uuidWithLine);
        result.put("b.生成简化 UUID(无横线,32位)", uuidWithoutLine);
        result.put("c.生成纯数字 UUID(基于雪花算法,Long类型,分布式唯一)", snowflakeId);
        result.put("d.生成纯数字 UUID(字符串形式)", snowflakeIdStr);
        return result;
    }


}