转发
由服务器端进行的页面跳转
public class Servlet01 extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//转发的跳转方式,跳转到page.html
request.getRequestDispatcher("page.html").forward(request,response);
}
}
特点:
1.发送一次请求
2.地址栏不发生变化
3.数据不会丢失
重定向
由浏览器进行的页面跳转
public class Servlet02 extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//重定向的跳转方式,跳转到page.html
response.sendRedirect("page.html");
}
特点:
1.进行两次请求
2.地址栏会变化
3.数据可能丢失
转发和重定向区别
一、请求次数
转发请求一次
重定向请求两次
二、访问普通页面区别(web下页面)
转发和重定向都能正常访问
三、访问外部页面区别
转发不能访问外部的页面,因为转发是在服务器内部执行的
重定向可以访问外部页面,因为重定向是由浏览器执行的
四、访问受保护页面(WEB-INF中的页面)
转发可以访问
重定向不能访问,因为浏览器没有访问WEB-INF中页面的权限