实现效果如下
表单代码
<form action="stu" method="get">
学号:<input type="text" name="id"><br>
姓名:<input type="text" name="name"><br>
<input type="submit" value="确定">
<input type="reset" value="重置">
</form>
学生类
public class Student {
private String sno;
private String name;
public String getSno() {
return sno;
}
public void setSno(String sno) {
this.sno = sno;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Student(String id,String name) {
this.sno=id;
this.name=name;
}
}
FirstServlet处理
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String id=request.getParameter("id");
String name=request.getParameter("name");
Student stu=new Student(id,name);
ServletContext ser=getServletContext();
ser.setAttribute("id", stu.getSno());
ser.setAttribute("name", stu.getName());
RequestDispatcher rd=ser.getRequestDispatcher("/SecondServlet");
rd.forward(request, response);
}
转发到SecondServlet处理
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter p=response.getWriter();
ServletContext ser=getServletContext();
p.println("<html>");
p.println("<head>");
p.println("</head>");
p.println("<body>");
p.println("<center><a href=\"http://localhost:8080/实验四/input.html\">返回</a><h3>");
p.println("<h3>学号:"+ser.getAttribute("id")+"</h3><p>");
p.println("<h3>姓名:"+ser.getAttribute("name")+"</h3><p></center>");
p.println("</body>");
p.println("</html>");
}
web.xml
<servlet>
<servlet-name>FirstServlet</servlet-name>
<servlet-class>实验四.FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FirstServlet</servlet-name>
<url-pattern>/stu</url-pattern>
</servlet-mapping>