请耐心等待我,因为我对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内部是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>
答案 0 :(得分: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>