Tom Tucker
Tom Tucker

Reputation: 11896

Accessing Files From Web Document Root

I'm using Spring MVC 3.0 and Tomcat.

I have a bean that has a property whose value should be a path rooted from the web document root. For example, I would specify its value in a Spring configuration file as following.

<bean id="myBean" class="com.stackoverflow.Bean">
    <property name="path" value="/WEB-INF/foo.xml" />
</bean>

Where do I take this value to so that I can read the file? Does Spring/Spring MVC provide a transparent way to access resources within the document root?

Upvotes: 1

Views: 2970

Answers (3)

Brian Matthews
Brian Matthews

Reputation: 8596

If you don't mind using Spring classes directly in you POJO you could inject the path property as a Resource object. Spring will handle the conversion from java.lang.String to org.springframework.core.io.Resource for you. So it should work with the XML that you posted in your question.

package com.stackoverflow;

import org.springframework.core.io.Resource;

public class Bean {

    private Resource resource;

    public void setPath(final Resource resource) {
        this.resource = resource;
    }

    public void doSomething() {
         // Use resource.getFile() to get java.io.File
         // or resource.getInputStream() to get java.io.InputStream
    }
}

See the Spring Reference for more information on resources.

Upvotes: 2

Mihir Mathuria
Mihir Mathuria

Reputation: 6539

In order to get the real path to the resource you will need to have access to ServletContext

One way to achieve this will be to make your com.stackoverflow.Bean implement ServletContextAware interface. Upon restart, the server should hand over an instance of ServletContext to this bean (you will have to include the following code)

private ServletContext ctx;
public void setServletContext(ServletContext servletContext) {
    ctx = servletContext;
}

Finally, use ctx.getRealPath(path) to get the real path to the resource.

Upvotes: 5

duffymo
duffymo

Reputation: 308743

I'll assume you have a good reason for NOT putting foo.xml in WEB-INF/classes. It's a simple matter of loading a resource from the CLASSPATH for that directory.

Perhaps a Resource can be had using the "file:WEB-INF/foo.xml" designation would work.

Upvotes: -1

Related Questions