有条件地使用RequestDispatcher跨多个JSP页面发送相同的Java对象
请容忍我,因为我对JSP很陌生。我提前感谢你的帮助;我非常感激 背景 我试图构建一个web应用程序,它在用户登录会话中“记住”某些java对象。目前,我有一个servlet,它使用RequestDispatcher通过doPost方法将对象发送到JSP页面 以下是servlet的doPost:有条件地使用RequestDispatcher跨多个JSP页面发送相同的Java对象,java,jsp,jakarta-ee,servlets,requestdispatcher,Java,Jsp,Jakarta Ee,Servlets,Requestdispatcher,请容忍我,因为我对JSP很陌生。我提前感谢你的帮助;我非常感激 背景 我试图构建一个web应用程序,它在用户登录会话中“记住”某些java对象。目前,我有一个servlet,它使用RequestDispatcher通过doPost方法将对象发送到JSP页面 以下是servlet的doPost: protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletExce
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);
}
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对象,并在单击submit按钮时将其发送到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>
书:
您可以将其作为参数传递给下一个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>
书:
感谢您的回复,非常感谢。在我的实际应用程序中,strBook实际上是一个更复杂的对象(“Book”对象而不是字符串),因此在sample1.jsp中,代码value=“”)将无法传输Book对象。我只是在寻找一种更通用的方法来将任何类型的对象从jsp发送到servlet,反之亦然,我想我刚刚找到了一种使用“会话”特性的方法。