Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access the ServletContext from within a JAX-WS web service?

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?

like image 807
Jens Bannmann Avatar asked Nov 04 '08 09:11

Jens Bannmann


People also ask

What is ServletContext interface?

Interface ServletContext. public interface ServletContext. Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file. There is one context per "web application" per Java Virtual Machine.

How do I test a JAX-WS web service?

A JAX-WS web service can be tested by using the Web Service Tester View displayed in Figure 7.1, “Web Service Test View”. The JAX-WS test is specified by: Selecting the JAX-WS combobox option. Entering the location of the WDSL file.

What is WebServiceContext?

A WebServiceContext makes it possible for a web service endpoint implementation class to access message context and security information relative to a request being served. Typically a WebServiceContext is injected into an endpoint implementation class using the Resource annotation.


2 Answers

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:

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:

ServletContext servletContext =     (ServletContext) context.getMessageContext().get(MessageContext.SERVLET_CONTEXT); 
like image 64
Jens Bannmann Avatar answered Oct 05 '22 03:10

Jens Bannmann


If you use Maven add this dependency!!!

        <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 :

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());
like image 21
Mirko Cianfarani Avatar answered Oct 05 '22 03:10

Mirko Cianfarani