views:

571

answers:

5

I need to get real path for file in my WebContent directory, so that framework that I use can access that file. It only takes String file as attribute, so I need to get the real path to this file in WebContent directory.

I use Spring Framework, so solution should be possible to make in Spring.

A: 

In situations like these I tend to extract the content I need as a resource (MyClass.getClass().getResourceAsStream()), write it as a file to a temporary location and use this file for the other call.

This way I don't have to bother with content that is only contained in jars or is located somewhere depending on the web container I'm currently using.

tangens
@tangens - I don't think he wants to read a resource from the webapps classloader; e.g. a file in a JAR in a WAR. He just wants to get the pathname of a file within the web container.
Stephen C
+2  A: 

If you need this in a servlet then use getServletContext().getRealPath("/filepathInContext")!

Shyam
thanx for answer, but I user Spring, so I need it in @Controller
newbie
A: 

Include the request as a parameter. Spring will then pass the request object when it calls the mapped method

@RequestMapping .....
public String myMethod(HttpServletRequest request) {
   String realPath = request.getRealPath("/somefile.txt");
   ...
objects
A: 

You could use the Spring Resource interface (and especially the ServletContextResource): http://static.springsource.org/spring/docs/current/javadoc-api/org/springframework/core/io/Resource.html

Thomas Vanstals
A: 

@Shyam implement ServletContexAware to get hold of it in a Controller

OrangeDog