1

I ran into a problem with accessing files within WebContent folder (in this case I need to access WEB-INF folder)

This is where I try to access WEB-INF folder.

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
    String dbPath = "/WEB-INF/musicDb.db";
    String xmlPath = "/WEB-INF/musicDb.xml";
    ServletContext context = null;
    context = getServletContext();  
    String test = context.getRealPath(xmlPath);

    File f = new File(test);
    if (f.exists()) {

    }
}

I have musicDb.xml ready in WEB-INF folder, however, by debugging, I always get this path instead

{my local project path}/.metadata/.plugins/org.eclipse.wst.server.core/tmp1/wtpwebapps/9321A1/WEB-INF/musicDb.xml

enter image description here

I suspect it has something to do with WebContent folder not being included in build process. This might be wrong.

Pretty much every tutorial/suggestion/article I've found so far point me to this approach using

getServletContext().getRealPath()

which doesn't seem to work in my case

Any help would be appreciated.

Thang

Thang Do
  • 316
  • 2
  • 16

1 Answers1

1

I suggest you move the file to /WEB-INF/classes or package it in a jar and place that jar in WEB-INF/lib. The load the file as a resource using any one of the getResourceAsSteam methods

See here: Best practices to store and access resource files in java web application and the correct answer here: Reading Web Application Resources

Community
  • 1
  • 1
chrisl08
  • 1,658
  • 1
  • 15
  • 24
  • but why would moving a file into a sub-folder make any difference? btw, I tried changing the path to /WEB-INF/ and check if file exists, it return true. (if that helps the case in any ways) – Thang Do Apr 13 '16 at 12:50
  • Ok, apparently, it does make a difference. I moved it into WEB-INF/lib folder and it works perfectly. I still wanna know why though – Thang Do Apr 13 '16 at 12:55
  • I don't remember for sure but the I think the servlet or jsp specification says that files inside WEB-INF are not visible/accessible to the web app – chrisl08 Apr 13 '16 at 13:03