2

我有一个过滤器,它处理请求以记录它们,所以我可以跟踪哪个会话在什么时间用什么请求参数访问了一个页面。效果很好...从 jsp 发布到 jsp,或直接调用 jsp。但是,当将表单发布到将请求转发到新 jsp 的 servlet 时,我无法看到请求被转发到了哪个 jsp。

例如,假设我有一个登录页面,它发布到 LoginServlet,然后将请求转发到 index.jsp 或 index1.jsp。如何从请求中确定 LoginServlet 是返回 index.jsp 还是 index1.jsp?

这是在使用 2.3 servlet 规范的 java 1.5 环境中。

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

2 回答 2

2

如果您可以执行附加检查,那么您可以使用属性来设置/获取原始请求 URI。在您的LoginServlet设置中的属性:

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

并在您PageLogFilter检查 originalUri 属性是否具有值时,将此值视为请求 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);
      }
}
于 2012-01-27T16:18:56.910 回答
0

虽然它不会帮助解决您当前的问题,但 Servlet 2.4 在调度程序上添加了更详细的控制,这正是您想要的。

有了它,您可以配置过滤器以添加以下调度程序元素,这将导致过滤器也适用于转发。

<filter-mapping>
       <filter-name>PageLogFilter</filter-name>
       <url-pattern>/*</url-pattern>
       <dispatcher>FORWARD</dispatcher>
</filter-mapping>

下面的文章更详细地解释了它

http://www.ibm.com/developerworks/java/library/j-tomcat2/

于 2012-01-27T16:30:39.360 回答