суббота, 31 июля 2010 г.

How to get request ip address from webservice method

One of common tasks is to check some environment variables, such as request ip. In some cases service is so simple, what this will not become "anti-pattern".

So, if you want this functionality, watch this example:
@WebService
public class Hello {

  @Resource
  WebServiceContext wsc;

  @WebMethod
  public String showMyIp() {
    return ((HttpServletRequest) wsc.getMessageContext().get(
            MessageContext.SERVLET_REQUEST)).getRemoteAddr();
  }
}


One important thing: this method may not work if your web service is EJB. In this case web service context is completely different object and doesn't contain HttpServletRequest reference.