【问题标题】:Spring MVC - Handling redirectionSpring MVC - 处理重定向
【发布时间】:2013-12-30 20:05:53
【问题描述】:

我想在服务器端重定向一个页面(使用 spring),但 URL 应该保持不变。

例如:如果用户尝试http://www.example.com/page1,我想在浏览器中呈现http://www.example.com/page2 的内容,但URL 仍应指向http://www.example.com/page1

我尝试了 301、302、307 重定向,但所有页面 URL 都更改为 http://www.example.com/page2

有没有办法做到这一点?

【问题讨论】:

标签: spring spring-mvc redirect


【解决方案1】:

这是术语的问题。您正在寻找的是forward 而不是redirect。如果你有兴趣,你可能想查一下,例如这里:http://www.javapractices.com/topic/TopicAction.do?Id=181

至少有两种方法可以做到这一点:

传统上,RequestDispatcher 也可以在 Spring WebMVC 应用程序之外使用。

public class MyController extends AbstractController {

    @Override
    protected void handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
    throws Exception {
        request.getRequestDispatcher("/new/path").forward(request, response);
    }
}

Spring WebMVC 表示法:

public class MyController extends AbstractController {

    @Override
    protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
    throws Exception {
        return new ModelAndView("forward:/new/path");
    }
}

【讨论】:

  • 为什么这么旧的 Spring 版本?
  • 谢谢。有用。是否可以将请求转发到某个外部站点?例如:从 example.com/page1yahoo.com 但 URL 仍然是 example.com/page1?
  • @SaravananShanmugam - 不
猜你喜欢
  • 1970-01-01
  • 2014-06-20
  • 2015-06-05
  • 1970-01-01
  • 2013-01-21
  • 2015-05-19
  • 2013-03-06
相关资源
最近更新 更多