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