Thang Do
Thang Do

Reputation: 316

Unable to access file in WEB-INF folder from servlet

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

Upvotes: 1

Views: 2471

Answers (1)

chrisl08
chrisl08

Reputation: 1658

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

Upvotes: 1

Related Questions