【问题标题】:Conditional use of RequestDispatcher to send the same Java object across multiple JSP pages有条件地使用 RequestDispatcher 跨多个 JSP 页面发送同一个 Java 对象
【发布时间】:2014-12-06 17:49:31
【问题描述】:

请多多包涵,因为我对 JSP 很陌生。我提前感谢您的帮助;非常感谢。

背景

我正在尝试构建一个 Web 应用程序,它可以在整个用户的登录会话中“记住”某些 java 对象。目前,我有一个 servlet,它使用 RequestDispatcher 通过其 doPost 方法将对象发送到 JSP 页面。

这里是 servlet 的 doPost:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws     ServletException, IOException {

    String strBook = "Test Book";

    // Send strBook to the next jsp page for rendering
    request.setAttribute("book", strBook);
    RequestDispatcher dispatcher = request.getRequestDispatcher("sample.jsp");
    dispatcher.include(request, response);

}

sample.jsp 获取 strBook 对象,并对其进行处理。 sample.jsp 的主体如下所示:

<body>

<% 
    // Obtain strBook for rendering on current page
    String strBook = (String) request.getAttribute("book"); 

    /*
      // TODO: A way to conditionally call code below, when form is submitted 
      // in order for sample2.jsp to have strBook object.

      RequestDispatcher dispatcher = request.getRequestDispatcher("sample2.jsp");
      dispatcher.include(request, response);
    */

%>


<h1> Book: </h1>
<p> <%=strBook%> </p>

<form action="sample2.jsp"  method="post">
    <input type="submit" id="buttonSubmit" name="buttonSubmit" value="Buy"/>
</form>

</body>

问题

如何从 sample.jsp 中获取 strBook 对象,并将其发送到 sample2.jsp当点击提交按钮时(这样 strBook 对象可以在 sample2.jsp 中使用)?

目前sample2.jsp的body是这样的,里面的strBook为null:

<body>

<% 
    // Obtain strBook for rendering on current page
    String strBook = (String) request.getAttribute("book"); 
%>


<h1> Book: </h1>
<p> <%="SAMPLE 2 RESULT " + strBook%> </p>

</body>

【问题讨论】:

    标签: java jsp jakarta-ee servlets requestdispatcher


    【解决方案1】:

    你可以把它作为参数传递给下一个jsp。

    Sample1.jsp

    <form action="sample2.jsp"  method="post">
       <input type="submit" id="buttonSubmit" name="buttonSubmit" value="Buy"/>
       <input type="hidden" name="book" value="<%=strBook%>"/>
    </form>
    

    Sample2.jsp

     <% 
    // Obtain strBook for rendering on current page
    String strBook = (String) request.getParameter("book"); 
     %>
    
    
    <h1> Book: </h1>
    <p> <%="SAMPLE 2 RESULT " + strBook%> </p>
    

    【讨论】:

    • 感谢您的回复 Sas - 我很感激。在我的实际应用程序中,strBook 实际上是一个更复杂的对象(“Book”对象不是字符串),因此在 sample1.jsp 中,代码 value="" 将无法传输 Book 对象.我只是在寻找一种更通用的方法来将任何类型的对象从 jsp 发送到 servlet,反之亦然,我想我刚刚找到了一种使用“会话”功能的方法。
    猜你喜欢
    • 1970-01-01
    • 2019-03-21
    • 1970-01-01
    • 1970-01-01
    • 2011-08-25
    • 2015-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多