servlet中调用转发、重定向的语句:
request.getRequestDispatcher(“new.jsp”).forward(request, response);//转发到new.jsp
response.sendRedirect(“new.jsp”);//重定向到new.jsp
在jsp页面中你也会看到通过下面的方式实现转发:
当然也可以在jsp页面中实现重定向:
<%response.sendRedirect(“new.jsp”);//重定向到new.jsp%>
重定向:
public class ServletRedirect extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//重定向
response.sendRedirect("/Web09-/Demo1.html");
//传递参数
request.setAttribute("Rong", "rong");
response.sendRedirect("/Web09-/ServletCookie/GetDataDemo");
System.out.println("重定向参数保存!");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
请求转发:
public class QingQiuzf extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//创建context对象
ServletContext context = this.getServletContext();
//使用请求转发方法
//RequestDispatcher getRequestDispatcher(String path);
RequestDispatcher rd = context.getRequestDispatcher("Demo1.html");
//使用forward方法封装 request和response
// rd.forward(request, response);
request.getRequestDispatcher("/Demo1.html").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
1) 重定向:
a:重定向(浏览器行为)跳转页面的时候,地址栏发生变化
b:一次重定向有2个请求对象
c:重定向是可以跳转到外部工程的资源文件中
d:request域对象可以获取到参数数据
2) 请求转发:
a:请求转发(服务器行为)跳转页面的时候,地址栏不发生变化
b:请求转发,只有1次请求
c:
使用请求转发,它只能转发到当前项目下的资源文件中,不能转发到外部工程里面
d:使用rquest域对象获取不到参数数据
转发是服务器行为,重定向是客户端(浏览器)行为