Link to home
Start Free TrialLog in
Avatar of jdestremps
jdestremps

asked on

Programmatic out-of-context includes in JSP (for shared code)

I want to be able to share global resources across web sites.  For example, foo.jsp which performs xyz, needs to be able to be included in jsp from several sites which use foo.jsp.  Copying the global resources N times is NOT an option for obvious reasons.

I know about:

<jsp:include page="/foofiles/foo.jsp"/>

and I've read about:
-------
ServletContext testContext = getServletContext();

RequestDispatcher disp = testContext.getRequestDispatcher( "/foofiles/foo.jsp" );

disp.include( request, response );
--------

but it seems that the included resources have to PHYSICALLY reside WITHIN the context of the application you're running.

I've even tried doing the above Java code from within <% jsp %> tags however this produced no output and I don't think the context was being found.  Either that or the found JSP was not being processed and output.  Do included resources create their own output streams???

I've experimented with <context> tags in Tomcat, but to no avail.  Does anyone know how I can include (programmitically using passed or read-in data) files from a cross-context resource.  If this is a limitation of JSP, I consider it a SEVERE limitation.  Doing this is ASP or JHTML on ATG Dynamo is easy and simple -- just create a virtual directory pointing TO anywhere and access it FROM anywhere.  JSP/J2EE seems to make this a burden (or impossible?!?).

Thanks for your responses and solutions.
Avatar of bobbit31
bobbit31
Flag of United States of America image

>  <context> tags in Tomcat

so i'm assuming you tried setting crossContext="true"  in your context?
Avatar of kennethxu
kennethxu

>> but it seems that the included resources have to PHYSICALLY reside WITHIN the context of the application you're running.
correct by default.
there are 2 solutions to your problem:

option 1 works when all your contexts are on same servlet cntainer. say you have "foo.jsp" under context "foofiles", and "bah.jsp" in context "bahapp" need to include "foo.jsp". set crossContext="true" for both foofiles and bahapp, then use:

ServletContext fooContext= ServletContext.getContext( "foofiles" );
RequestDispatcher disp = fooContext.getRequestDispatcher( /foo.jsp" );
disp.include( request, response );
ASKER CERTIFIED SOLUTION
Avatar of kennethxu
kennethxu

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
option 2 works cross servers, need to use JSTL <c:import> tag:
http://java.sun.com/products/jsp/jstl/
and here is the tutorial:
http://www.onjava.com/pub/a/pub/a/onjava/2002/05/08/jstl.html?page=2
let me know if you have further enquires.
Avatar of jdestremps

ASKER

Thanks Kenneth.  A very timely and accurate response.  I tried it out and it works!  Awesome.
glad to know and my pleasure to help :)