使用 Java Web 服务时如何访问 HttpServletRequest 对象 [英] How can I get access to the HttpServletRequest object when using Java Web Services
问题描述
我使用的是 Java 6、Tomcat 6 和 Metro.我使用 WebService 和 WebMethod 注释来公开我的 Web 服务.我想获取有关请求的信息.我尝试了以下代码,但 wsCtxt 始终为空.我必须采取什么步骤来不为 WebServiceContext 获取 null.
I'm using Java 6, Tomcat 6, and Metro. I use WebService and WebMethod annotations to expose my web service. I would like to obtain information about the request. I tried the following code, but wsCtxt is always null. What step must I take to not get null for the WebServiceContext.
换句话说:我如何执行以下行来获取 wsCtxt 的非空值?
In other words: how can I execute the following line to get a non-null value for wsCtxt?
MessageContext msgCtxt = wsCtxt.getMessageContext();
MessageContext msgCtxt = wsCtxt.getMessageContext();
@WebService
public class MyService{
@Resource
WebServiceContext wsCtxt;
@WebMethod
public void myWebMethod(){
MessageContext msgCtxt = wsCtxt.getMessageContext();
HttpServletRequest req = (HttpServletRequest)msgCtxt.get(MessageContext.SERVLET_REQUEST);
String clientIP = req.getRemoteAddr();
}
推荐答案
我建议您要么将变量从 wsCtxt 重命名为 wsContext,要么将 name 属性分配给 @Resource 注释.@Resource 上的 J2ee 教程 表明该变量用作查找的一部分.我在 Glassfish 注入不同类型的资源时使用资源注入遇到了同样的问题.
I recommend you either rename your variable from wsCtxt to wsContext or assign the name attribute to the @Resource annotation. The J2ee tutorial on @Resource indicates that the name of the variable is used as part of the lookup. I've encountered this same problem using resource injection in Glassfish injecting a different type of resource.
尽管您的正确名称可能不是 wsContext.我正在关注这个 java 提示.如果你喜欢变量名 wsCtxt,那么在变量声明中使用 name 属性:
Though your correct name may not be wsContext. I'm following this java tip. If you like the variable name wsCtxt, then use the name attribute in the variable declaration:
@Resource(name="wsContext") WebServiceContext wsCtxt;
这篇关于使用 Java Web 服务时如何访问 HttpServletRequest 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!