【问题标题】:Passing attribute when redirecting from a filter to a JSP: Session vs Request从过滤器重定向到 JSP 时传递属性:会话与请求
【发布时间】:2012-03-19 11:37:49
【问题描述】:

在过滤器中,我试图将过期的会话发送回登录页面,其中包含用户必须登录的消息。我更喜欢将消息附加到请求对象,而不是会话对象,这样我就不必担心以后会删除消息。

当我在过滤器内使用时:

catch (NullPointerException exc)

{

    String message = "You must log in to access this site.";
    url += "/login.jsp";
    request.setAttribute("message", message);
    httpResponse.sendRedirect(url); 
}

登录页面不显示消息(消息为空)。但是,当我使用时:

session.setAttribute("message", message);

该消息在登录页面上显示得很好。

在 servlet 中,使用请求对象附加和显示消息没有问题。只有过滤器我才注意到这个困难。

为什么会发生这种情况,可以预防吗?如果在从过滤器重定向时必须使用会话,那么在 JSP 端擦除消息的最佳方法是什么?

【问题讨论】:

    标签: java jsp redirect request servlet-filters


    【解决方案1】:

    请改用RequestDispatcher

    我总是将任何询问 RequestDispatcher 与 SendRedirect 的人推荐给The Server Side 上的这篇文章。

    另见ServletRequest#getRequestDispatcher(java.lang.String)

    原来如此

     request.getRequestDispatcher("/login.jsp").forward(request, httpResponse);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-16
      • 2011-07-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多