请求的转发和重定向:
1)本质区别:请求的转发只发出一次请求,而重定向则发出来两次请求。
具体:
①请求的转发:地址栏是初次发出请求的地址
请求的重定向:地址栏不再是初次发出的请求地址,地址栏为最后响应的那个地址
②请求转发:在最终的Servlet中,request对象和中转的那个request是同一个对象
请求的重定向:在最终的Servlet中,request对象和中转的那个request不是同一个对象
(3)请求的转发:只能转发给当前WEB应用的资源
请求的重定向:可以重定向到任何资源。
④请求转发:/ 代表的是当前WEB应用的根目录
请求重定向:/ 代表的是当前WEB站点的根目录
JSP
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<a href="ForwardServlet">ForwardServlet</a>
<br>
<a href="RedirectServlet">RedirectServlet</a>
</body>
</html>
Servlet
public class ForwardServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("ForwardServlet's doGet");
/**
* 请求的转发
* 1.调用HttpServletRequest的getRequestDispatcher()方法获取RequestDispatcher对象
* 调用getRequestDispatcher()需要传入要转发的地址
*/
String path = "/TestServlet";
RequestDispatcher requestDispatcher = request.getRequestDispatcher(path);
/**
* 2.调用HttpServletRequest的forward(request,response)进行请求的转发
*/
requestDispatcher.forward(request,response);
}
public class TestServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("TestServlet's doGet");
}
}
@WebServlet(name = "RedirectServlet")
public class RedirectServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("RedirectServlet's doGet");
//执行请求的重定向,直接调用response,sendRedirect(path)方法
//path为要重定向的地址
String path = "TestServlet";
response.sendRedirect(path);
}
}
转载于:https://www.cnblogs.com/yangHS/p/10985219.html