April 2016 Posts

ServletContext.getRealPath Always Return Null on Apache Tomcat 8

I met a very strange error, that somehow works on Tomcat 7, but not working on Tomcat 8. I’m using ServletContext’s class getRealPath method, for getting my application’s absolute file path. Here is my code,

@PostConstruct
    private void init() {
        try {
            // get report location
            String reportLocation = servletContext.getRealPath("WEB-INF");           
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

On this code, i’m trying to get my report’s location and then processing it, by using servletContext.getRealPath. Which works well on my Apache Tomcat 7, but not well enough on Apache Tomcat 8. Somehow it always show null instead of the absolute path of my “WEB-INF” folder.

The workaround is actually quite simple, adding slash in front of “WEB-INF” make the problem disappear.

@PostConstruct
    private void init() {
        try {
            // get report location
            String reportLocation = servletContext.getRealPath("/WEB-INF");           
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }
Google+