Search code examples
javaservlet-filtersforwardrequestdispatcher

How to determine from a filter which jsp was forwarded to from a RequestDispatcher.forward call?


I have a filter which processes requests in order to log them, so I can keep track of which session hit a page at what time with what request parameters. works great... posting from jsp to jsp, or making a direct call to a jsp. When a form is posted to a servlet which forwards that request to a new jsp, however, I am unable to see which jsp the request was forwarded to.

For example, suppose I have a login page, which posts to a LoginServlet, which then forwards the request to either index.jsp or index1.jsp. How can I determine from the request whether LoginServlet is returning index.jsp or index1.jsp?

This is in a java 1.5 environment using the 2.3 servlet specification.

public class PageLogFilter implements Filter {

    FilterConfig filterConfig = null;

    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
    }

    public void destroy() {
        this.filterConfig = null;
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        try {
            if (request instanceof HttpServletRequest) {
                HttpServletRequest req = (HttpServletRequest) request;
                HttpSession session = req.getSession(false);

                //For non-forwards, I can call req.getRequestURI() to determine which 
                //page was returned. For forwards, it returns me the URI of the  
                //servlet which processed the post. I'd like to also get the URI
                //of the jsp to which the request was forwarded by the servlet, for
                //example "index.jsp" or "index1.jsp"
            }
        } catch (Exception e {
            System.out.println("-- ERROR IN PageLogFilter: " + e.getLocalizedMessage());
        }

        chain.doFilter(request, response);
    }
}

Solution

  • If you are OK with performing an additional check then you can use attribute to set/get original request URI. In your LoginServlet set the attribute:

    //LoginServlet
    public void doFilter(...) {
          HttpServletRequest oReq = (HttpServletRequest)request;
          ..
          ...
          //save original request URI
          oReq.setAttribute("originalUri", oReq.getRequestURI());
    }
    

    and in your PageLogFilter check if originalUri attribute has value then consider this value as the request URI

    //PageLogFilter 
    public void doFilter(...) {
          HttpServletRequest req = (HttpServletRequest) request;
          if(req.getAttribute("originalUri") != null) {
              String strOriginalUri = (String) req.getAttribute("originalUri");
              //set it back to null
          req.setAttribute("originalUri", null);
          }
    }