我曾经使用HttpServletRequest.getRemoteAddr()获取客户端IP。
我想知道如何通过ServerWebExchange获取它。
我的最佳猜测是:
serverWebExchange.getRequest().getRemoteAddress().getAddress().getHostAddress();
这正确吗?
我曾经使用HttpServletRequest.getRemoteAddr()获取客户端IP。
我想知道如何通过ServerWebExchange获取它。
我的最佳猜测是:
serverWebExchange.getRequest().getRemoteAddress().getAddress().getHostAddress();
这正确吗?
你可以使用org.springframework.http.server.reactive.ServerHttpRequest
。
String remoteAddress = serverHttpRequest.getRemoteAddress().getAddress().getHostAddress();
.reactive.ServerHttpRequest
代表着反应式服务器端HTTP请求。可在以下链接中查阅相关详细信息:https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/http/server/reactive/ServerHttpRequest.html。是的,这是实现该目标的正确方法。 请注意,如果您想支持Forwarded或X-Forwarded-* HTTP请求头,这是需要在服务器配置级别进行配置的。
您还可以将org.springframework.http.server.ServerHttpRequest
添加为参数到@RerquestMapping
注解方法中,并从中获取IP地址:
@GetMapping("/myPath")
public void someMethod(ServerHttpRequest request) {
System.out.println(request.getRemoteAddress().getAddress().getHostAddress();)
}