转发(request.setRequestDispacter)和重定向(response.sendRedirect)的区别以及转发的include和forward的区别
//response 重定向的时候,url是会跳转到新的页面的,输入的地址要包含项目名(可以跳到项目之外的页面,比如百度)
//request 请求转发的时候,url是不会跳转到新页面的,输入的地址不包含项目名(只可以在此项目中进行跳转 )
/*request.getRequestDispatcher("/RquestDemo5").forward(request, response);
*request.getRequestDispatcher("/RquestDemo5").include(request, response); 的区别
*
*在原页面out.write("11111") ,在新的页面out.write("22222");
*
*forward :在浏览器显示的是 22222
*include :在浏览器中显示的11111
*/
这个自己写一两个小demo试一试就知道了
页面一(原页面):
package com.chensi; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet 请求转发和请求重定向 进行一下 对比 */ @WebServlet("/RequestDemo4") public class RequestDemo4 extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); String str = "66666"; request.setAttribute("str", str); //request.getRequestDispatcher("/RequestDemo/RquestDemo5").forward(request, response); request.getRequestDispatcher("/RquestDemo5").forward(request, response); //request.getRequestDispatcher("http://WWW.baidu.com").forward(request, response); //response.sendRedirect("/RequestDemo/RquestDemo5"); //response.sendRedirect("http://WWW.baidu.com"); //request.getRequestDispatcher("/RquestDemo5").include(request, response); response.getWriter().write("111111111111"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
页面二(被跳转的页面):
package com.chensi; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class RquestDemo5 */ @WebServlet("/RquestDemo5") public class RquestDemo5 extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); //System.out.println("我试试 进没进来这个demo5"); //response.getWriter().write("这个是被转发或者重定向 的页面!!!demo5"); //System.out.println(request.getAttribute("str")); response.getWriter().write("22222222"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }