转发:
转发是内部资源跳转的一个过程
(浏览器调用jsp容器中的方法调用目标页面,浏览器不知道,所有地址栏的地址不会发生变化) request.getRequestDispatcher("/login.jsp").forward(request,response);
重定向:
一个web资源收到客户端的请求后,通知客户端去访问另外一个web资源
(通知浏览器发送一个新的页面请求,地址栏会发生变化)
response.sendRedirect(request.getContextPath() + “/index.jsp”);
两者的对比如下:
重定向之后当前页面的数据与跳转后页面的数据是不能共享的,要解决这个问题,我们可以新建一个Servlet。
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
/**
* @Author: zc
*
* 抽取出来的servlet
*/
public class BaseServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//通过判断用户的方法来执行对应的操作
String methodName = request.getParameter("method");
try {
Method method = this.getClass().getMethod(methodName,HttpServletRequest.class,HttpServletResponse.class);
String url = (String) method.invoke(this,request,response);//等同于this.method;
//判断url是否为空 不等0 说明有数据
if (url!=null&&url.length()!=0){
//根据返回值判断转发或者是重定向,添加前缀名 redirect 或者forward
if (url.startsWith("forward:")){
request.getRequestDispatcher(url.split(":")[1]).forward(request,response);
}else {
response.sendRedirect(url);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}
当我们使用重定向时,只需要在重定向的路径前添加一个forword:即可解决数据共享的问题。