要获取请求的 IP 和路由,可以使用 Spring AOP 结合 HttpServletRequest 对象来实现。

首先,创建一个切面类,使用 @Aspect 注解标记该类为切面类。然后使用 @Around 注解标记一个方法作为切点,并在该方法中获取 HttpServletRequest 对象。

@Aspect
@Component
public class RequestAspect {

    @Around("execution(* com.example.controller.*.*(..)) ")
    public Object logRequest(ProceedingJoinPoint joinPoint) throws Throwable {
        // 获取 HttpServletRequest 对象
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        // 获取请求的 IP
        String ip = request.getRemoteAddr();

        // 获取请求的路由
        String route = request.getRequestURI();

        // 打印请求的 IP 和路由
        System.out.println('Request IP: ' + ip);
        System.out.println('Request Route: ' + route);

        // 继续执行原方法
        Object result = joinPoint.proceed();

        return result;
    }
}

在切面类中,使用 @Around 注解来指定要切入的方法,这里使用了 execution 表达式来匹配所有 Controller 类的方法。

在切点方法中,通过 RequestContextHolder.getRequestAttributes() 方法获取 ServletRequestAttributes 对象,再通过 getRequest() 方法获取 HttpServletRequest 对象。

然后,可以使用 getRemoteAddr() 方法获取请求的 IP 地址,使用 getRequestURI() 方法获取请求的路由。

最后,可以根据需求进行处理,比如打印请求的 IP 和路由。

注意,还需要将切面类注册到 Spring 容器中,可以使用 @Component 注解或 @Configuration 注解。

这样,在每次请求进入 Controller 方法之前,切面类的切点方法会被执行,可以获取请求的 IP 和路由进行处理。


原文地址: https://www.cveoy.top/t/topic/pJc3 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录