2014-12-06 31 views
0

請耐心等待,因爲我對JSP很陌生。我事先感謝你的幫助;我非常感謝。有條件地使用RequestDispatcher跨多個JSP頁面發送相同的Java對象

背景

我想建立一個Web應用程序在整個用戶的登錄會話它會「記住」特定的Java對象。目前,我有一個使用RequestDispatcher通過doPost方法發送對象到JSP頁面的servlet。

這裏是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的身體看起來是這樣的,而strBook內爲空:

<body> 

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


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

</body> 

回答

0

你可以通過它作爲參數傳遞給下一個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> 
+0

謝謝你的迴應SAS - 我很感激。在我真正的應用程序中,strBook實際上是一個更復雜的對象(「Book」對象不是String),因此在sample1.jsp中,代碼value =「<%=strBook%>」將無法傳輸Book對象。我只是尋找一種更通用的方法來將任何類型的對象從jsp發送到servlet,反之亦然,我想我只是找到了使用「會話」功能的方法。 – 2014-12-06 19:21:08