Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing a Servlet that checks to see if JSP's exist and forwards to another JSP if they aren't

UPDATE:

To clarify a generic error catcher that catches 404's doesn't have enough granularity for me. I need to do this only if the jsp is in a particular directory and then only if the filename contains a certain string.

/UPDATE

I've been tasked with writing a servlet that intercepts a call to and JSP in a specific directory, check that the file exists and if it does just forwarding to that file, if it doesn't then I'm going to forward to a default JSP. I've setup the web.xml as follows:

<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>

And the doGet method of the servlet is as follows:

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);   
  }
 }

This seems to result in an error 500 from tomcat, I think this is because the servlet is redirecting to the same folder which is then being intercepted again by the servlet, resulting in an infinite loop. Is there a better way to do this? I'm lead to believe that I could use filters to do this, but I don't know very much about them.

like image 934
Omar Kooheji Avatar asked Mar 24 '10 10:03

Omar Kooheji


People also ask

How check if file exists in JSP?

RE: JSP - Checking if a file exists. getRealPath(""); File theFile = new File(path + "/images/07News/news/" + "news4image1. jpg"); out. print("File Exists: " + theFile.

Can a JSP be called using a servlet if so how?

Invoking a JSP Page from a Servlet. You can invoke a JSP page from a servlet through functionality of the standard javax. servlet.

Can we use both JSP and servlet?

The Model 2 architecture, as shown in Figure 3, integrates the use of both servlets and JSP pages. In this mode, JSP pages are used for the presentation layer, and servlets for processing tasks. The servlet acts as a controller responsible for processing requests and creating any beans needed by the JSP page.

How does JSP and servlet work together?

The JSP engine compiles the servlet into an executable class and forwards the original request to a servlet engine. A part of the web server called the servlet engine loads the Servlet class and executes it. During execution, the servlet produces an output in HTML format.


1 Answers

File file = new File(requestUri);

This is wrong. The java.io.File knows nothing about the webapp context it is running in. The file path will be relative to the current working directory, which is dependent on the way how you start the appserver. It may for example be relative to C:/Tomcat/bin rather than the webapp root as you seem to expect. You don't want to have this.

Use ServletContext#getRealPath() to translate a relative web path to an absolute disk file system path. The ServletContext is available in the servlet by the inherited getServletContext() method. Thus, following should point out the right file:

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

if (file.exists()) { 
    // ...
}

Or, if the target container doesn't expand the WAR on physical disk file system but instead in memory, then you'd better use ServletContext#getResource():

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

if (url != null) { 
    // ...
}
like image 60
BalusC Avatar answered Oct 13 '22 03:10

BalusC