Javaweb的转发与重定向的区别以及解决重定向不能共享数据的问题

转发:
转发是内部资源跳转的一个过程
(浏览器调用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:即可解决数据共享的问题。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值