学习getRequestDispatcher()与sendRedirect()笔记
1、request.getRequestDispatcher().forward(request, response);是请求转发,前后页面共享一个request ; 这个是在服务端运行的,对浏览器来说是透明的。这种方式跳转,传值可以使用三种方法:url中带parameter,session,request.setAttribute
2、response.sendRedirect()是重新定向,前后页面不是一个request。而这个是在浏览器端运行的。
该方式只适用于无传值跳转.
给自己看的并且记录
StudentServiceImple ssi = new StudentServiceImple();
List<Student> list;
Scanner input = new Scanner(System.in);
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String op = request.getParameter("op");
System.out.println(op);
if ("update1".equals(op)) {
update1Student(request, response);
} else if ("update2".equals(op)) {
update2Student(request, response);
} else if ("add".equals(op)) {
addStudent(request, response);
} else if ("add2".equals(op)) {
addStudent2(request, response);
} else {
list = ssi.queryAll();
request.setAttribute("students", list);
getServletContext().getRequestDispatcher("/studentServlet.jsp").forward(request, response);
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
// 根据要修改的id找到所有的属性
public void update1Student(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
for (Student s : list) {
int id = Integer.valueOf(request.getParameter("id"));
if (id == s.getId()) {
request.setAttribute("student", s);
break;
}
}
getServletContext().getRequestDispatcher("/update.jsp").forward(request, response);
}
// 实现修改的方法
public void update2Student(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int id = Integer.valueOf(request.getParameter("id"));
String sname = request.getParameter("name");
String ssex = request.getParameter("sex");
ssi.updateStudent(new Student(id, sname, ssex, 0));
// 重定向跳转
System.out.println("==================================");
response.sendRedirect("StudentServlet");
}
public void addStudent(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.sendRedirect("addStudent.jsp");
}
public void addStudent2(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int id = Integer.valueOf(request.getParameter("id"));
String sname = request.getParameter("sname");
String ssex = request.getParameter("ssex");
int tid = Integer.valueOf(request.getParameter("stid"));
System.out.println(id + sname + ssex+tid);
ssi.addStudent(new Student(id, sname, ssex, tid));
response.sendRedirect("StudentServlet");
}
1、使用response.sendRedirect()地址栏将改变
2、使用request.getRequestDispatcher().forward(request,response)地址栏中的信息保持不变.
request.setAttribute存的东西
只用通过方法2跳转 才能在新页取出来