Monday, September 08, 2008

TIP: JAX-WS Knowing Client IP (Requester IP)

To find out the client IP (the invoker) in JAX-WS Webservice one will need to use WebServiceContext

   1: import com.sun.xml.ws.transport.Headers;
   2: import javax.annotation.Resource;
   3: import javax.jws.WebMethod;
   4: import javax.jws.WebService;
   5: import javax.xml.ws.WebServiceContext;
   6: import javax.xml.ws.handler.MessageContext; 
   7:  
   8: @WebService
   9: public class XYZService 
  10: { 
  11:  
  12:     @Resource
  13:     WebServiceContext wsContext; 
  14:  
  15:     /**
  16:      * Web service operation
  17:      */
  18:     @WebMethod(operationName = "doOperation")
  19:     public String doOperation() 
  20:     {
  21:         MessageContext mc = wsContext.getMessageContext();
  22:         HttpServletRequest req = (HttpServletRequest)mc.get(MessageContext.SERVLET_REQUEST);
  23:         String clientIP = req.getRemoteAddr();
  24:         System.out.println("Client IP = " + clientIP); 
  25:         .....
  26:     } 
  27:  
  28: }

No comments: