I am using JAX-WS and I am having trouble retrieving the client information that is consuming a webservice. I've found out how to do it with JAX-RPC, and Apache Tomcat Axis, but not with JAX-WS. Does anyone have an idea about this?
Asked
Active
Viewed 4.4k times
4 Answers
49
What about this:
@WebService
public class MyService {
@Resource
WebServiceContext wsContext;
/**
* Web service operation
*/
@WebMethod
public String myMethod() {
MessageContext mc = wsContext.getMessageContext();
HttpServletRequest req = (HttpServletRequest)mc.get(MessageContext.SERVLET_REQUEST);
System.out.println("Client IP = " + req.getRemoteAddr());
}
}

Pascal Thivent
- 562,542
- 136
- 1,062
- 1,124
-
2I think I just missed the @Resource annotation. – monksy Oct 29 '09 at 05:13
-
To the best of my knowledge this is the best description of how to do this on the whole wide web. ;) Thank you, Pascal! – Zakum Mar 08 '12 at 15:49
-
I try same but mc size 22 and "request" is null. I can't understand why, have you any idea? – luffy Jun 30 '16 at 08:15
-
This works only in a servlet container but the OP asked for a JAX-WS implementation. Take a look at [this posting](https://stackoverflow.com/questions/12727989/jax-ws-getting-client-ip) for a good summary to retrieve the IP address in different environments. – Markus L Jul 26 '16 at 14:07
5
Or this:
@Path("terminal") public class terminal { @Context private javax.servlet.http.HttpServletRequest hsr; @GET @Path("get_ip") @Produces("text/plain") public String get_ip() { return ip = hsr.getRemoteAddr(); } }

Darren
- 68,902
- 24
- 138
- 144

Zayin Krige
- 3,229
- 1
- 35
- 34
3
Taking a huge and appreciated hint from Zayin and Darren's answer/edit, I tried this, and it works too.
@GET
@Produces(MediaType.TEXT_PLAIN)
@Path("ip")
public String sayIP(@Context HttpServletRequest req, @QueryParam("p1") String p1, ...) {
return req.getRemoteAddr();
}

Richard
- 59
- 4
0
public String getIp(@Context HttpServletRequest req) {
return req.getRemoteHost();
}

N K
- 3,217
- 5
- 23
- 38
-
@Context cannot be identified, and no import is suggested, what is this exactly ? – abdelrahman-sinno Nov 19 '15 at 14:53
-
@united-expression, https://jax-rs-spec.java.net/nonav/2.0/apidocs/javax/ws/rs/core/Context.html, https://jersey.java.net/documentation/latest/jaxrs-resources.html – N K Nov 20 '15 at 08:28