Svetoslav Marinov
Svetoslav Marinov

Reputation: 492

How to reach the WebContent folder from a web service method

I want to reach a file in 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 get to a file in the directory "/usr/share/glassfish3/glassfish/domains/domain1/applications/my_project_name/" folder. How can I get to it?

Upvotes: 4

Views: 3884

Answers (3)

Ahmed Akhtar
Ahmed Akhtar

Reputation: 1463

The best way to do this that I use is:

Thread.currentThread().getContextClassLoader().getResource("myFile.txt").getPath()

This gives the path of any file myFile.txt placed in /WEB-INF/classes/ directory inside the WebContent folder of the WebApp.

In Eclipse JEE environment you need to keep the file myFile.txt, that you may want to read within the Web Service, in the src folder for it to be transported to the /WEB-INF/classes/ folder by the deployer.

Upvotes: 2

Marco Lackovic
Marco Lackovic

Reputation: 6487

Add the following parameter to your web service class:

@Context
ServletContext context;

Then, supposing your config.xml file is in the WebContent folder, you can get its absolute path by invoking the method context.getRealPath(String). Using your example code it would be:

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

Or directly, without passing by a File object:

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

Upvotes: 1

Arun
Arun

Reputation: 3680

From your code, I understand that yours is an JAXWS webservice.

In jaxws, you can get the HttpServletRequest, HttpServletResponse, ServletContext,

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

@Resource
private WebServiceContext context;

And then in your method, you can get the ServletContext this way

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

From servletContext, you can get the path.

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

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

and you can get the context path of your app like

request.getContextPath() ;

Upvotes: 1

Related Questions