Search code examples
javajspjakarta-eeservletsrequestdispatcher

Conditional use of RequestDispatcher to send the same Java object across multiple JSP pages


Please bear with me as I'm very new to JSP. I thank you in advance for your help; I greatly appreciate it.

BACKGROUND

I am trying to build a web application which "remembers" certain java objects throughout a user's login session. Currently, I have a servlet which uses RequestDispatcher to send an object to a JSP page via its doPost method.

Here is the doPost of the servlet:

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

}

The sample.jsp gets the strBook object, and processes it. The body of the sample.jsp looks like this:

<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>

PROBLEM

How do I take the strBook object from within sample.jsp, and send it to the sample2.jsp WHEN the submit button is clicked (so the strBook object can be utilized in sample2.jsp)?

Currently, the body of sample2.jsp looks like this, and the strBook within is 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>

Solution

  • You could pass it as parameter to next 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>