开发者

Accessing Files From Web Document Root

开发者 https://www.devze.com 2023-01-25 01:02 出处:网络
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 configuratio

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" 开发者_C百科/>
</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?


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消