Search code examples
javajspclassloader

What is the class loading process for a JSP?


I have a dynamic web project in eclipse. I have a file a.xml in my WEB-INF which is present on classpath. I have class named Test in my project.

I have following code in a JSP scriptlet -

<%@page import="com.kshitiz.Test"%>
<%
System.out.println(ClassLoader.getSystemClassLoader().getSystemResource("a.xml"));
System.out.println(this.getClass().getClassLoader().getSystemResource("a.xml"));
System.out.println(Test.class.getClassLoader().getResource("a.xml"));
%>

The output is -

null
null
C:/Users/kshitiz/eclipse/.metadata/.plugins/org.eclipse.wst.server.core/tmp1/wtpwebapps/test-project/WEB-INF/classes/a.xml

Apparently the system class loader and the JSP classloader are not able to find my file.

Could you explain the output? Is tomcat using a different classloader to load JSP? Why so? Why isn't system classloader able to find my file?

I already know that I can use following to get to my file -

getServletContext().getResourceAsStream("/WEB-INF/a.xml");

I'm interested in understanding the above scenario not the various methods to load that file.


Solution

  • Each deployed web application has its own class loader. That's what makes it possible to deploy two different webapps on the same container and to undeploy them, even if they use conflicting versions of the same library.

    The webapp's classloader is a child of the tomcat classloader, and its classpath contains the webapp's WEB-INF/classes directory, as well as every jar file in WEB-INF/lib. I don't know how you set your classpath, but you shouldn't set any classpath in eclipse, and the WEB-INF directory itself should definiitely not be in the classpath.

    The first and second line are basically equivalent, since they both use getSstemResource, which uses the system classloader. It's normal that they don't find your file, since the webapp's classpath is not in the system classpath.

    The third line should find the file if it's in the webapp's classpath, i.e. under WEB-INF/classes or in a jar under WEB-INF/lib.