RequestDispatcher
的forward()
和HttpServletResponse
的sendRedirect()
方法有什么区别?
任何人都可以通过实时示例解释这些方法的示例和最佳用法吗?
最佳答案
重定向是一种发送回客户端的响应,而转发委托(delegate)完全在服务器端进行,转发操作的结果返回给客户端,就好像它仅来自原始 URL。
另一个区别是转发委托(delegate)只能用于应用程序内的资源,而重定向 命令可以将客户端浏览器重定向到当前域之外。
示例:
// Sends a temporary redirect to the HTTP client. Only absolute URLs are allowed.
ServletResponse.sendRedirect(String location);
// Delegates one HttpRequest to another dynamic or static resource
HttpRequest.getRequestDispatcher("example.jsp").forward(request, response);
// Includes/enriches current response with another dynamic or static resource
HttpRequest.getRequestDispatcher("example.html").include(request, response);
另一个很好的解释可以在这里找到:
Difference between sendRedirect() and forward()
关于java - RequestDispatcher.forward() 和 HttpServletResponse.sendRedirect() 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7220241/