UPDATE:寫檢查,看看是否JSP的存在,並轉發到另一個JSP,如果他們是一個Servlet不
要澄清一個一般性錯誤捕手,捕捉404的沒有足夠的粒度對我來說。只有當jsp位於特定的目錄中,並且僅當文件名包含某個字符串時,我才需要執行此操作。
/UPDATE
我一直在負責編寫攔截在一個特定的目錄和JSP調用一個servlet,檢查文件是否存在,如果它不只是轉發該文件,如果它那麼我不會轉發到默認的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>
並且servlet的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);
}
}
這似乎從Tomcat導致錯誤500,我想這是因爲servlet重定向到同一個文件夾,然後被servlet再次攔截,導致無限循環。 有沒有更好的方法來做到這一點?我導致我相信我可以使用過濾器來做到這一點,但我對它們不甚瞭解。
謝謝,我會試試這個。 – 2010-03-24 11:40:24
這仍然無法阻止它進入無限循環的問題。 – 2010-03-24 11:45:35
將' REQUEST '添加到''。順便說一句:過濾器確實是一個更好的地方,你可以在'doFilter()'中放入相同的代碼,你只需要向下施放請求和響應。 –
BalusC
2010-03-24 12:17:02