/**
* 重定向特点:
* 两次请求,浏览器行为,地址栏改变,请求域中的数据会丢失
* 请求转发:
* 一次请求,服务器行为,地址栏不变,请求域中的数据不丢失
*
* 请求域的作用范围:
* 当前请求(一次请求),和当前请求的转发之中
*/
public class RequestDemo6 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//1.拿到请求调度对象
RequestDispatcher rd = request.getRequestDispatcher("/RequestDemo7");//如果是给浏览器看的,/可写可不写。如果是给服务器看的,一般情况下,/都是必须的。
//放入数据到请求域中
request.setAttribute("CityCode", "bj-010");
//2.实现真正的转发操作
rd.forward(request, response);//实现真正的转发操作
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
/**
* 转发的目的地
*/
public class RequestDemo7 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//获取请求域中的数据
String value = (String)request.getAttribute("CityCode");
response.getWriter().write("welcome to request demo 7 "+value);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
/**
* 请求包含
* 它是把两个Servlet的响应内容合并输出。
* 注意:
* 这种包含是动态包含。
* 动态包含的特点:
* 各编译各的,只是最后合并输出。
*/
public class RequestDemo8 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.getWriter().write("I am request demo8 ");
//1.拿到请求调度对象
RequestDispatcher rd = request.getRequestDispatcher("/RequestDemo9");
//2.实现包含的操作
rd.include(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
/**
* 被包含者
*/
public class RequestDemo9 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.getWriter().write("include request demo 9 ");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
请求转发的注意事项:负责转发的Servlet,转发前后的响应正文丢失,由转发目的地来响应浏览器。
请求包含的注意事项:被包含者的响应消息头丢失。因为它被包含起来了。