Solon v2.7.5

forward 和 redirect 的区别

</> markdown

1、Context::forward

forward 是在服务端,把当前请求“路径”(比如:/)转换为一个“新路径”(比如:/index)(是当前服务端的路径),通过 Solon.app().tryHandle() 再执行一次;

客户端对它的感觉是:

  • 请求只发生一次
  • 请求的地求没变化(例:请求的是 /)

内部实现代码:

public void forward(String pathNew) {
    pathNew(pathNew); //新地址,必须是路由器内存在的

    Solon.app().tryHandle(this);
    setHandled(true);
    setRendered(true);
}

Solon 是不支持 ContextPath 特性的。平时通过 ContextPathFilter 进行效果模拟,其内部就是基于 pathNew 这个特性实现的。

2、Context::redirect

redirect 是服务端,输出头信息 Location=“新地址”(例如:/index)和 头信息 Status=302,通知客户端用“新地址”再发起一次请求

客户端对它的感觉是:

  • 请求了两次
  • 请求的地求也变化了
  • 可以跳转到其它域名的地址

内部实现代码:

public void redirect(String url) {
    redirect(url, 302);
}

public void redirect(String url, int code) {
    headerSet("Location", url); //可以是相对地址,也可以是绝对地址;也可以是其它域的地址
    status(code);
}