Search code examples
jspservletsrequestdispatcher

Make JSP accessible via RequestDispatcher#include only


The problem I am trying to solve is that I have a web project running on Tomcat 7 with mostly publicly accessible JSP pages, but also with a few JSP pages that are not meant to be publicly accessible. These "private" pages are used by various servlets like so:

response.setContentType(...);
request.getRequestDispatcher("/private/example.jsp").include(request, response);

I want the private JSP pages to be accessible by RequestDispatchaer#include(), but not if a client navigates to e.g. /private/example.jsp directly.

The way I am handling this now is I am setting a request attribute from the servlet:

request.setAttribute("okToAccess", true);

Then in the JSP page I check for that attribute, returning an empty document if it's not found. The two downsides to this are:

  1. The code is boiler-platey and annoying to write.
  2. Servlets dispatched via include can't modify response status/headers and so I can't e.g. send back a 403 or 404 from the JSP, I have to implement slightly more complex logic to let the calling servlet issue error responses instead.

My question is: Is there a cleaner way to block direct access to these "private" JSPs while still letting them be used with include()? Something I can put in web.xml or something?


Solution

  • Any content stored in WEB-INF won't be served directly by a web container. Place your private jsp files in that folder to force the request through a servlet.