Can I serve JSPs from inside a JAR in lib, or is there a workaround?

waxwing picture waxwing · Feb 16, 2011 · Viewed 29.8k times · Source

I have a web application deployed as a WAR file in Tomcat 7. The application is build as a multi-module project:

  • core - packaged as JAR, contains most of the backend code
  • core-api - packaged as JAR, contains interfaces toward core
  • webapp - packaged as WAR, contains frontend code and depends on core
  • customer-extensions - optional module, packaged as JAR

Normally, we can put our JSP files in the webapp project, and reference them relative to the context:

/WEB-INF/jsp/someMagicalPage.jsp

The question is what we do about JSP files that are specific to the customer-extensions project, that should not always be included in the WAR. Unfortunately, I cannot refer to JSPs inside JAR files, it appears. Attempting classpath:jsp/customerMagicalPage.jsp results in a file not found in the JspServlet, since it uses ServletContext.getResource().

Traditionally, we "solved" this having maven unpack the customer-extensions JAR, locate the JSPs, and put them in the WAR when building it. But an ideal situation is where you just drop a JAR in the exploded WAR in Tomcat and the extension is discovered - which works for everything but the JSPs.

Is there anyway to solve this? A standard way, a Tomcat-specific way, a hack, or a workaround? For example, I've been thinking of unpacking the JSPs on application startup...

Answer

scarba05 picture scarba05 · Jun 16, 2012

Servlet 3.0 which Tomcat 7 supports includes the ability to package jsps into a jar.

You need to:

  • place your jsps in META-INF/resources directory of your jar
  • optionally include a web-fragment.xml in the META-INF directory of your jar
  • place the jar in WEB-INF/lib directory of your war

You should then be able to reference your jsps in your context. For example if you have a jsp META-INF/resources/test.jsp you should be able reference this at the root of your context as test.jsp