赞
踩
在Spring框架中,可以使用拦截器(Interceptor)来监听每个控制器(Controller)的请求,并记录请求者的IP地址。
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; public class IpLoggingInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // 在请求处理之前调用,可以记录IP地址等信息 String clientIpAddress = getClientIpAddress(request); System.out.println("IP地址:" + clientIpAddress); return true; } @Override 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) throws Exception { // 在整个请求完成后调用,可以进行一些清理工作 } private String getClientIpAddress(HttpServletRequest request) { String ipAddress = request.getHeader("X-Forwarded-For"); if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) { ipAddress = request.getHeader("Proxy-Client-IP"); } if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) { ipAddress = request.getHeader("WL-Proxy-Client-IP"); } if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) { ipAddress = request.getRemoteAddr(); } return ipAddress; } }
上述代码中的 IpLoggingInterceptor 类实现了 HandlerInterceptor 接口,其中的 preHandle 方法在请求处理之前被调用。在该方法中,我们获取了请求者的IP地址,并进行了简单的打印。可以根据需要,将这些信息记录到日志文件或其他存储设备中。
接下来,需要将这个拦截器注册到Spring应用中。在Spring Boot项目中,可以使用WebMvcConfigurer来注册拦截器。
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new IpLoggingInterceptor());
}
}
欢迎访问我的博客网站:https://www.yqiu.top
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。