我想做一个简单的帖子 - 重定向 - 使用 JSP。我就是这样做的。重要的Servlet是这样的:
public class PostRedirectGet extends HttpServlet {
public void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
throws ServletException, IOException {
getServletContext().getRequestDispatcher("/WEB-INF/getInformation.jsp")
.forward(httpServletRequest,httpServletResponse);
}
public void doPost(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse)
throws IOException {
String firstName = httpServletRequest.getParameter("firstName");
HttpSession httpSession = httpServletRequest.getSession();
httpSession.setAttribute("firstName",firstName);
httpServletResponse.sendRedirect(getServletContext().getContextPath()+"/getFormData");
}
}
因此,当对此 Servlet (/index ) 发出 get 请求 时,我仅显示表单所在的 getInformation.jsp。
表单向同一 URL (/index ) 发出 post 请求,这次调用 doPost。在这里,我保留了名字,如下所示:
String firstName = httpServletRequest.getParameter("firstName");
然后我将用户重定向到/getFormData。这是负责的 servlet:
public class Get extends HttpServlet {
public void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
throws ServletException, IOException {
String firstName = (String) httpServletRequest.getSession().getAttribute("firstName");
httpServletRequest.setAttribute("firstName",firstName);
getServletContext().getRequestDispatcher("/WEB-INF/showInformation.jsp")
.forward(httpServletRequest, httpServletResponse);
}
}
所以我在这里获取变量
String firstName = (String) httpServletRequest.getSession().getAttribute("firstName");
我的第一个问题是:1)这样,firstName 将在所有 session 期间可用,但我不希望这样。那么我应该如何在 2 个 servlet 之间传递信息呢?或者我应该如何清除这个值?
然后我将请求转发到 showInformation.jsp,如下所示:
Hello, your first name is: <%= request.getAttribute("firstName") %>
我的第二个问题是:2)为什么没有“;”在这里的 request.getAttribute("firstName) 之后?它工作得很好,但我希望需要一个分号(“;”)。
如果我输入分号,我的 jsp 文件上会出现此异常:
Syntax error on token ";", delete this token
最佳答案
关于你的第一个问题:你不应该使用 session 来存储这样的临时数据。
让我们举一个更现实的例子。该表单用于创建产品。 POST请求包含了产品的所有信息。因此,Servlet 从请求参数中获取此信息,在数据库的产品表中创建一行,并为该创建的产品生成一个标识符(主键)。现在 servlet 应该重定向到显示创建的产品信息的页面。所以它应该重定向到这种 URL:
/product?id=<theGeneratedProductId>
或
/products/<theGeneratedProductId>
然后,第二个 servlet 将从请求参数或请求 URL 中获取产品的 ID,从数据库中获取产品信息,将 Product 对象存储在请求属性中,然后转发到显示该产品的 JSP。
关于你的第二个问题:
<%= request.getAttribute("firstName") %>
由 JSP 编译器翻译为以下 Java 指令(这并不完全正确,但您应该明白):
response.getWriter().print(request.getAttribute("firstName"));
所以你明白添加分号会转化为
response.getWriter().print(request.getAttribute("firstName"););
这将是无效的 Java 代码。
无论如何,您都不应该在 JSP 中使用 scriptlet。因此,请尝试忘记 scriptlet 的存在,并学习 JSP EL、JSTL 和其他自定义标记库。你应该这样写:
${firstName}
或者,甚至更好:
<c:out value="${firstName}"/>
这将确保您的 HTML 保持有效,即使名字碰巧包含必须进行 HTML 转义的字符,例如 <
, >
, &
, '
或"
.
考虑一下如果用户提交以下名字并且没有正确转义会发生什么:
<script>alert('Got you!');</script>
关于java - 如何用JSP文件实现Post Redirect Get,数据保存在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19914011/