Class loading in a web container is slightly more complex than a normal Java application. The normal configuration is that each web context (web application or WAR file) has its own classloader, which has the system classloader as its parent. Such a classloader hierarchy is normal in Java, however the servlet specification complicates the hierarchy because it requires the following:
- Classes contained within WEB-INF/lib or WEB-INF/classes have priority over classes on the parent classloader. This is the opposite of the normal behaviour of a Java 2 classloader.
- System classes such as java.lang.String are excluded from the webapp priority, and you may not replace them with classes in WEB-INF/lib or WEB-INF/classes. Unfortunately the specification does not clearly state what classes are System classes, and it is unclear if all javax classes should be treated as System classes.
- Server implementation classes like org.eclipse.jetty.server.Server should be hidden from the web application and should not be available in any classloader. Unfortunately the specification does not state what classes are Server classes, and it is unclear if common libraries like the Xerces parser should be treated as Implementation classes.
Configuring Webapp Classloading
Jetty provides configuration options to control the three webapp class loading issues identified above.
You can configure webapp classloading by several methods on the org.eclipse.jetty.webapp.WebAppContext. You can call these methods directly if you are working with the Jetty API, or you can inject methods from a context XML file if you are using the Context Provider. You CANNOT set these methods from a jetty-web.xml file, as it executes after the classloader configuration is set.
Controlling Webapp Classloader Priority
The method org.eclipse.jetty.webapp.WebAppContext.setParentLoaderPriority(boolean) allows control over the priority given to webapp classes over system classes. If you set it to false (the default), Jetty uses standard webapp classloading priority. However, if in this mode some classes that are dependencies of other classes are loaded from the parent classloader (due to settings of system classes below), so ambiguities might arise as both the webapp and system classloader versions can end up being loaded.
If set to true, then Jetty uses normal JavaSE classloading priority, and gives priority to the parent/system classloader. This avoids the issues of multiple versions of a class within a webapp, but the version the parent/system loader provides must be the right version for all webapps you configure in this way.
Setting System Classes
You can call the methods org.eclipse.jetty.webapp.WebAppContext.setSystemClasses(String Array) or org.eclipse.jetty.webapp.WebAppContext.addSystemClass(String) to allow fine control over which classes are considered System classes.
- A web application can see a System class.
- A WEB-INF class cannot replace a System class.
The default system classes are: