How to get IP from ContainerRequestContext JERSEY

2019-04-29 01:24发布

问题:

My code is this:

public void filter(ContainerRequestContext request) throws IOException 
  {
   // can I get Ip from request?????

 }

How can I get ip address from request?

回答1:

According to this JIRA ticket, based on this discussion, they added support for injecting the HttpServletRequest into your filter, a code snippet from the above JIRA looks like this:

public class MyRequestFilter implements ContainerRequestFilter {

  @Context
  private HttpServletRequest servletRequest;

You can then use the HttpServletRequest API to get the Remote IP, see the full Javadoc here, excerpt:

getRemoteAddr

java.lang.String getRemoteAddr()

Returns the Internet Protocol (IP) address of the client or last proxy that sent the request. For HTTP servlets, same as the value of the CGI variable REMOTE_ADDR.

Returns:

a String containing the IP address of the client that sent the request