更新:
为了澄清捕获 404 的通用错误捕获器对我来说没有足够的粒度。仅当 jsp 位于特定目录中并且文件名包含特定字符串时,我才需要执行此操作。
/更新
我的任务是编写一个 servlet,拦截对特定目录中的 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>
而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 拦截,从而导致无限循环。 有一个更好的方法吗?我被引导相信我可以使用过滤器来做到这一点,但我对它们知之甚少。
最佳答案
File file = new File(requestUri);
这是错误的。 java.io.File
对它运行的 webapp 上下文一无所知。文件路径将相对于当前工作目录,这取决于如何您启动应用程序服务器。例如,它可能与 C:/Tomcat/bin
相关,而不是您所期望的 webapp 根目录。你不想拥有这个。
使用ServletContext#getRealPath()
将相对 Web 路径转换为绝对磁盘文件系统路径。 ServletContext
由继承的 getServletContext()
在 servlet 中可用。方法。因此,以下应该指出正确的文件:
String absoluteFilePath = getServletContext().getRealPath(requestUri);
File file = new File(absoluteFilePath);
if (file.exists()) {
// ...
}
或者,如果目标容器不在物理磁盘文件系统上而是在内存中扩展 WAR,那么您最好使用 ServletContext#getResource()
:
URL url = getServletContext().getResource(requestUri);
if (url != null) {
// ...
}
关于java - 编写一个 Servlet 检查 JSP 是否存在,如果不存在则转发给另一个 JSP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2506994/