How to get to WebContent folder from web service method

I want to get a file in the WebContent folder from a method in a web service in the same project. For example:

@WebMethod
public String test() {
     File configFile = new File("config.xml");
     return configFile.getAbsolutePath();
}

      

It returns "/usr/share/glassfish3/glassfish/domains/domain1/config/config.xml". I want to navigate to a file in the "/ usr / share / glassfish3 / glassfish / domains / domain1 / applications / my_project_name /" directory. How can I get to it?

+3


source to share


2 answers


Add the following parameter to your web service class:

@Context
ServletContext context;

      

Then, if your file config.xml

is in a folder WebContent

, you can get its absolute path by calling the method context.getRealPath(String)

. Using your example code, this would be:



@WebMethod
public String test() {
     File configFile = new File(context.getRealPath("config.xml"));
     return configFile.getAbsolutePath();
}

      

Or directly, without going through the File object:

@WebMethod
public String test() {
     return context.getRealPath("config.xml");
}

      

+1


source


From your code, I understand that your web service is JAXWS.

In jaxws you can get HttpServletRequest, HttpServletResponse, ServletContext,

Have a private variable in your webservice class and annotate it this way

@Resource
private WebServiceContext context;

      

And then in your method you can get the ServletContext like this

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

      



From servletContext you can get the path.

Suppose you need to get HttpServletRequest, you can get it this way

HttpServletRequest request =
            (HttpServletRequest) context.getMessageContext().get(MessageContext.SERVLET_REQUEST);

      

and you can get the context path to your application like

request.getContextPath() ;

      

0


source







All Articles