【问题标题】:Redirect to dynamic URL in Spring MVC在 Spring MVC 中重定向到动态 URL
【发布时间】:2012-03-07 21:21:42
【问题描述】:

我希望我的 Spring MVC 应用程序重定向到一个动态 URL(由用户提交)。所以如果我有这样的代码,

@RequestMapping("/redirectToSite")
protected ModelAndView redirect(
    @RequestParam("redir_url") String redirectUrl,
    HttpServletRequest request, 
    HttpServletResponse response) 
{
    // redirect to redirectUrl here
    return ?
}

我应该写什么来重定向到提交的 URL?例如 http://mySpringMvcApp/redirectToSite?redir_url=http://www.google.com 应该重定向到 Google。

【问题讨论】:

  • 你试过 new ModelAndView(new RedirectView(redirectUrl)) 吗?
  • @Joe:同样有效。很棒的东西。
  • 不确定您是否考虑过这一点,但您应该考虑到开放式重定向是一种安全反模式,并且您至少应该在实际重定向到之前对提交的 url 进行基本验证。参见例如owasp.org/index.php/…

标签: spring redirect spring-mvc


【解决方案1】:
@RequestMapping(value="/redirect",method=RequestMethod.GET)
void homeController(HttpServletResponse http){
  try {
    http.sendRedirect("Your url here!");
  } catch (IOException ex) {

  }
}

【讨论】:

    【解决方案2】:

    试试这个:

    @RequestMapping("/redirectToSite")
    protected String redirect(@RequestParam("redir_url") String redirectUrl) 
    {
        return "redirect:" + redirectUrl;
    }
    

    这在 Spring reference documentation16.5.3.2 The redirect: prefix 中有解释。当然,您始终可以手动执行此操作:

    response.sendRedirect(redirectUrl);
    

    【讨论】:

    • 非常感谢,刚刚测试了它,它工作。必须将方法返回类型从 ModelAndView 更改为 String
    • @TomaszNurkiewicz 这个方法保留了url中的查询参数,如何去掉查询参数,只重定向到没有查询参数的url?
    • @TomaszNurkiewicz 我在这里找到了答案:stackoverflow.com/a/32406090/1385441
    • 请注意,目前的代码并未验证重定向 url 以确保其合法。我意识到这个问题与安全性无关,但会提醒人们不要只按原样解除此代码。永远不要相信客户端总是指定你可以重定向到的 url。 owasp.org/index.php/…
    猜你喜欢
    • 1970-01-01
    • 2014-06-20
    • 1970-01-01
    • 1970-01-01
    • 2010-09-26
    • 2016-02-03
    • 2013-08-06
    • 1970-01-01
    相关资源
    最近更新 更多