编写一个Servlet来检查JSP是否存在,如果不存在则转发给另一个JSP

Oma*_*eji 6 java jsp servlets servlet-filters

更新:

澄清捕获404的一般错误捕获器对我来说没有足够的粒度.我只有在jsp位于特定目录中时才需要这样做,并且只有当文件名包含某个字符串时才需要这样做.

/ UPDATE

我的任务是编写一个servlet来拦截对特定目录中的JSP和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>
Run Code Online (Sandbox Code Playgroud)

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);   
  }
 }
Run Code Online (Sandbox Code Playgroud)

这似乎导致tomcat出现错误500,我认为这是因为servlet重定向到同一个文件夹,然后由servlet再次拦截,导致无限循环.有一个更好的方法吗?我认为我可以使用过滤器来做到这一点,但我不太了解它们.

Bal*_*usC 8

File file = new File(requestUri);
Run Code Online (Sandbox Code Playgroud)

这是错的.该java.io.File知道什么关于它在运行webapp的背景下,该文件的路径将是相对于当前工作目录,你如何启动应用程序服务器是依赖的方式.例如,它可能C:/Tomcat/bin与您期望的相对而不是webapp根目录相关.你不想拥有这个.

ServletContext#getRealPath()一个相对路径网络转化为一个绝对的磁盘文件系统的路径.该ServletContext是由继承servlet的可用getServletContext()方法.因此,以下应指出正确的文件:

String absoluteFilePath = getServletContext().getRealPath(requestUri);
File file = new File(absoluteFilePath);

if (file.exists()) { 
    // ...
}
Run Code Online (Sandbox Code Playgroud)

或者,如果目标容器没有在物理磁盘文件系统上扩展WAR,而是在内存中扩展WAR,那么最好使用ServletContext#getResource():

URL url = getServletContext().getResource(requestUri);

if (url != null) { 
    // ...
}
Run Code Online (Sandbox Code Playgroud)