UPDATE:
To clarify a generic error catcher that catches 404's doesn't have enough granularity for me. I need to do this only if the jsp is in a particular directory and then only if the filename contains a certain string.
/UPDATE
I've been tasked with writing a servlet that intercepts a call to and JSP in a specific directory, check that the file exists and if it does just forwarding to that file, if it doesn't then I'm going 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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…