原因:
javax.serverlet.* 不兼容了
//import javax.servlet.*;
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
解决方案:
使用
jakarta.servlet.*
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
完整代码:
//springboot 3.4版本不兼容,需要用jakarta.servlet
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
//import javax.servlet.*;
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
@Component
public class LogFilter implements Filter {
private static final Logger log = LoggerFactory.getLogger(LogFilter.class);
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// 初始化过滤器
//System.out.println("过滤器初始化");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
//System.out.println("过滤器执行");
HttpServletRequest httpRequest = (HttpServletRequest) request;
// 记录请求开始时间
long startTime = System.currentTimeMillis();
// 记录请求地址
String requestURI = httpRequest.getRequestURI();
log.info("请求地址: " + requestURI);
// 记录远程地址
String remoteAddr = httpRequest.getRemoteAddr();
log.info("远程地址: " + remoteAddr);
// 记录请求日志
logRequest(httpRequest);
// 记录响应日志
logResponse((HttpServletResponse) response);
// 记录请求结束时间
long endTime = System.currentTimeMillis();
// 计算请求时间
long requestTime = endTime - startTime;
// 打印请求时间
log.info("请求时间: " + requestTime + "ms");
// 打印响应内容(如果需要)
// System.out.println("响应内容: " + responseWrapper.toString());
}
@Override
public void destroy() {
// 销毁过滤器
}
private void logRequest(HttpServletRequest request) {
log.info("请求方法: " + request.getMethod());
log.info("请求URL: " + request.getRequestURL());
log.info("请求头: " + request.getHeader("User-Agent"));
}
private void logResponse(ServletResponse response) {
HttpServletResponse httpResponse = (HttpServletResponse) response;
log.info("响应状态码: " + httpResponse.getStatus());
}
}
另外,application.properties配置启动日志过滤器
# 在application.properties中
spring.mvc.filters.logFilter.enabled=true