url 重写结合HttpSession实现会话管理之 form 提交
package com.test; import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter; @WebServlet("/questionnaire")
public class Questionnaire extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter();
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<meta charset='UTF-8'>");
out.println("<title>问卷调查</title>");
out.println("</head>");
out.println("<body>");
String page = request.getParameter("page");
if(page == null) { // 第一頁問卷
out.println("<form action='questionnaire' method='get'>");
out.println("問題一:<input type='text' name='p1q1'><br>");
out.println("問題二:<input type='text' name='p1q2'><br>");
out.println("<input type='submit' name='page' value='page2'>");
out.println("</form>");
}
else if("page2".equals(page)) { // 第二頁問卷
/**
* 下面这三行代码的顺序不可变
*/
HttpSession session = request.getSession();
String url = response.encodeURL("questionnaire");
out.println("<form action=\"" + url + "\" method=\"get\">");
session.setAttribute("p1q1", request.getParameter("p1q1"));
session.setAttribute("p1q2", request.getParameter("p1q2"));
out.println("問題三:<input type='text' name='p2q1'> <br>");
out.println("<input type='submit' name='page' value='finish'>");
out.println("</form>");
}
else if("finish".equals(page)) { // 最後答案收集
HttpSession session = request.getSession();
out.println(session.getAttribute("p1q1") + "<br>");
out.println(session.getAttribute("p1q2") + "<br>");
out.println(request.getParameter("p2q1") + "<br>");
}
out.println("</body>");
out.println("</html>");
out.close();
} @Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
} @Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
}