v3.0.0 init

This commit is contained in:
ageerle
2026-02-06 03:00:23 +08:00
parent eb2e8f3ff8
commit 7b8cfe02a1
1524 changed files with 53132 additions and 58866 deletions

View File

@@ -23,7 +23,7 @@ public class CaptchaConfig {
private static final int WIDTH = 160;
private static final int HEIGHT = 60;
private static final Color BACKGROUND = Color.PINK;
private static final Color BACKGROUND = Color.LIGHT_GRAY;
private static final Font FONT = new Font("Arial", Font.BOLD, 48);
/**

View File

@@ -1,19 +1,16 @@
package org.ruoyi.common.web.config;
import jakarta.servlet.DispatcherType;
import org.ruoyi.common.core.utils.StringUtils;
import org.ruoyi.common.web.config.properties.XssProperties;
import org.ruoyi.common.web.filter.RepeatableFilter;
import org.ruoyi.common.web.filter.XssFilter;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistration;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import java.util.HashMap;
import java.util.Map;
/**
* Filter配置
*
@@ -23,31 +20,22 @@ import java.util.Map;
@EnableConfigurationProperties(XssProperties.class)
public class FilterConfig {
@SuppressWarnings({"rawtypes", "unchecked"})
@Bean
@ConditionalOnProperty(value = "xss.enabled", havingValue = "true")
public FilterRegistrationBean xssFilterRegistration(XssProperties xssProperties) {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setDispatcherTypes(DispatcherType.REQUEST);
registration.setFilter(new XssFilter());
registration.addUrlPatterns(StringUtils.split(xssProperties.getUrlPatterns(), StringUtils.SEPARATOR));
registration.setName("xssFilter");
registration.setOrder(FilterRegistrationBean.HIGHEST_PRECEDENCE);
Map<String, String> initParameters = new HashMap<>();
initParameters.put("excludes", xssProperties.getExcludes());
registration.setInitParameters(initParameters);
return registration;
@FilterRegistration(
name = "xssFilter",
urlPatterns = "/*",
order = FilterRegistrationBean.HIGHEST_PRECEDENCE + 1,
dispatcherTypes = DispatcherType.REQUEST
)
public XssFilter xssFilter() {
return new XssFilter();
}
@SuppressWarnings({"rawtypes", "unchecked"})
@Bean
public FilterRegistrationBean someFilterRegistration() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new RepeatableFilter());
registration.addUrlPatterns("/*");
registration.setName("repeatableFilter");
registration.setOrder(FilterRegistrationBean.LOWEST_PRECEDENCE);
return registration;
@FilterRegistration(name = "repeatableFilter", urlPatterns = "/*")
public RepeatableFilter repeatableFilter() {
return new RepeatableFilter();
}
}

View File

@@ -1,11 +1,13 @@
package org.ruoyi.common.web.config;
import org.ruoyi.common.web.interceptor.DemoModeInterceptor;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import org.ruoyi.common.core.utils.ObjectUtils;
import org.ruoyi.common.web.handler.GlobalExceptionHandler;
import org.ruoyi.common.web.interceptor.PlusWebInvokeTimeInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@@ -13,6 +15,8 @@ import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.Date;
/**
* 通用配置
*
@@ -21,35 +25,22 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@AutoConfiguration
public class ResourcesConfig implements WebMvcConfigurer {
@Autowired(required = false)
private DemoModeInterceptor demoModeInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 全局访问性能拦截
registry.addInterceptor(new PlusWebInvokeTimeInterceptor());
}
// 演示模式拦截器
if (demoModeInterceptor != null) {
registry.addInterceptor(demoModeInterceptor)
.addPathPatterns("/**") // 拦截所有路径
.excludePathPatterns(
// 排除静态资源
"/css/**",
"/js/**",
"/images/**",
"/fonts/**",
"/favicon.ico",
// 排除错误页面
"/error",
// 排除API文档
"/*/api-docs/**",
"/swagger-ui/**",
"/webjars/**",
// 排除监控端点
"/actuator/**"
);
}
@Override
public void addFormatters(FormatterRegistry registry) {
// 全局日期格式转换配置
registry.addConverter(String.class, Date.class, source -> {
DateTime parse = DateUtil.parse(source);
if (ObjectUtils.isNull(parse)) {
return null;
}
return parse.toJdkDate();
});
}
@Override
@@ -77,4 +68,12 @@ public class ResourcesConfig implements WebMvcConfigurer {
// 返回新的CorsFilter
return new CorsFilter(source);
}
/**
* 全局异常处理器
*/
@Bean
public GlobalExceptionHandler globalExceptionHandler() {
return new GlobalExceptionHandler();
}
}

View File

@@ -1,10 +1,14 @@
package org.ruoyi.common.web.config;
import io.undertow.server.DefaultByteBufferPool;
import io.undertow.server.handlers.DisallowedMethodsHandler;
import io.undertow.util.HttpString;
import io.undertow.websockets.jsr.WebSocketDeploymentInfo;
import org.ruoyi.common.core.utils.SpringUtils;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.core.task.VirtualThreadTaskExecutor;
/**
* Undertow 自定义配置
@@ -15,15 +19,44 @@ import org.springframework.boot.web.server.WebServerFactoryCustomizer;
public class UndertowConfig implements WebServerFactoryCustomizer<UndertowServletWebServerFactory> {
/**
* 设置 Undertow 的 websocket 缓冲池
* 自定义 Undertow 配置
* <p>
* 主要配置内容包括:
* 1. 配置 WebSocket 部署信息
* 2. 在虚拟线程模式下使用虚拟线程池
* 3. 禁用不安全的 HTTP 方法,如 CONNECT、TRACE、TRACK
* </p>
*
* @param factory Undertow 的 Web 服务器工厂
*/
@Override
public void customize(UndertowServletWebServerFactory factory) {
// 默认不直接分配内存 如果项目中使用了 websocket 建议直接分配
factory.addDeploymentInfoCustomizers(deploymentInfo -> {
// 配置 WebSocket 部署信息,设置 WebSocket 使用的缓冲区池
WebSocketDeploymentInfo webSocketDeploymentInfo = new WebSocketDeploymentInfo();
webSocketDeploymentInfo.setBuffers(new DefaultByteBufferPool(false, 512));
webSocketDeploymentInfo.setBuffers(new DefaultByteBufferPool(true, 1024));
deploymentInfo.addServletContextAttribute("io.undertow.websockets.jsr.WebSocketDeploymentInfo", webSocketDeploymentInfo);
// 如果启用了虚拟线程,配置 Undertow 使用虚拟线程池
if (SpringUtils.isVirtual()) {
// 创建虚拟线程池,线程池前缀为 "undertow-"
VirtualThreadTaskExecutor executor = new VirtualThreadTaskExecutor("undertow-");
// 设置虚拟线程池为执行器和异步执行器
deploymentInfo.setExecutor(executor);
deploymentInfo.setAsyncExecutor(executor);
}
// 配置禁止某些不安全的 HTTP 方法(如 CONNECT、TRACE、TRACK
deploymentInfo.addInitialHandlerChainWrapper(handler -> {
// 禁止三个方法 CONNECT/TRACE/TRACK 也是不安全的 避免爬虫骚扰
HttpString[] disallowedHttpMethods = {
HttpString.tryFromString("CONNECT"),
HttpString.tryFromString("TRACE"),
HttpString.tryFromString("TRACK")
};
// 使用 DisallowedMethodsHandler 拦截并拒绝这些方法的请求
return new DisallowedMethodsHandler(handler, disallowedHttpMethods);
});
});
}

View File

@@ -1,10 +1,9 @@
package org.ruoyi.common.web.config.properties;
import lombok.Data;
import org.ruoyi.common.web.enums.CaptchaCategory;
import org.ruoyi.common.web.enums.CaptchaType;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* 验证码 配置属性
@@ -12,7 +11,6 @@ import org.springframework.stereotype.Component;
* @author Lion Li
*/
@Data
@Component
@ConfigurationProperties(prefix = "captcha")
public class CaptchaProperties {

View File

@@ -3,6 +3,9 @@ package org.ruoyi.common.web.config.properties;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import java.util.ArrayList;
import java.util.List;
/**
* xss过滤 配置属性
*
@@ -13,18 +16,13 @@ import org.springframework.boot.context.properties.ConfigurationProperties;
public class XssProperties {
/**
* 过滤开关
* Xss开关
*/
private String enabled;
private Boolean enabled;
/**
* 排除链接(多个用逗号分隔)
* 排除路径
*/
private String excludes;
/**
* 匹配链接
*/
private String urlPatterns;
private List<String> excludeUrls = new ArrayList<>();
}

View File

@@ -1,9 +1,9 @@
package org.ruoyi.common.web.core;
import org.springframework.web.servlet.LocaleResolver;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.LocaleResolver;
import java.util.Locale;
/**

View File

@@ -1,10 +1,10 @@
package org.ruoyi.common.web.enums;
import cn.hutool.captcha.generator.CodeGenerator;
import cn.hutool.captcha.generator.MathGenerator;
import cn.hutool.captcha.generator.RandomGenerator;
import lombok.AllArgsConstructor;
import lombok.Getter;
import org.ruoyi.common.web.utils.UnsignedMathGenerator;
/**
* 验证码类型
@@ -18,7 +18,7 @@ public enum CaptchaType {
/**
* 数字
*/
MATH(UnsignedMathGenerator.class),
MATH(MathGenerator.class),
/**
* 字符

View File

@@ -1,10 +1,10 @@
package org.ruoyi.common.web.filter;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import org.ruoyi.common.core.utils.StringUtils;
import org.springframework.http.MediaType;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import java.io.IOException;
/**
@@ -20,10 +20,10 @@ public class RepeatableFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
throws IOException, ServletException {
ServletRequest requestWrapper = null;
if (request instanceof HttpServletRequest
&& StringUtils.startsWithIgnoreCase(request.getContentType(), MediaType.APPLICATION_JSON_VALUE)) {
&& StringUtils.startsWithIgnoreCase(request.getContentType(), MediaType.APPLICATION_JSON_VALUE)) {
requestWrapper = new RepeatedlyRequestWrapper((HttpServletRequest) request, response);
}
if (null == requestWrapper) {

View File

@@ -1,12 +1,13 @@
package org.ruoyi.common.web.filter;
import cn.hutool.core.io.IoUtil;
import org.ruoyi.common.core.constant.Constants;
import jakarta.servlet.ReadListener;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletRequestWrapper;
import org.ruoyi.common.core.constant.Constants;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;

View File

@@ -1,11 +1,13 @@
package org.ruoyi.common.web.filter;
import org.ruoyi.common.core.utils.SpringUtils;
import org.ruoyi.common.core.utils.StringUtils;
import org.ruoyi.common.web.config.properties.XssProperties;
import org.springframework.http.HttpMethod;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.ruoyi.common.core.utils.StringUtils;
import org.springframework.http.HttpMethod;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@@ -23,18 +25,13 @@ public class XssFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
String tempExcludes = filterConfig.getInitParameter("excludes");
if (StringUtils.isNotEmpty(tempExcludes)) {
String[] url = tempExcludes.split(StringUtils.SEPARATOR);
for (int i = 0; url != null && i < url.length; i++) {
excludes.add(url[i]);
}
}
XssProperties properties = SpringUtils.getBean(XssProperties.class);
excludes.addAll(properties.getExcludeUrls());
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
if (handleExcludeURL(req, resp)) {

View File

@@ -1,6 +1,8 @@
package org.ruoyi.common.web.filter;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HtmlUtil;
import jakarta.servlet.ReadListener;
@@ -14,6 +16,8 @@ import org.springframework.http.MediaType;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
/**
* XSS过滤处理
@@ -28,19 +32,52 @@ public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {
super(request);
}
@Override
public String getParameter(String name) {
String value = super.getParameter(name);
if (value == null) {
return null;
}
return HtmlUtil.cleanHtmlTag(value).trim();
}
@Override
public Map<String, String[]> getParameterMap() {
Map<String, String[]> valueMap = super.getParameterMap();
if (MapUtil.isEmpty(valueMap)) {
return valueMap;
}
// 避免某些容器不允许改参数的情况 copy一份重新改
Map<String, String[]> map = new HashMap<>(valueMap.size());
map.putAll(valueMap);
for (Map.Entry<String, String[]> entry : map.entrySet()) {
String[] values = entry.getValue();
if (values != null) {
int length = values.length;
String[] escapseValues = new String[length];
for (int i = 0; i < length; i++) {
// 防xss攻击和过滤前后空格
escapseValues[i] = HtmlUtil.cleanHtmlTag(values[i]).trim();
}
map.put(entry.getKey(), escapseValues);
}
}
return map;
}
@Override
public String[] getParameterValues(String name) {
String[] values = super.getParameterValues(name);
if (values != null) {
int length = values.length;
String[] escapseValues = new String[length];
for (int i = 0; i < length; i++) {
// 防xss攻击和过滤前后空格
escapseValues[i] = HtmlUtil.cleanHtmlTag(values[i]).trim();
}
return escapseValues;
if (ArrayUtil.isEmpty(values)) {
return values;
}
return super.getParameterValues(name);
int length = values.length;
String[] escapseValues = new String[length];
for (int i = 0; i < length; i++) {
// 防xss攻击和过滤前后空格
escapseValues[i] = HtmlUtil.cleanHtmlTag(values[i]).trim();
}
return escapseValues;
}
@Override

View File

@@ -0,0 +1,213 @@
package org.ruoyi.common.web.handler;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpStatus;
import com.fasterxml.jackson.core.JsonParseException;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.ruoyi.common.core.domain.R;
import org.ruoyi.common.core.exception.ServiceException;
import org.ruoyi.common.core.exception.SseException;
import org.ruoyi.common.core.exception.base.BaseException;
import org.ruoyi.common.core.utils.StreamUtils;
import org.ruoyi.common.json.utils.JsonUtils;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingPathVariableException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.async.AsyncRequestTimeoutException;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.servlet.NoHandlerFoundException;
import java.io.IOException;
/**
* 全局异常处理器
*
* @author Lion Li
*/
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
/**
* 请求方式不支持
*/
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
public R<Void> handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e,
HttpServletRequest request) {
String requestURI = request.getRequestURI();
log.error("请求地址'{}',不支持'{}'请求", requestURI, e.getMethod());
return R.fail(HttpStatus.HTTP_BAD_METHOD, e.getMessage());
}
/**
* 业务异常
*/
@ExceptionHandler(ServiceException.class)
public R<Void> handleServiceException(ServiceException e, HttpServletRequest request) {
log.error(e.getMessage());
Integer code = e.getCode();
return ObjectUtil.isNotNull(code) ? R.fail(code, e.getMessage()) : R.fail(e.getMessage());
}
/**
* 认证失败
*/
@ResponseStatus(org.springframework.http.HttpStatus.UNAUTHORIZED)
@ExceptionHandler(SseException.class)
public String handleNotLoginException(SseException e, HttpServletRequest request) {
String requestURI = request.getRequestURI();
log.debug("请求地址'{}',认证失败'{}',无法访问系统资源", requestURI, e.getMessage());
return JsonUtils.toJsonString(R.fail(HttpStatus.HTTP_UNAUTHORIZED, "认证失败,无法访问系统资源"));
}
/**
* servlet异常
*/
@ExceptionHandler(ServletException.class)
public R<Void> handleServletException(ServletException e, HttpServletRequest request) {
String requestURI = request.getRequestURI();
log.error("请求地址'{}',发生未知异常.", requestURI, e);
return R.fail(e.getMessage());
}
/**
* 业务异常
*/
@ExceptionHandler(BaseException.class)
public R<Void> handleBaseException(BaseException e, HttpServletRequest request) {
log.error(e.getMessage());
return R.fail(e.getMessage());
}
/**
* 请求路径中缺少必需的路径变量
*/
@ExceptionHandler(MissingPathVariableException.class)
public R<Void> handleMissingPathVariableException(MissingPathVariableException e, HttpServletRequest request) {
String requestURI = request.getRequestURI();
log.error("请求路径中缺少必需的路径变量'{}',发生系统异常.", requestURI);
return R.fail(String.format("请求路径中缺少必需的路径变量[%s]", e.getVariableName()));
}
/**
* 请求参数类型不匹配
*/
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
public R<Void> handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e, HttpServletRequest request) {
String requestURI = request.getRequestURI();
log.error("请求参数类型不匹配'{}',发生系统异常.", requestURI);
return R.fail(String.format("请求参数类型不匹配,参数[%s]要求类型为:'%s',但输入值为:'%s'", e.getName(), e.getRequiredType().getName(), e.getValue()));
}
/**
* 找不到路由
*/
@ExceptionHandler(NoHandlerFoundException.class)
public R<Void> handleNoHandlerFoundException(NoHandlerFoundException e, HttpServletRequest request) {
String requestURI = request.getRequestURI();
log.error("请求地址'{}'不存在.", requestURI);
return R.fail(HttpStatus.HTTP_NOT_FOUND, e.getMessage());
}
/**
* 拦截未知的运行时异常
*/
@ResponseStatus(org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(IOException.class)
public void handleIoException(IOException e, HttpServletRequest request) {
String requestURI = request.getRequestURI();
if (requestURI.contains("sse")) {
// sse 经常性连接中断 例如关闭浏览器 直接屏蔽
return;
}
log.error("请求地址'{}',连接中断", requestURI, e);
}
/**
* sse 连接超时异常 不需要处理
*/
@ExceptionHandler(AsyncRequestTimeoutException.class)
public void handleRuntimeException(AsyncRequestTimeoutException e) {
}
/**
* 拦截未知的运行时异常
*/
@ExceptionHandler(RuntimeException.class)
public R<Void> handleRuntimeException(RuntimeException e, HttpServletRequest request) {
String requestURI = request.getRequestURI();
log.error("请求地址'{}',发生未知异常.", requestURI, e);
return R.fail(e.getMessage());
}
/**
* 系统异常
*/
@ExceptionHandler(Exception.class)
public R<Void> handleException(Exception e, HttpServletRequest request) {
String requestURI = request.getRequestURI();
log.error("请求地址'{}',发生系统异常.", requestURI, e);
return R.fail(e.getMessage());
}
/**
* 自定义验证异常
*/
@ExceptionHandler(BindException.class)
public R<Void> handleBindException(BindException e) {
log.error(e.getMessage());
String message = StreamUtils.join(e.getAllErrors(), DefaultMessageSourceResolvable::getDefaultMessage, ", ");
return R.fail(message);
}
/**
* 自定义验证异常
*/
@ExceptionHandler(ConstraintViolationException.class)
public R<Void> constraintViolationException(ConstraintViolationException e) {
log.error(e.getMessage());
String message = StreamUtils.join(e.getConstraintViolations(), ConstraintViolation::getMessage, ", ");
return R.fail(message);
}
/**
* 自定义验证异常
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
public R<Void> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
log.error(e.getMessage());
String message = StreamUtils.join(e.getBindingResult().getAllErrors(), DefaultMessageSourceResolvable::getDefaultMessage, ", ");
return R.fail(message);
}
/**
* JSON 解析异常Jackson 在处理 JSON 格式出错时抛出)
* 可能是请求体格式非法,也可能是服务端反序列化失败
*/
@ExceptionHandler(JsonParseException.class)
public R<Void> handleJsonParseException(JsonParseException e, HttpServletRequest request) {
String requestURI = request.getRequestURI();
log.error("请求地址'{}' 发生 JSON 解析异常: {}", requestURI, e.getMessage());
return R.fail(HttpStatus.HTTP_BAD_REQUEST, "请求数据格式错误JSON 解析失败):" + e.getMessage());
}
/**
* 请求体读取异常(通常是请求参数格式非法、字段类型不匹配等)
*/
@ExceptionHandler(HttpMessageNotReadableException.class)
public R<Void> handleHttpMessageNotReadableException(HttpMessageNotReadableException e, HttpServletRequest request) {
log.error("请求地址'{}', 参数解析失败: {}", request.getRequestURI(), e.getMessage());
return R.fail(HttpStatus.HTTP_BAD_REQUEST, "请求参数格式错误:" + e.getMostSpecificCause().getMessage());
}
}

View File

@@ -1,96 +0,0 @@
package org.ruoyi.common.web.interceptor;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.ruoyi.common.core.config.RuoYiConfig;
import org.ruoyi.common.core.exception.DemoModeException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
/**
* 演示模式拦截器
* 全局拦截所有编辑操作POST、PUT、DELETE、PATCH
*
* @author ruoyi
*/
@Slf4j
@Component
public class DemoModeInterceptor implements HandlerInterceptor {
@Autowired
private RuoYiConfig ruoYiConfig;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 如果演示模式未开启,直接放行
if (!ruoYiConfig.isDemoEnabled()) {
return true;
}
String method = request.getMethod();
String requestURI = request.getRequestURI();
// 拦截所有编辑操作
if (isEditOperation(method)) {
// 排除一些特殊的只读操作
if (isExcludedPath(requestURI)) {
return true;
}
log.warn("演示模式拦截: {} {}", method, requestURI);
throw new DemoModeException();
}
return true;
}
/**
* 判断是否为编辑操作
*/
private boolean isEditOperation(String method) {
return "POST".equalsIgnoreCase(method)
|| "PUT".equalsIgnoreCase(method)
|| "DELETE".equalsIgnoreCase(method)
|| "PATCH".equalsIgnoreCase(method);
}
/**
* 判断是否为排除的路径这些路径即使是POST等方法也不拦截
*/
private boolean isExcludedPath(String requestURI) {
// 排除登录相关
if (requestURI.contains("/auth/login") || requestURI.contains("/auth/logout")) {
return true;
}
// 排除导出操作虽然是POST但是只读操作
if (requestURI.contains("/export")) {
return true;
}
// 排除查询操作一些复杂查询使用POST
if (requestURI.contains("/list") || requestURI.contains("/query") || requestURI.contains("/search")) {
return true;
}
// 排除聊天接口(核心功能)
if (requestURI.contains("/chat/send") || requestURI.contains("/chat/upload")) {
return true;
}
// 排除文件上传预览等只读操作
if (requestURI.contains("/upload") || requestURI.contains("/preview")) {
return true;
}
// 排除支付回调
if (requestURI.contains("/pay/returnUrl") || requestURI.contains("/pay/notifyUrl")) {
return true;
}
// 排除重置密码(用户自己的操作)
return requestURI.contains("/auth/reset/password");
}
}

View File

@@ -2,7 +2,7 @@ package org.ruoyi.common.web.interceptor;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.map.MapUtil;
import com.alibaba.ttl.TransmittableThreadLocal;
import cn.hutool.core.util.ObjectUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
@@ -19,7 +19,6 @@ import java.util.Map;
/**
* web的调用时间统计拦截器
* dev环境有效
*
* @author Lion Li
* @since 3.3.0
@@ -27,13 +26,12 @@ import java.util.Map;
@Slf4j
public class PlusWebInvokeTimeInterceptor implements HandlerInterceptor {
private final TransmittableThreadLocal<StopWatch> invokeTimeTL = new TransmittableThreadLocal<>();
private final static ThreadLocal<StopWatch> KEY_CACHE = new ThreadLocal<>();
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String url = request.getMethod() + " " + request.getRequestURI();
String domainName = request.getServerName();
log.info("域名信息:{}", domainName);
// 打印请求参数
if (isJsonRequest(request)) {
String jsonParam = "";
@@ -41,32 +39,37 @@ public class PlusWebInvokeTimeInterceptor implements HandlerInterceptor {
BufferedReader reader = request.getReader();
jsonParam = IoUtil.read(reader);
}
log.debug("[PLUS]开始请求 => URL[{}],参数类型[json],参数:[{}]", url, jsonParam);
log.info("[PLUS]开始请求 => URL[{}],参数类型[json],参数:[{}]", url, jsonParam);
} else {
Map<String, String[]> parameterMap = request.getParameterMap();
if (MapUtil.isNotEmpty(parameterMap)) {
String parameters = JsonUtils.toJsonString(parameterMap);
log.debug("[PLUS]开始请求 => URL[{}],参数类型[param],参数:[{}]", url, parameters);
log.info("[PLUS]开始请求 => URL[{}],参数类型[param],参数:[{}]", url, parameters);
} else {
log.debug("[PLUS]开始请求 => URL[{}],无参数", url);
log.info("[PLUS]开始请求 => URL[{}],无参数", url);
}
}
StopWatch stopWatch = new StopWatch();
invokeTimeTL.set(stopWatch);
KEY_CACHE.set(stopWatch);
stopWatch.start();
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
log.debug("结束请求 => URL[{}]", request.getRequestURI());
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
StopWatch stopWatch = KEY_CACHE.get();
if (ObjectUtil.isNotNull(stopWatch)) {
stopWatch.stop();
log.info("[PLUS]结束请求 => URL[{}],耗时:[{}]毫秒", request.getMethod() + " " + request.getRequestURI(), stopWatch.getDuration().toMillis());
KEY_CACHE.remove();
}
}
/**
@@ -82,4 +85,5 @@ public class PlusWebInvokeTimeInterceptor implements HandlerInterceptor {
}
return false;
}
}

View File

@@ -1,88 +0,0 @@
package org.ruoyi.common.web.utils;
import cn.hutool.captcha.generator.CodeGenerator;
import cn.hutool.core.math.Calculator;
import cn.hutool.core.util.CharUtil;
import cn.hutool.core.util.RandomUtil;
import org.ruoyi.common.core.utils.StringUtils;
import java.io.Serial;
/**
* 无符号计算生成器
*
* @author Lion Li
*/
public class UnsignedMathGenerator implements CodeGenerator {
@Serial
private static final long serialVersionUID = -5514819971774091076L;
private static final String OPERATORS = "+-*";
/**
* 参与计算数字最大长度
*/
private final int numberLength;
/**
* 构造
*/
public UnsignedMathGenerator() {
this(2);
}
/**
* 构造
*
* @param numberLength 参与计算最大数字位数
*/
public UnsignedMathGenerator(int numberLength) {
this.numberLength = numberLength;
}
@Override
public String generate() {
final int limit = getLimit();
int a = RandomUtil.randomInt(limit);
int b = RandomUtil.randomInt(limit);
String max = Integer.toString(Math.max(a, b));
String min = Integer.toString(Math.min(a, b));
max = StringUtils.rightPad(max, this.numberLength, CharUtil.SPACE);
min = StringUtils.rightPad(min, this.numberLength, CharUtil.SPACE);
return max + RandomUtil.randomChar(OPERATORS) + min + '=';
}
@Override
public boolean verify(String code, String userInputCode) {
int result;
try {
result = Integer.parseInt(userInputCode);
} catch (NumberFormatException e) {
// 用户输入非数字
return false;
}
final int calculateResult = (int) Calculator.conversion(code);
return result == calculateResult;
}
/**
* 获取验证码长度
*
* @return 验证码长度
*/
public int getLength() {
return this.numberLength * 2 + 2;
}
/**
* 根据长度获取参与计算数字最大值
*
* @return 最大值
*/
private int getLimit() {
return Integer.parseInt("1" + StringUtils.repeat('0', this.numberLength));
}
}