views:

131

answers:

1

Hi,

I am trying to retrieve xml file (containing bean definition) in my Spring MVC project. If I have the xml file under WEB-INF directory, then what path should I put into FileSystemResource in my servlet to retrieve the xml?

i.e. BeanFactory factory = new XmlBeanFactory(new FileSystemResource("xml"));

Thanks

A: 

You shouldn't use FileSystemResource, you should use ServletContextResource:

new ServletContextResource(servletContext, "/myfile.xml");

Assuming, of course, that the servletContext is available to you.

If you really want to use FileSystemResource, then you need to ask the container where the directory is, and use that as a relative path, e.g.

String filePath = servletContext.getRealPath("/myfile.xml");
new FileSystemResource(filePath);

It it easier to let Spring do the work for you, though. Say you have a bean that needs this Resource. You can inject the resource path as a String, and let Spring convert it to the resource, e.g.

public class MyBean {

   private Resource myResource;

   public void setMyResource(Resource myResource) {
      this.myResource = myResource;
   }
}

and in your beans file:

<bean id="myBean" class="MyBean">
   <property name="myResource" value="/path/under/webapp/root/of/my/file.xml">
</bean>

Spring will convert the resource path into a ServletContextResource and pass that to your bean.

skaffman
Thanks!. In my servlet I have HttpServletRequest and HttpServletResponse, so I do "request.getRealPath()" instead of servletContext.getRealPath().
portoalet