0

In my servlet:

protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 new Action();
}

In my Action class:

Action(){
    System.out.println("--> " + this.getClass().getResource("/").toString());
}

I have on result, this location:

--> file:/C:/Users/saad/Desktop/apache-tomcat-7.0.37/wtpwebapps/Serveur/WEB-INF/classes/

But i would like to get access to the root of my webApp like this: file:/C:/Users/saad/Desktop/apache-tomcat-7.0.37/wtpwebapps/Serveur/

I insist that the Action class does not inherit from the HttpServlet, so i can't use ServletContext.getResource("") .

How can i do this ?

Saad Lamarti
  • 300
  • 1
  • 5
  • 15
  • We'll, if you can't modify your `Action` class to get the request as a parameter (which I can't see any good reason not to...), you already have the path to your classes folder. You should be able to compute your path from it. Although, if it is for storing files inside the web application, as you suggest in my answer, I would recommend you to think otherwise. – NilsH Apr 18 '13 at 20:40
  • What exactly do you need this information for? Please don't say that you need this to write files to. – BalusC Apr 18 '13 at 21:36

1 Answers1

1

You can get the actual file system path of a web resource by using ServletContext.getRealPath() method.

ServletContext ctx = request.getServletContext();
String path = ctx.getRealPath("/");

And modify your Action to take either the request or the servlet context as a parameter:

public Action(ServletContext ctx) {
    System.out.println("--> " + ctx.getRealPath("/"));
}
NilsH
  • 13,705
  • 4
  • 41
  • 59
  • the problem that Action class does not inherit from HttpServlet, so i can't execute ServletContext.getRealPath() or ServletContext.getResource() – Saad Lamarti Apr 18 '13 at 20:12
  • +1. Gives exactly what the OP asked. Oops, or is it )) But +1 anyway – informatik01 Apr 18 '13 at 20:12
  • in my case, when I run the Action class, I would like to create a ZIP File in this location : /WebApp/accounts/ – Saad Lamarti Apr 18 '13 at 20:20
  • 1
    I won't recommend storing files the webapp folder like that (if it is inside the webapplication itself?). It would only work if the web application is exploded, and it could be overwritten on re-reployments. It would be better to store them somewhere completely outside your application server, and make the location configurable, either by a servlet/init parmater, or a property somewhere. – NilsH Apr 18 '13 at 20:23