【步驟 1】創建一個名為 input.html 的 HTML 頁面,其中包括一個表單,表單中包含兩 個文本域,分別供用戶輸入學號和姓名,該頁面也包含提交和重置按鈕。
【步驟 2】定義一個名為 com.demo.Student 類,其中包括學號 sno 和姓名 name 兩個 private 的成員變量,定義訪問和修改 sno 和 name 的方法。
【步驟 3】編寫名為 FirstServlet 的 Servlet,要求當用戶在 input.html 中輸入信息后點擊 “提交”按鈕,請求 FirstServlet 對其處理。在 FirstServlet 中使用表單傳遞的參數(學號和 姓名)創建一個 Student 對象并將其作為屬性存儲在 ServletContext 對象中,然后獲得通過 ServletContext 的 getRequestDispatcher()方法獲得 RequestDispatcher()對象,將請求轉發到 SecondServlet。
【步驟 4】在 SecondServlet 中取出 ServletContext 上存儲的 Student 對象,并顯示輸出 該學生的學號和姓名。在 SecondServlet 的輸出中應該包含一個超鏈接,點擊該連接可以返 回 input.html 頁面。
源代碼
Student類
public class Student {private String sno;private String name;public Student(String sno, String name) {this.sno = sno;this.name = name;}public String getSno() {return this.sno;}public void setSno(String sno) {this.sno = sno;}public String getName() {return this.name;}public void setName(String name) {this.name = name;}
}
FirstServlet類
public class FirstServlet extends HttpServlet {private static final long serialVersionUID = 1L;public FirstServlet() {}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {ServletContext servletContext = this.getServletContext();servletContext.setAttribute("stu", new Student(request.getParameter("sno"), request.getParameter("name")));servletContext.getRequestDispatcher("/SecondServlet").forward(request, response);}public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this.doGet(request, response);}
}
SecondServlet類
public class SecondServlet extends HttpServlet {private static final long serialVersionUID = 1L;public SecondServlet() {}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response.setContentType("text/html;charset=UTF-8");ServletContext context = this.getServletContext();Student student = (Student)context.getAttribute("stu");PrintWriter out = response.getWriter();String title = "讀取數據";String docType = "<!DOCTYPE html> \n";out.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" + "<body bgcolor=\"#f0f0f0\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<ul>\n" + " <li><b>學號</b>:" + student.getSno() + "\n" + " <li><b>姓名</b>:" + student.getName() + "\n" + "</ul>\n" + "<a href=\"http://localhost:8080/webDemo2_war_exploded/input.html\">訪問輸入頁</a>" + "</body></html>");}public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this.doGet(request, response);}
}