How to get the client's ip address in jax rs and ws

In this tutorial I'll not teach how to create jax-rs nor jax-ws web service but rather will show how we can get the client's or the caller's ip address who invoke the service.

In jax-rs:
//inject
@Context
private HttpServletRequest httpServletRequest;

public void serviceMethod() {
 //get the ip
 log.debug("IP=" + httpServletRequest.getRemoteAddr());
}
In jax-ws, we inject a different resource but it's almost the same.
@Resource
private WebServiceContext wsContext;

public void serviceMethod() { 
 MessageContext mc = wsContext.getMessageContext();
 HttpServletRequest req = (HttpServletRequest) mc.get(MessageContext.SERVLET_REQUEST);

 log.debug("IP=" + req.getRemoteAddr());
}

If you need help building jax-rs service here's how I'm doing things: http://czetsuya-tech.blogspot.com/2014/11/rest-testing-with-arquillian-in-jboss.html.
How to get the client's ip address in jax rs and ws How to get the client's ip address in jax rs and ws Reviewed by Edward Legaspi on Monday, January 26, 2015 Rating: 5

No comments:

Powered by Blogger.