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