请求转发与重定向

740 阅读2分钟

针对传统项目,特别是用springMVC框架的

请求转发



public class TestRequestDispatcher extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    /*
    * 1.逻辑的处理
    * 2.服务器端的页面跳转,地址栏不变
    * */
    req.getRequestDispatcher("/test.html").forward(req, resp);
}
 
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    doGet(req, resp);
}
}

重定向

@WebServlet("/send_redirect")
public class SendRedirectServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    doPost(request,response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    request.setCharacterEncoding("UTF-8");
    String name = request.getParameter("name");
    response.setContentType("text/html");
    this.getServletContext.setAttribute("name",name);
    //setAttribute("name",name);
    response.sendRedirect("http://localhost:8088/welcome.jsp");
}

}

总结

  1. 两者都可以实现页面的跳转。

  2. 请求转发是服务器内部转发,浏览器只发出一次请求;重定向时浏览器发出了两次请求,第一次请求得到一个地址,根据得到的地址发出第二次请求才得到内容

  3. 请求转发浏览器上的地址不会改变;(302跳转)重定向浏览器上的地址会改变。

  4. 请求转发只能在服务器内部转发;重定向可以跳转到其他服务器进行转发。

  5. 请求转发 是由HttpServletRequest对象调用方法:getRequestDispatcher("/hello4").forward(req, resp)
    重定向是HttpServletResponse 对象调用方法sendRedirect(URL)

针对前后端分离的项目

请求转发

/**	
** 请求转发
 */
@ApiOperation(value = "请求转发")
@RequestMapping("/oauth/forWard")
public void forWard( HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
	request.getRequestDispatcher("/oauth/render").forward(request,response);
}



重定向

/**
 * 重定向
 */
@ApiOperation(value = "重定向")
@RequestMapping("/oauth/render")
public void renderAuth(HttpServletResponse response) throws IOException {
	String toUrl = "http://localhost:8080";
	response.sendRedirect(toUrl);
}

总结:

  1. 前后端分离的项目,用请求转发的场景基本没有。因为后端项目不提供jsp页面与html页面,只提供接口。由a接口请求转发到b接口多此一举,不如直接调用b接口。
  2. 重定向的场景适用于后端向前端页面的跳转,比如跳转到第三方页面。