UPDATE:
Чтобы прояснить общий улавливатель ошибок, который ловит 404, мне не хватает детализации. Мне нужно делать это только в том случае, если jsp находится в определенном каталоге, и только в том случае, если имя файла содержит определенную строку.
/ UPDATE
Мне было поручено написать сервлет, который перехватывает вызов и JSP в определенном каталоге, проверить, существует ли файл, и если он просто переадресовывает этот файл, если нет, я собираюсь переслать JSP по умолчанию.
Я настроил web.xml следующим образом:
<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>
И метод doGet сервлета выглядит следующим образом:
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);
}
}
Кажется, это приводит к ошибке 500 от tomcat, я думаю, это потому, что сервлет перенаправляет в ту же папку, которая затем снова перехватывается сервлетом, что приводит к бесконечному циклу.
Есть лучший способ сделать это? Я склонен полагать, что я мог бы использовать фильтры для этого, но я не очень много знаю о них.