4.sendRedirect和RequestDispatcher的区别:
马克-to-win:response.sendRedirect()与request.getRequestDispatcher().forward()区别:response.sendRedirect(url)是先回到客户端,再重新请求url,和过去的请求没关系。可以访问任何地方。浏览器的地址栏也变成了新的url。request.getRequestDispatcher().forward()就干脆没回到客户端,就一直在服务器里,从本个web应用的一个资源(servlet,jsp,或html)跳到另一个资源。(所以不能随便访问什么地方)。而且浏览器地址栏没有变。同时可以用request.setAttribute("requestkey","requstvalue1");来传递参数。
以上几点是大家经常谈到的几点不同。底下就是我专门(exclusively)写给大家的,一点不
同。也许初学者难于理解,望留点印象。
RequestDispatcher会block,因为同在服务器端。当程序需要从资源1跳到资源2时,资源1
会等资源2运行完,回来以后,再继续执行下面没执行的部分。所谓的block。
例:3.4.1
package com;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletHello1 extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
System.out.println("ServletHello1 before");
request.getRequestDispatcher("/ServletHello2").forward(request,
response);
System.out.println("这里会block5秒,ServletHello1 after");
}
}
package com;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletHello2 extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("ServletHello2");
}
}
更多请看:https://blog.csdn.net/qq_44594371/article/details/103163921