Writing a Servlet that checks to see if JSP's exist and forwards to another JSP if they aren't
Posted
by Omar Kooheji
on Stack Overflow
See other posts from Stack Overflow
or by Omar Kooheji
Published on 2010-03-24T10:53:18Z
Indexed on
2010/03/24
11:03 UTC
Read the original article
Hit count: 420
I've beeb tasked with writing a servlet that intercepts a call to and JSP in a specific directoy, check that the file exists and if it does just forwarding to that file, if if doesn't I'm to forward to a default JSP.
I've setup the web.xml as follows:
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>CustomJSPListener</servlet-name>
<servlet-class> ... CustomJSPListener</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
...
<servlet-mapping>
<servlet-name>CustomJSPListener</servlet-name>
<url-pattern>/custom/*</url-pattern>
</servlet-mapping>
And the doGet method of the servlet is as follows:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
logger.debug(String.format("Intercepted a request for an item in the custom directory [%s]",request.getRequestURL().toString()));
String requestUri = request.getRequestURI();
// Check that the file name contains a text string
if (requestUri.toLowerCase(Locale.UK).contains("someText")){
logger.debug(String.format("We are interested in this file [%s]",requestUri));
File file = new File(requestUri);
boolean fileExists = file.exists();
logger.debug(String.format("Checking to see if file [%s] exists [%s].",requestUri,fileExists));
// if the file exists just forward it to the file
if (fileExists){
getServletConfig().getServletContext().getRequestDispatcher(
requestUri).forward(request,response);
} else {
// Otherwise redirect to default.jsp
getServletConfig().getServletContext().getRequestDispatcher(
"/custom/default.jsp").forward(request,response);
}
} else {
// We aren't responsible for checking this file exists just pass it on to the requeseted jsp
getServletConfig().getServletContext().getRequestDispatcher(
requestUri).forward(request,response);
}
}
This seems to result in an error 500 from tomcat, I think this is because the servlet is redirecting to the same folder which is then being intercepted again by the servlet, resulting in an infinite loop.
Is there a better way to do this? I'm lead to believe that I could use filters to do this, but I don't know very much about them.
© Stack Overflow or respective owner