Java 如何从 JAX-WS Web 服务中访问 ServletContext?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/261348/
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
How can I access the ServletContext from within a JAX-WS web service?
提问by Jens Bannmann
I want to share an object between my servlets and my webservice (JAX-WS) by storing it as a servlet context attribute. But how can I retrieve the servlet context from a web service?
我想通过将对象存储为 servlet 上下文属性来在我的 servlet 和我的 web 服务 (JAX-WS) 之间共享一个对象。但是如何从 Web 服务中检索 servlet 上下文呢?
采纳答案by Jens Bannmann
The servlet context is made available by JAX-WS via the message context, which can be retrieved using the web service context. Inserting the following member will cause JAX-WS to inject a reference to the web service context into your web service:
JAX-WS 通过消息上下文使 servlet 上下文可用,可以使用 Web 服务上下文检索消息上下文。插入以下成员将导致 JAX-WS 将对 Web 服务上下文的引用注入到您的 Web 服务中:
import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.handler.MessageContext;
...
@Resource
private WebServiceContext context;
Then, you can access the servlet context using:
然后,您可以使用以下方法访问 servlet 上下文:
ServletContext servletContext =
(ServletContext) context.getMessageContext().get(MessageContext.SERVLET_CONTEXT);
回答by Mirko Cianfarani
If you use Maven add this dependency!!!
如果您使用 Maven 添加此依赖项!!!
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.4</version>
<scope>provided</scope>
</dependency>
So I solved for avoid conflict error for get ServletContext INFO :
所以我解决了避免冲突错误获取 ServletContext INFO :
And in class method I use
在课堂方法中我使用
@WebService(endpointInterface = "choice.HelloWorld")
public class HelloWorldImpl implements HelloWorld {
@Resource
private WebServiceContext context;
public String sayHi(String text) {
HttpServletRequest request =(HttpServletRequest) context.getMessageContext().get(MessageContext.SERVLET_REQUEST);
System.out.println(request.getContextPath());