import javax.servlet.http.HttpServletRequest;
@GET
@Path("/yourservice")
@Produces("text/xml")
public String activate(@Context HttpServletRequest req,@Context SecurityContext context){
String ipAddressRequestCameFrom = requestContext.getRemoteAddr();
// header name is case insensitive
String xForwardedForIP = req.getHeader("X-Forwarded-For");
// if xForwardedForIP is populated use it, else return ipAddressRequestCameFrom
String ip = xForwardedForIP != null ? xForwardedForIP : ipAddressRequestCameFrom;
System.out.println("IP is "+ip);
// get the host name the client contacted. If the header `Host` is populated the `Host` header is automatically returned.
// An AWS ALB populated the Host header for you.
String hostNameRequestCameFrom = req.getServerName();
System.out.println("Host is "+hostNameRequestCameFrom);
//Also if security is enabled
Principal principal = context.getUserPrincipal();
String userName = principal.getName();
}
5条答案
按热度按时间qv7cva1a1#
将HttpServletRequest注入Rest服务,如下所示:
正如@ HemantNagpal提到的,如果负载平衡器将X-Forwarded-For头插入到请求中,您还可以检查X-Forwarded-For头以确定真实的的源。
您也可以取得客户端连络的服务器名称。这是DNS名称或Host信头中设定的值,其中OSI第7层负载平衡器可以填入。
1.示例:未填充标题
返回
2.示例:X-Forwarded-填充For和Host标头
返回
4xrmg8kj2#
我想你可以通过请求对象得到IP。
如果我没记错的话,
request.getRemoteAddr()
左右。wyyhbhjk3#
你可以这样做:
lfapxunr4#
假设您正在使用servlet创建“Web服务”,那么请求对象上相当简单的方法调用
.getRemoteAddr()
将为您提供调用者的IP地址。rn0zuynd5#