Java 获取 Web 服务的客户端 IP 地址
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1641594/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting the IP Address Of A client For a webservice
提问by monksy
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?
我正在使用 JAX-WS,但在检索使用 Web 服务的客户端信息时遇到问题。我已经找到了如何使用 JAX-RPC 和 Apache Tomcat Axis 来做到这一点,但没有使用 JAX-WS。有没有人有这个想法?
采纳答案by Pascal Thivent
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());
}
}
回答by Zayin Krige
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(); } }
回答by Richard
Taking a huge and appreciated hint from Zayin and Darren's answer/edit, I tried this, and it works too.
从 Zayin 和 Darren 的回答/编辑中得到了一个巨大而值得赞赏的提示,我尝试了这个,它也有效。
@GET
@Produces(MediaType.TEXT_PLAIN)
@Path("ip")
public String sayIP(@Context HttpServletRequest req, @QueryParam("p1") String p1, ...) {
return req.getRemoteAddr();
}
回答by N K
public String getIp(@Context HttpServletRequest req) {
return req.getRemoteHost();
}