java - 如何从过滤器确定从 RequestDispatcher.forward 调用转发到哪个 jsp?

标签 java servlet-filters forward requestdispatcher

我有一个过滤器,它处理请求以便记录它们,因此我可以跟踪哪个 session 在什么时间使用什么请求参数访问了一个页面。效果很好...从 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);
    }
}

最佳答案

如果您可以执行额外的检查,那么您可以使用属性来设置/获取原始请求 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);
      }
}

关于java - 如何从过滤器确定从 RequestDispatcher.forward 调用转发到哪个 jsp?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9036280/

相关文章:

c++ - 右值引用和文字

http - Spring过滤器看不到静态页面请求的状态码

java - 排除子目录的过滤器映射 url-pattern

java - 寻找 Java 正则表达式以匹配给定范围内的最后 2 位数字

java - JDialog标题的字体大小

java - 非 Spring MVC 应用程序中的 MultipartFilter

尽管包含 header ,但 C++ 成员访问不完整类型

java - 如何使用 Spring Security 允许转发到外部 URL

java - JRE 8 与 weblogic 10.3.6 (11g

Java合并多个replaceAll - 子字符串出现一次或多次