service common

This commit is contained in:
2025-09-28 15:50:38 +08:00
parent 6fda9d89f6
commit f6e9206da3
18 changed files with 1677 additions and 9 deletions

View File

@@ -0,0 +1,89 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.xyzh</groupId>
<artifactId>common</artifactId>
<version>${school-news.version}</version>
</parent>
<groupId>org.xyzh</groupId>
<artifactId>common-all</artifactId>
<version>${school-news.version}</version>
<packaging>jar</packaging>
<name>Common All-in-One</name>
<description>包含所有common模块功能的聚合jar包</description>
<properties>
<maven.compiler.source>21</maven.compiler.source>
<maven.compiler.target>21</maven.compiler.target>
</properties>
<dependencies>
<!-- 包含所有common子模块 -->
<dependency>
<groupId>org.xyzh</groupId>
<artifactId>common-core</artifactId>
</dependency>
<dependency>
<groupId>org.xyzh</groupId>
<artifactId>common-dto</artifactId>
</dependency>
<dependency>
<groupId>org.xyzh</groupId>
<artifactId>common-exception</artifactId>
</dependency>
<dependency>
<groupId>org.xyzh</groupId>
<artifactId>common-util</artifactId>
</dependency>
<dependency>
<groupId>org.xyzh</groupId>
<artifactId>common-annotation</artifactId>
</dependency>
<dependency>
<groupId>org.xyzh</groupId>
<artifactId>common-redis</artifactId>
</dependency>
<dependency>
<groupId>org.xyzh</groupId>
<artifactId>common-jdbc</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<!-- Maven Shade Plugin - 将所有依赖打包到一个jar中 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.4.1</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
</excludes>
</filter>
</filters>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@@ -4,7 +4,7 @@ package org.xyzh.common.core.constant;
* @description Constants.java文件描述 * @description Constants.java文件描述
* @filename Constants.java * @filename Constants.java
* @author yslg * @author yslg
* @copyright yslg * @copyright xyzh
* @since 2025-09-07 * @since 2025-09-07
*/ */
public class Constants { public class Constants {

View File

@@ -1,5 +1,273 @@
package org.xyzh.common.core.domain; package org.xyzh.common.core.domain;
public class LoginDomain { import java.io.Serializable;
import java.util.Date;
import java.util.List;
import org.xyzh.common.dto.user.TbSysUser;
import org.xyzh.common.dto.user.TbSysUserInfo;
import org.xyzh.common.dto.role.TbSysRole;
import org.xyzh.common.dto.permission.TbSysPermission;
import org.xyzh.common.dto.dept.TbSysDeptRole;
import org.xyzh.common.dto.menu.TbSysMenu;
/**
* @description LoginDomain.java文件描述 登录域对象
* @filename LoginDomain.java
* @author yslg
* @copyright xyzh
* @since 2025-09-28
*/
public class LoginDomain implements Serializable {
private static final long serialVersionUID = 1L;
/**
* @description 用户信息
* @author yslg
* @since 2025-09-28
*/
private TbSysUser user;
/**
* @description 用户详细信息
* @author yslg
* @since 2025-09-28
*/
private TbSysUserInfo userInfo;
/**
* @description 用户角色列表
* @author yslg
* @since 2025-09-28
*/
private List<TbSysDeptRole> roles;
/**
* @description 用户权限列表
* @author yslg
* @since 2025-09-28
*/
private List<TbSysPermission> permissions;
/**
* @description 用户菜单列表
* @author yslg
* @since 2025-09-28
*/
private List<TbSysMenu> menus;
/**
* @description JWT令牌
* @author yslg
* @since 2025-09-28
*/
private String token;
/**
* @description 令牌过期时间
* @author yslg
* @since 2025-09-28
*/
private Date tokenExpireTime;
/**
* @description 登录时间
* @author yslg
* @since 2025-09-28
*/
private Date loginTime;
/**
* @description 登录IP地址
* @author yslg
* @since 2025-09-28
*/
private String ipAddress;
/**
* @description 登录类型 (email/username/phone/wechat)
* @author yslg
* @since 2025-09-28
*/
private String loginType;
/**
* @description 获取用户
* @author yslg
* @since 2025-09-28
*/
public TbSysUser getUser() {
return user;
}
/**
* @description 设置用户
* @author yslg
* @since 2025-09-28
*/
public void setUser(TbSysUser user) {
this.user = user;
}
/**
* @description 获取用户详细信息
* @author yslg
* @since 2025-09-28
*/
public TbSysUserInfo getUserInfo() {
return userInfo;
}
/**
* @description 设置用户详细信息
* @author yslg
* @since 2025-09-28
*/
public void setUserInfo(TbSysUserInfo userInfo) {
this.userInfo = userInfo;
}
/**
* @description 获取用户角色列表
* @author yslg
* @since 2025-09-28
*/
public List<TbSysDeptRole> getRoles() {
return roles;
}
/**
* @description 设置用户角色列表
* @author yslg
* @since 2025-09-28
*/
public void setRoles(List<TbSysDeptRole> roles) {
this.roles = roles;
}
/**
* @description 获取用户权限列表
* @author yslg
* @since 2025-09-28
*/
public List<TbSysPermission> getPermissions() {
return permissions;
}
/**
* @description 设置用户权限列表
* @author yslg
* @since 2025-09-28
*/
public void setPermissions(List<TbSysPermission> permissions) {
this.permissions = permissions;
}
/**
* @description 获取用户菜单列表
* @author yslg
* @since 2025-09-28
*/
public List<TbSysMenu> getMenus() {
return menus;
}
/**
* @description 设置用户菜单列表
* @author yslg
* @since 2025-09-28
*/
public void setMenus(List<TbSysMenu> menus) {
this.menus = menus;
}
/**
* @description 获取JWT令牌
* @author yslg
* @since 2025-09-28
*/
public String getToken() {
return token;
}
/**
* @description 设置JWT令牌
* @author yslg
* @since 2025-09-28
*/
public void setToken(String token) {
this.token = token;
}
/**
* @description 获取令牌过期时间
* @author yslg
* @since 2025-09-28
*/
public Date getTokenExpireTime() {
return tokenExpireTime;
}
/**
* @description 设置令牌过期时间
* @author yslg
* @since 2025-09-28
*/
public void setTokenExpireTime(Date tokenExpireTime) {
this.tokenExpireTime = tokenExpireTime;
}
/**
* @description 获取登录时间
* @author yslg
* @since 2025-09-28
*/
public Date getLoginTime() {
return loginTime;
}
/**
* @description 设置登录时间
* @author yslg
* @since 2025-09-28
*/
public void setLoginTime(Date loginTime) {
this.loginTime = loginTime;
}
/**
* @description 获取登录IP地址
* @author yslg
* @since 2025-09-28
*/
public String getIpAddress() {
return ipAddress;
}
/**
* @description 设置登录IP地址
* @author yslg
* @since 2025-09-28
*/
public void setIpAddress(String ipAddress) {
this.ipAddress = ipAddress;
}
/**
* @description 获取登录类型
* @author yslg
* @since 2025-09-28
*/
public String getLoginType() {
return loginType;
}
/**
* @description 设置登录类型
* @author yslg
* @since 2025-09-28
*/
public void setLoginType(String loginType) {
this.loginType = loginType;
}
} }

View File

@@ -16,6 +16,27 @@ public class LoginParam {
*/ */
private String email; private String email;
/**
* @description 用户名
* @author yslg
* @since 2025-09-28
*/
private String username;
/**
* @description 手机号
* @author yslg
* @since 2025-09-28
*/
private String phone;
/**
* @description 微信ID
* @author yslg
* @since 2025-09-28
*/
private String wechatID;
/** /**
* @description 密码 * @description 密码
* @author yslg * @author yslg
@@ -23,20 +44,168 @@ public class LoginParam {
*/ */
private String password; private String password;
/**
* @description 验证码
* @author yslg
* @since 2025-09-28
*/
private String captcha;
/**
* @description 登录类型 (email/username/phone/wechat)
* @author yslg
* @since 2025-09-28
*/
private String loginType;
/**
* @description 记住我
* @author yslg
* @since 2025-09-28
*/
private boolean rememberMe;
/**
* @description 获取邮箱
* @author yslg
* @since 2025-09-28
*/
public String getEmail() { public String getEmail() {
return email; return email;
} }
/**
* @description 设置邮箱
* @author yslg
* @since 2025-09-28
*/
public void setEmail(String email) { public void setEmail(String email) {
this.email = email; this.email = email;
} }
/**
* @description 获取用户名
* @author yslg
* @since 2025-09-28
*/
public String getUsername() {
return username;
}
/**
* @description 设置用户名
* @author yslg
* @since 2025-09-28
*/
public void setUsername(String username) {
this.username = username;
}
/**
* @description 获取手机号
* @author yslg
* @since 2025-09-28
*/
public String getPhone() {
return phone;
}
/**
* @description 设置手机号
* @author yslg
* @since 2025-09-28
*/
public void setPhone(String phone) {
this.phone = phone;
}
/**
* @description 获取微信ID
* @author yslg
* @since 2025-09-28
*/
public String getWechatID() {
return wechatID;
}
/**
* @description 设置微信ID
* @author yslg
* @since 2025-09-28
*/
public void setWechatID(String wechatID) {
this.wechatID = wechatID;
}
/**
* @description 获取密码
* @author yslg
* @since 2025-09-28
*/
public String getPassword() { public String getPassword() {
return password; return password;
} }
/**
* @description 设置密码
* @author yslg
* @since 2025-09-28
*/
public void setPassword(String password) { public void setPassword(String password) {
this.password = password; this.password = password;
} }
/**
* @description 获取验证码
* @author yslg
* @since 2025-09-28
*/
public String getCaptcha() {
return captcha;
}
/**
* @description 设置验证码
* @author yslg
* @since 2025-09-28
*/
public void setCaptcha(String captcha) {
this.captcha = captcha;
}
/**
* @description 获取登录类型
* @author yslg
* @since 2025-09-28
*/
public String getLoginType() {
return loginType;
}
/**
* @description 设置登录类型
* @author yslg
* @since 2025-09-28
*/
public void setLoginType(String loginType) {
this.loginType = loginType;
}
/**
* @description 获取记住我
* @author yslg
* @since 2025-09-28
*/
public boolean isRememberMe() {
return rememberMe;
}
/**
* @description 设置记住我
* @author yslg
* @since 2025-09-28
*/
public void setRememberMe(boolean rememberMe) {
this.rememberMe = rememberMe;
}
} }

View File

@@ -10,7 +10,7 @@ import org.xyzh.common.core.page.PageParam;
* @description ResultDomain.java文件描述 统一返回结果实体类 * @description ResultDomain.java文件描述 统一返回结果实体类
* @filename ResultDomain.java * @filename ResultDomain.java
* @author yslg * @author yslg
* @copyright yslg * @copyright xyzh
* @since 2025-09-07 * @since 2025-09-07
*/ */
public class ResultDomain<T> implements Serializable{ public class ResultDomain<T> implements Serializable{

View File

@@ -6,7 +6,7 @@ import java.io.Serializable;
* @description BaseEntity.java文件描述 基础实体类 * @description BaseEntity.java文件描述 基础实体类
* @filename BaseEntity.java * @filename BaseEntity.java
* @author yslg * @author yslg
* @copyright yslg * @copyright xyzh
* @since 2025-09-07 * @since 2025-09-07
*/ */
public class BaseEntity implements Serializable { public class BaseEntity implements Serializable {

View File

@@ -6,7 +6,7 @@ import org.xyzh.common.core.enums.DataStatus;
* @description DataEntity.java文件描述 数据实体类 * @description DataEntity.java文件描述 数据实体类
* @filename DataEntity.java * @filename DataEntity.java
* @author yslg * @author yslg
* @copyright yslg * @copyright xyzh
* @since 2025-09-07 * @since 2025-09-07
*/ */
public class DataEntity<T> extends BaseEntity { public class DataEntity<T> extends BaseEntity {

View File

@@ -4,7 +4,7 @@ package org.xyzh.common.core.enums;
* @description DataStatus枚举类 数据状态枚举类 * @description DataStatus枚举类 数据状态枚举类
* @filename DataStatus.java * @filename DataStatus.java
* @author yslg * @author yslg
* @copyright yslg * @copyright xyzh
* @since 2025-09-07 * @since 2025-09-07
*/ */
public enum DataStatus { public enum DataStatus {

View File

@@ -1,5 +1,73 @@
package org.xyzh.common.core.enums; package org.xyzh.common.core.enums;
/**
* @description UserStatus枚举类 用户状态枚举类
* @filename UserStatus.java
* @author yslg
* @copyright xyzh
* @since 2025-09-28
*/
public enum UserStatus { public enum UserStatus {
NORMAL("0", "正常", "用户状态正常"),
DISABLED("1", "禁用", "用户被禁用"),
LOCKED("2", "锁定", "用户被锁定"),
EXPIRED("3", "过期", "用户已过期"),
PENDING("4", "待激活", "用户待激活");
private final String code;
private final String name;
private final String description;
UserStatus(String code, String name, String description) {
this.code = code;
this.name = name;
this.description = description;
}
/**
* @description 获取枚举值
* @return String 枚举值
* @author yslg
* @since 2025-09-28
*/
public String getCode() {
return code;
}
/**
* @description 获取枚举名称
* @return String 枚举名称
* @author yslg
* @since 2025-09-28
*/
public String getName() {
return name;
}
/**
* @description 获取枚举描述
* @return String 枚举描述
* @author yslg
* @since 2025-09-28
*/
public String getDescription() {
return description;
}
/**
* @description 根据code获取枚举
* @param code 状态码
* @return UserStatus 用户状态枚举
* @author yslg
* @since 2025-09-28
*/
public static UserStatus fromCode(String code) {
for (UserStatus status : UserStatus.values()) {
if (status.getCode().equals(code)) {
return status;
}
}
return NORMAL;
}
} }

View File

@@ -6,7 +6,7 @@ import java.util.List;
* @description PageDomain.java文件描述 分页数据实体类 * @description PageDomain.java文件描述 分页数据实体类
* @filename PageDomain.java * @filename PageDomain.java
* @author yslg * @author yslg
* @copyright yslg * @copyright xyzh
* @since 2025-09-07 * @since 2025-09-07
*/ */
public class PageDomain<T> implements Serializable{ public class PageDomain<T> implements Serializable{

View File

@@ -6,7 +6,7 @@ import java.io.Serializable;
* @description PageParam.java文件描述 分页参数 * @description PageParam.java文件描述 分页参数
* @filename PageParam.java * @filename PageParam.java
* @author yslg * @author yslg
* @copyright yslg * @copyright xyzh
* @since 2025-09-07 * @since 2025-09-07
*/ */
public class PageParam implements Serializable { public class PageParam implements Serializable {

View File

@@ -0,0 +1,75 @@
package org.xyzh.common.exception;
/**
* @description BaseException.java文件描述 基础异常类
* @filename BaseException.java
* @author yslg
* @copyright xyzh
* @since 2025-09-28
*/
public class BaseException extends RuntimeException{
private static final long serialVersionUID = 1L;
/**
* @description code
* @author yslg
* @since 2025-09-28
*/
private String code;
/**
* @description BaseException
* @author yslg
* @since 2025-09-28
*/
public BaseException(String message) {
super(message);
}
/**
* @description BaseException
* @author yslg
* @since 2025-09-28
*/
public BaseException(String code, String message) {
super(message);
this.code = code;
}
/**
* @description BaseException
* @author yslg
* @since 2025-09-28
*/
public BaseException(String message, Throwable cause) {
super(message, cause);
}
/**
* @description BaseException
* @author yslg
* @since 2025-09-28
*/
public BaseException(String code, String message, Throwable cause) {
super(message, cause);
this.code = code;
}
/**
* @description getCode
* @author yslg
* @since 2025-09-28
*/
public String getCode() {
return code;
}
/**
* @description setCode
* @author yslg
* @since 2025-09-28
*/
public void setCode(String code) {
this.code = code;
}
}

View File

@@ -0,0 +1,39 @@
package org.xyzh.common.exception.auth;
import org.xyzh.common.exception.BaseException;
/**
* @description AuthException.java文件描述 认证异常类
* @filename AuthException.java
* @author yslg
* @copyright xyzh
* @since 2025-09-28
*/
public class AuthException extends BaseException {
private static final long serialVersionUID = 1L;
public AuthException(String message) {
super(message);
}
public AuthException(String code, String message) {
super(code, message);
}
public AuthException(String message, Throwable cause) {
super(message, cause);
}
public AuthException(String code, String message, Throwable cause) {
super(code, message, cause);
}
public String getCode() {
return super.getCode();
}
public void setCode(String code) {
super.setCode(code);
}
}

View File

@@ -0,0 +1,23 @@
package org.xyzh.common.utils;
import java.util.UUID;
/**
* @description IDUtils.java文件描述
* @filename IDUtils.java
* @author yslg
* @copyright xyzh
* @since 2025-09-07
*/
public class IDUtils {
/**
* @description 生成UUID
* @return UUID
* @author yslg
* @since 2025-09-07
*/
public static String generateID() {
return UUID.randomUUID().toString().replaceAll("-", "");
}
}

View File

@@ -0,0 +1,404 @@
package org.xyzh.common.utils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.BufferedReader;
import java.util.Enumeration;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.HashSet;
/**
* @description ServletUtils.java文件描述Servlet相关常用工具方法
* @filename ServletUtils.java
* @author yslg
* @copyright xyzh
* @since 2023-12-19
*/
public class ServletUtils {
/**
* @description 获取请求的真实IP地址
* @param request HTTP请求对象
* @return 客户端真实IP地址
* @author yslg
* @since 2023-12-19
*/
public static String getClientIp(HttpServletRequest request) {
String ip = request.getHeader("X-Forwarded-For");
if (ip != null && ip.isEmpty() && !"unknown".equalsIgnoreCase(ip)) {
// 多级代理时取第一个
int idx = ip.indexOf(',');
if (idx > -1) {
ip = ip.substring(0, idx);
}
return ip.trim();
}
ip = request.getHeader("Proxy-Client-IP");
if (ip != null && ip.isEmpty() && !"unknown".equalsIgnoreCase(ip)) {
return ip;
}
ip = request.getHeader("WL-Proxy-Client-IP");
if (ip != null && ip.isEmpty() && !"unknown".equalsIgnoreCase(ip)) {
return ip;
}
ip = request.getRemoteAddr();
return ip;
}
/**
* @description 向响应写出JSON字符串
* @param response HTTP响应对象
* @param json 要写出的JSON字符串
* @return void
* @author yslg
* @since 2023-12-19
*/
public static void writeJson(HttpServletResponse response, String json) throws IOException {
response.setContentType("application/json;charset=UTF-8");
PrintWriter writer = response.getWriter();
writer.write(json);
writer.flush();
writer.close();
}
/**
* @description 获取请求参数(支持默认值)
* @param request HTTP请求对象
* @param name 参数名
* @param defaultValue 默认值
* @return 参数值或默认值
* @author yslg
* @since 2023-12-19
*/
public static String getParameter(HttpServletRequest request, String name, String defaultValue) {
String value = request.getParameter(name);
return value != null ? value : defaultValue;
}
/**
* @description 判断请求是否为Ajax
* @param request HTTP请求对象
* @return 是否为Ajax请求
* @author yslg
* @since 2023-12-19
*/
public static boolean isAjaxRequest(HttpServletRequest request) {
String header = request.getHeader("X-Requested-With");
return "XMLHttpRequest".equalsIgnoreCase(header);
}
/**
* @description 获取请求体内容
* @param request HTTP请求对象
* @return 请求体内容
* @author yslg
* @since 2023-12-19
*/
public static String getRequestBody(HttpServletRequest request) throws IOException {
StringBuilder sb = new StringBuilder();
BufferedReader reader = request.getReader();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
return sb.toString();
}
/**
* @description 重定向到指定URL
* @param response HTTP响应对象
* @param url 目标URL
* @return void
* @author yslg
* @since 2023-12-19
*/
public static void redirect(HttpServletResponse response, String url) throws IOException {
response.sendRedirect(url);
}
/**
* @description 获取完整请求URL
* @param request HTTP请求对象
* @return 完整URL
* @author yslg
* @since 2023-12-19
*/
public static String getFullUrl(HttpServletRequest request) {
StringBuilder url = new StringBuilder();
url.append(request.getScheme()).append("://");
url.append(request.getServerName());
int port = request.getServerPort();
if (("http".equals(request.getScheme()) && port != 80) ||
("https".equals(request.getScheme()) && port != 443)) {
url.append(":").append(port);
}
url.append(request.getRequestURI());
String queryString = request.getQueryString();
if (queryString != null) {
url.append("?").append(queryString);
}
return url.toString();
}
/**
* @description 判断请求是否为GET方法
* @param request HTTP请求对象
* @return 是否为GET请求
* @author yslg
* @since 2023-12-19
*/
public static boolean isGet(HttpServletRequest request) {
return "GET".equalsIgnoreCase(request.getMethod());
}
/**
* @description 判断请求是否为POST方法
* @param request HTTP请求对象
* @return 是否为POST请求
* @author yslg
* @since 2023-12-19
*/
public static boolean isPost(HttpServletRequest request) {
return "POST".equalsIgnoreCase(request.getMethod());
}
/**
* @description 判断请求是否为PUT方法
* @param request HTTP请求对象
* @return 是否为PUT请求
* @author yslg
* @since 2023-12-19
*/
public static boolean isPut(HttpServletRequest request) {
return "PUT".equalsIgnoreCase(request.getMethod());
}
/**
* @description 判断请求是否为DELETE方法
* @param request HTTP请求对象
* @return 是否为DELETE请求
* @author yslg
* @since 2023-12-19
*/
public static boolean isDelete(HttpServletRequest request) {
return "DELETE".equalsIgnoreCase(request.getMethod());
}
/**
* @description 获取所有请求参数
* @param request HTTP请求对象
* @return 参数Map
* @author yslg
* @since 2023-12-19
*/
public static Map<String, String> getParameterMap(HttpServletRequest request) {
Map<String, String> paramMap = new HashMap<>();
Enumeration<String> parameterNames = request.getParameterNames();
while (parameterNames.hasMoreElements()) {
String paramName = parameterNames.nextElement();
String paramValue = request.getParameter(paramName);
paramMap.put(paramName, paramValue);
}
return paramMap;
}
/**
* @description 获取请求头信息
* @param request HTTP请求对象
* @return 头信息Map
* @author yslg
* @since 2023-12-19
*/
public static Map<String, String> getHeaderMap(HttpServletRequest request) {
Map<String, String> headerMap = new HashMap<>();
Enumeration<String> headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
String headerName = headerNames.nextElement();
String headerValue = request.getHeader(headerName);
headerMap.put(headerName, headerValue);
}
return headerMap;
}
/**
* @description 获取Cookie值
* @param request HTTP请求对象
* @param name Cookie名
* @return Cookie值
* @author yslg
* @since 2023-12-19
*/
public static String getCookieValue(HttpServletRequest request, String name) {
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (name.equals(cookie.getName())) {
return cookie.getValue();
}
}
}
return null;
}
/**
* @description 设置Cookie
* @param response HTTP响应对象
* @param name Cookie名
* @param value Cookie值
* @param maxAge 过期时间(秒)
* @return void
* @author yslg
* @since 2023-12-19
*/
public static void setCookie(HttpServletResponse response, String name, String value, int maxAge) {
Cookie cookie = new Cookie(name, value);
cookie.setMaxAge(maxAge);
cookie.setPath("/");
cookie.setHttpOnly(true);
response.addCookie(cookie);
}
/**
* @description 删除Cookie
* @param response HTTP响应对象
* @param name Cookie名
* @return void
* @author yslg
* @since 2023-12-19
*/
public static void removeCookie(HttpServletResponse response, String name) {
Cookie cookie = new Cookie(name, null);
cookie.setMaxAge(0);
cookie.setPath("/");
response.addCookie(cookie);
}
/**
* @description 判断是否为HTTPS请求
* @param request HTTP请求对象
* @return 是否为HTTPS请求
* @author yslg
* @since 2023-12-19
*/
public static boolean isHttps(HttpServletRequest request) {
return "https".equals(request.getScheme()) || request.isSecure() ||
"443".equals(request.getHeader("X-Forwarded-Port")) ||
"https".equals(request.getHeader("X-Forwarded-Proto"));
}
/**
* @description 获取上下文路径
* @param request HTTP请求对象
* @return 上下文路径
* @author yslg
* @since 2023-12-19
*/
public static String getContextPath(HttpServletRequest request) {
return request.getContextPath();
}
/**
* @description 检测请求是否包含指定参数
* @param request HTTP请求对象
* @param paramName 参数名
* @return 是否包含参数
* @author yslg
* @since 2023-12-19
*/
public static boolean hasParameter(HttpServletRequest request, String paramName) {
return request.getParameter(paramName) != null;
}
/**
* @description 获取Session对象
* @param request HTTP请求对象
* @return HttpSession对象
* @author yslg
* @since 2023-12-19
*/
public static HttpSession getSession(HttpServletRequest request) {
return request.getSession();
}
/**
* @description 获取Session属性
* @param request HTTP请求对象
* @param attributeName 属性名
* @return 属性值
* @author yslg
* @since 2023-12-19
*/
public static Object getSessionAttribute(HttpServletRequest request, String attributeName) {
HttpSession session = request.getSession(false);
return session != null ? session.getAttribute(attributeName) : null;
}
/**
* @description 设置Session属性
* @param request HTTP请求对象
* @param attributeName 属性名
* @param attributeValue 属性值
* @return void
* @author yslg
* @since 2023-12-19
*/
public static void setSessionAttribute(HttpServletRequest request, String attributeName, Object attributeValue) {
request.getSession().setAttribute(attributeName, attributeValue);
}
/**
* @description 移除Session属性
* @param request HTTP请求对象
* @param attributeName 属性名
* @return void
* @author yslg
* @since 2023-12-19
*/
public static void removeSessionAttribute(HttpServletRequest request, String attributeName) {
HttpSession session = request.getSession(false);
if (session != null) {
session.removeAttribute(attributeName);
}
}
/**
* @description 防止XSS攻击的字符串过滤
* @param input 输入字符串
* @return 过滤后的字符串
* @author yslg
* @since 2023-12-19
*/
public static String escapeXss(String input) {
if (input == null) {
return null;
}
return input
.replace("<", "&lt;")
.replace(">", "&gt;")
.replace("'", "&#39;")
.replace("\"", "&quot;")
.replace("&", "&amp;");
}
/**
* @description 获取所有请求参数名
* @param request HTTP请求对象
* @return 参数名集合
* @author yslg
* @since 2023-12-19
*/
public static Set<String> getParameterNames(HttpServletRequest request) {
Set<String> paramNames = new HashSet<>();
Enumeration<String> names = request.getParameterNames();
while (names.hasMoreElements()) {
paramNames.add(names.nextElement());
}
return paramNames;
}
}

View File

@@ -0,0 +1,235 @@
package org.xyzh.common.utils;
/**
* @description StringUtils.java文件描述 字符串工具类
* @filename StringUtils.java
* @author yslg
* @copyright xyzh
* @since 2025-09-07
*/
public class StringUtils {
/**
* @description 字符串是否为空
* @param str String 字符串
* @return 是否为空
* @author yslg
* @since 2025-09-07
*/
public static boolean isEmpty(String str) {
return str == null || str.isEmpty();
}
/**
* @description 字符串是否不为空
* @param str String 字符串
* @return 是否不为空
* @author yslg
* @since 2025-09-07
*/
public static boolean isNotEmpty(String str) {
return !isEmpty(str);
}
public static String format(String template, Object... args) {
if (template == null || args == null) return template;
return String.format(template, args);
}
/**
* @description 去除字符串首尾空格
* @param str String 字符串
* @return 去除空格后的字符串
* @author yslg
* @since 2025-09-07
*/
public static String trim(String str) {
return str == null ? null : str.trim();
}
/**
* @description 判断两个字符串是否相等支持null
* @param a String 字符串A
* @param b String 字符串B
* @return 是否相等
* @author yslg
* @since 2025-09-07
*/
public static boolean equals(String a, String b) {
return a == null ? b == null : a.equals(b);
}
/**
* @description 判断字符串是否包含子串
* @param str String 原字符串
* @param sub String 子串
* @return 是否包含
* @author yslg
* @since 2025-09-07
*/
public static boolean contains(String str, String sub) {
return str != null && sub != null && str.contains(sub);
}
/**
* @description 字符串拼接(用分隔符)
* @param delimiter String 分隔符
* @param elements String[] 待拼接字符串数组
* @return 拼接后的字符串
* @author yslg
* @since 2025-09-07
*/
public static String join(String delimiter, String... elements) {
if (elements == null) return null;
return String.join(delimiter, elements);
}
/**
* @description 字符串分割
* @param str String 原字符串
* @param regex String 分割正则表达式
* @return 分割后的字符串数组
* @author yslg
* @since 2025-09-07
*/
public static String[] split(String str, String regex) {
return str == null ? null : str.split(regex);
}
/**
* @description 字符串替换
* @param str String 原字符串
* @param target String 替换目标
* @param replacement String 替换内容
* @return 替换后的字符串
* @author yslg
* @since 2025-09-07
*/
public static String replace(String str, String target, String replacement) {
return str == null ? null : str.replace(target, replacement);
}
/**
* @description 是否以指定前缀开头
* @param str String 原字符串
* @param prefix String 前缀
* @return 是否以前缀开头
* @author yslg
* @since 2025-09-07
*/
public static boolean startsWith(String str, String prefix) {
return str != null && prefix != null && str.startsWith(prefix);
}
/**
* @description 是否以指定后缀结尾
* @param str String 原字符串
* @param suffix String 后缀
* @return 是否以后缀结尾
* @author yslg
* @since 2025-09-07
*/
public static boolean endsWith(String str, String suffix) {
return str != null && suffix != null && str.endsWith(suffix);
}
/**
* @description 转为大写
* @param str String 原字符串
* @return 大写字符串
* @author yslg
* @since 2025-09-07
*/
public static String toUpperCase(String str) {
return str == null ? null : str.toUpperCase();
}
/**
* @description 转为小写
* @param str String 原字符串
* @return 小写字符串
* @author yslg
* @since 2025-09-07
*/
public static String toLowerCase(String str) {
return str == null ? null : str.toLowerCase();
}
/**
* @description 反转字符串
* @param str String 原字符串
* @return 反转后的字符串
* @author yslg
* @since 2025-09-07
*/
public static String reverse(String str) {
if (str == null) return null;
return new StringBuilder(str).reverse().toString();
}
/**
* @description 重复字符串n次
* @param str String 原字符串
* @param n int 重复次数
* @return 重复后的字符串
* @author yslg
* @since 2025-09-07
*/
public static String repeat(String str, int n) {
if (str == null || n <= 0) return "";
return str.repeat(n);
}
/**
* @description 截取字符串
* @param str String 原字符串
* @param beginIndex int 起始索引
* @param endIndex int 结束索引
* @return 截取后的字符串
* @author yslg
* @since 2025-09-07
*/
public static String substring(String str, int beginIndex, int endIndex) {
if (str == null) return null;
if (beginIndex < 0) beginIndex = 0;
if (endIndex > str.length()) endIndex = str.length();
if (beginIndex > endIndex) return "";
return str.substring(beginIndex, endIndex);
}
/**
* @description 判断字符串是否为数字
* @param str String 原字符串
* @return 是否为数字
* @author yslg
* @since 2025-09-07
*/
public static boolean isNumeric(String str) {
if (isEmpty(str)) return false;
for (int i = 0; i < str.length(); i++) {
if (!Character.isDigit(str.charAt(i))) return false;
}
return true;
}
/**
* @description 字符串是否为空白
* @param str String 原字符串
* @return 是否为空白
* @author yslg
* @since 2025-09-07
*/
public static boolean isBlank(String str) {
return str == null || str.isBlank();
}
/**
* @description 字符串是否不为空白
* @param str String 原字符串
* @return 是否不为空白
* @author yslg
* @since 2025-09-07
*/
public static boolean isNotBlank(String str) {
return !isBlank(str);
}
}

View File

@@ -0,0 +1,297 @@
package org.xyzh.common.utils;
import java.text.DateFormat;
import java.time.Duration;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Instant;
import java.time.ZoneId;
import java.text.ParseException;
/**
* @description TimeUtils.java文件描述时间相关的常用工具方法
* @filename TimeUtils.java
* @author yslg
* @copyright xyzh
* @since 2025-09-05
*/
public class TimeUtils {
/**
* @description 将时间戳字符串转为指定格式的日期时间字符串
* @param time 毫秒时间戳字符串
* @param format 日期格式化对象
* @return 格式化后的日期时间字符串
* @author yslg
* @since 2025-09-05
*/
public static String timeFormat(String time, DateFormat format){
try {
Date date = format.parse(time);
return format.format(date);
} catch (ParseException e) {
return null;
}
}
/**
* @description 格式化Date为指定格式字符串
* @param date Date对象
* @param pattern 格式化模式,如"yyyy-MM-dd HH:mm:ss"
* @return String 格式化后的字符串
*/
public static String format(Date date, String pattern) {
if (date == null || pattern == null) return null;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
LocalDateTime ldt = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
return ldt.format(formatter);
}
/**
* @description 格式化LocalDate为指定格式字符串
* @param localDate LocalDate对象
* @param pattern 格式化模式
* @return 格式化后的字符串
*/
public static String format(LocalDate localDate, String pattern) {
if (localDate == null || pattern == null) return null;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
return localDate.format(formatter);
}
/**
* @description 格式化LocalDateTime为指定格式字符串
* @param localDateTime LocalDateTime对象
* @param pattern 格式化模式
* @return 格式化后的字符串
*/
public static String format(LocalDateTime localDateTime, String pattern) {
if (localDateTime == null || pattern == null) return null;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
return localDateTime.format(formatter);
}
/**
* @description 格式化时间戳为指定格式字符串
* @param timestampMillis 毫秒时间戳
* @param pattern 格式化模式
* @return 格式化后的字符串
*/
public static String format(long timestampMillis, String pattern) {
if (pattern == null) return null;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
LocalDateTime ldt = Instant.ofEpochMilli(timestampMillis).atZone(ZoneId.systemDefault()).toLocalDateTime();
return ldt.format(formatter);
}
/**
* @description 将字符串按指定格式解析为LocalDateTime
* @param dateTimeStr 日期时间字符串
* @param pattern 格式化模式
* @return LocalDateTime对象解析失败返回null
*/
public static LocalDateTime parseToLocalDateTime(String dateTimeStr, String pattern) {
if (dateTimeStr == null || pattern == null) return null;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
try {
return LocalDateTime.parse(dateTimeStr, formatter);
} catch (Exception e) {
return null;
}
}
/**
* @description 将字符串按指定格式解析为LocalDate
* @param dateStr 日期字符串
* @param pattern 格式化模式
* @return LocalDate对象解析失败返回null
*/
public static LocalDate parseToLocalDate(String dateStr, String pattern) {
if (dateStr == null || pattern == null) return null;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
try {
return LocalDate.parse(dateStr, formatter);
} catch (Exception e) {
return null;
}
}
/**
* @description 将字符串或Date对象按指定DateTimeFormatter格式化为标准时间字符串yyyy-MM-dd HH:mm:ss
* @param input 可以为String类型的日期、Date对象或LocalDateTime对象
* @param formatter 指定的DateTimeFormatter
* @return 标准化时间字符串无法解析时返回null
*/
public static String normalizeToDateTimeString(Object input, DateTimeFormatter formatter) {
if (input == null || formatter == null) return null;
try {
if (input instanceof String str) {
LocalDateTime ldt;
try {
ldt = LocalDateTime.parse(str, formatter);
} catch (Exception e) {
LocalDate ld = LocalDate.parse(str, formatter);
ldt = ld.atStartOfDay();
}
return ldt.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
}
if (input instanceof Date date) {
LocalDateTime ldt = dateToLocalDateTime(date);
return ldt.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
}
if (input instanceof LocalDateTime ldt) {
return ldt.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
}
if (input instanceof LocalDate ld) {
return ld.atStartOfDay().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
}
} catch (Exception e) {
return null;
}
return null;
}
/**
* @description 获取当前时间戳,单位毫秒
* @return 当前时间戳字符串
* @author yslg
* @since 2025-09-05
*/
public static String getCurrentTimestamp() {
return String.valueOf(System.currentTimeMillis());
}
/**
* @description 获取当前时间戳,单位秒
* @return 当前时间戳(秒)字符串
* @author yslg
* @since 2025-09-05
*/
public static String getCurrentTimestampSeconds() {
return String.valueOf(System.currentTimeMillis() / 1000);
}
/**
* @description 获取当前日期时间格式yyyy-MM-dd HH:mm:ss
* @return 当前日期时间字符串
* @author yslg
* @since 2025-09-05
*/
public static String getCurrentDateTime() {
return LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
}
/**
* @description 获取当前日期格式yyyy-MM-dd
* @return 当前日期字符串
* @author yslg
* @since 2025-09-05
*/
public static String getCurrentDate() {
return LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
}
/**
* @description 获取当前时间格式HH:mm:ss
* @return 当前时间字符串
* @author yslg
* @since 2025-09-05
*/
public static String getCurrentTime() {
return LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss"));
}
/**
* @description 将时间戳毫秒转为日期时间字符串格式yyyy-MM-dd HH:mm:ss
* @param timestampMillis 毫秒时间戳
* @return 日期时间字符串
* @author yslg
* @since 2025-09-05
*/
public static String timestampToDateTime(long timestampMillis) {
return Instant.ofEpochMilli(timestampMillis)
.atZone(ZoneId.systemDefault())
.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
}
/**
* @description 将日期时间字符串yyyy-MM-dd HH:mm:ss转为时间戳毫秒
* @param dateTimeStr 日期时间字符串
* @return 毫秒时间戳
* @author yslg
* @since 2025-09-05
*/
public static long dateTimeToTimestamp(String dateTimeStr) {
LocalDateTime ldt = LocalDateTime.parse(dateTimeStr, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
return ldt.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
}
/**
* @description 获取指定日期加减天数后的日期字符串yyyy-MM-dd
* @param dateStr 原始日期字符串
* @param days 增加或减少的天数(可为负数)
* @return 计算后的日期字符串
* @author yslg
* @since 2025-09-05
*/
public static String plusDays(String dateStr, int days) {
LocalDate date = LocalDate.parse(dateStr, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
return date.plusDays(days).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
}
/**
* @description 获取两个日期之间的天数差
* @param startDate 开始日期字符串yyyy-MM-dd
* @param endDate 结束日期字符串yyyy-MM-dd
* @return 天数差
* @author yslg
* @since 2025-09-05
*/
public static long daysBetween(String startDate, String endDate) {
LocalDate start = LocalDate.parse(startDate, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
LocalDate end = LocalDate.parse(endDate, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
return Duration.between(start.atStartOfDay(), end.atStartOfDay()).toDays();
}
/**
* @description 判断当前时间是否在指定时间段内
* @param startTime 开始时间字符串HH:mm:ss
* @param endTime 结束时间字符串HH:mm:ss
* @return 是否在时间段内
* @author yslg
* @since 2025-09-05
*/
public static boolean isNowBetween(String startTime, String endTime) {
LocalTime now = LocalTime.now();
LocalTime start = LocalTime.parse(startTime, DateTimeFormatter.ofPattern("HH:mm:ss"));
LocalTime end = LocalTime.parse(endTime, DateTimeFormatter.ofPattern("HH:mm:ss"));
return !now.isBefore(start) && !now.isAfter(end);
}
/**
* @description Date转LocalDateTime
* @param date java.util.Date对象
* @return LocalDateTime对象
* @author yslg
* @since 2025-09-05
*/
public static LocalDateTime dateToLocalDateTime(Date date) {
return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
}
/**
* @description LocalDateTime转Date
* @param localDateTime LocalDateTime对象
* @return java.util.Date对象
* @author yslg
* @since 2025-09-05
*/
public static Date localDateTimeToDate(LocalDateTime localDateTime) {
return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
}
}

View File

@@ -21,6 +21,7 @@
<module>common-redis</module> <module>common-redis</module>
<module>common-jdbc</module> <module>common-jdbc</module>
<module>common-util</module> <module>common-util</module>
<module>common-all</module>
</modules> </modules>
<properties> <properties>