请多多包涵,因为我对 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 的主体是这样的,其中的 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>