【发布时间】: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