【问题标题】:How can I access the ServletContext from within a JAX-WS web service?如何从 JAX-WS Web 服务中访问 ServletContext?
【发布时间】:2010-09-20 15:41:23
【问题描述】:

我想通过将对象存储为 servlet 上下文属性来在我的 servlet 和我的 web 服务 (JAX-WS) 之间共享一个对象。但是如何从 Web 服务中检索 servlet 上下文?

【问题讨论】:

    标签: java web-services jax-ws


    【解决方案1】:

    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;
    

    然后,您可以使用以下方法访问 servlet 上下文:

    ServletContext servletContext =
        (ServletContext) context.getMessageContext().get(MessageContext.SERVLET_CONTEXT);
    

    【讨论】:

    • 如果您在 JBoss EAP 堆栈上尝试此操作,并且您首先使用 JBoss Developer Studio 中的新建项目向导创建一个 Seam 项目,您最终会得到一个 commons-annotations.jar 文件您的 WEB-INF/lib(其中包含 @Resource 注释)。最终结果是您的 WebServiceContext 没有被填充,并且您得到一个 NullPointerException。对我们来说,解决方案只是删除 commons-annotations.jar,以确保使用包含 JBoss 的版本。之后,事情就顺风顺水了。感谢您的出色回答,真正的救星!
    • 除了web服务上下文还有其他可注入资源吗?
    【解决方案2】:

    如果你使用 Maven 添加这个依赖!!!

            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>servlet-api</artifactId>
                <version>2.4</version>
                <scope>provided</scope>
            </dependency>
    

    所以我解决了 get ServletContext 的避免冲突错误 INFO :

    在类方法中我使用

    @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());
    

    【讨论】:

      猜你喜欢
      • 2010-10-10
      • 2011-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多