[英]Conditional use of RequestDispatcher to send the same Java object across multiple JSP pages
請耐心等待,因為我是JSP的新手。 我預先感謝您的幫助; 我非常感謝。
背景
我正在嘗試構建一個在用戶的登錄會話中“記住”某些java對象的Web應用程序。 當前,我有一個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(以便可以在sample2.jsp中使用strBook對象)?
當前,sample2.jsp的主體如下所示,其中的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>
您可以將其作為參數傳遞給下一個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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.