我想做一个简单的帖子 - 重定向 - 使用 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。在这里,我保留了 firstName,如下所示:
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 将在整个会话期间可用,但我不希望这样。那么我应该如何在 2 个 servlet 之间传递信息呢?或者我应该如何清除这个值?
然后我将请求转发给 showInformation.jsp,如下所示:
Hello, your first name is: <%= request.getAttribute("firstName") %>
我的第二个问题是:2)为什么没有“;” 在request.getAttribute("firstName)在这里之后?它像这样工作得很好,但我希望需要一个分号(“;”)。
如果我在我的 jsp 文件中加上一个分号,我会得到这个异常:
Syntax error on token ";", delete this token