从 Spring MVC 中的控制器操作重定向到外部 URL

新手上路,请多包涵

我注意到以下代码将用户重定向到项目内的 URL,

 @RequestMapping(method = RequestMethod.POST)
public String processForm(HttpServletRequest request, LoginForm loginForm,
                          BindingResult result, ModelMap model)
{
    String redirectUrl = "yahoo.com";
    return "redirect:" + redirectUrl;
}

然而,以下是按预期正确重定向,但需要 http:// 或 https://

 @RequestMapping(method = RequestMethod.POST)
    public String processForm(HttpServletRequest request, LoginForm loginForm,
                              BindingResult result, ModelMap model)
    {
        String redirectUrl = "http://www.yahoo.com";
        return "redirect:" + redirectUrl;
    }

我希望重定向始终重定向到指定的 URL,无论它是否具有有效协议,并且不想重定向到视图。我怎样才能做到这一点?

谢谢,

原文由 Jake 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 566
2 个回答

你可以用两种方法来做到这一点。

第一的:

 @RequestMapping(value = "/redirect", method = RequestMethod.GET)
public void method(HttpServletResponse httpServletResponse) {
    httpServletResponse.setHeader("Location", projectUrl);
    httpServletResponse.setStatus(302);
}

第二:

 @RequestMapping(value = "/redirect", method = RequestMethod.GET)
public ModelAndView method() {
    return new ModelAndView("redirect:" + projectUrl);
}

原文由 Rinat Mukhamedgaliev 发布,翻译遵循 CC BY-SA 4.0 许可协议

您可以使用 RedirectView 。从 JavaDoc 复制:

重定向到绝对、上下文相关或当前请求相对 URL 的视图

例子:

 @RequestMapping("/to-be-redirected")
public RedirectView localRedirect() {
    RedirectView redirectView = new RedirectView();
    redirectView.setUrl("http://www.yahoo.com");
    return redirectView;
}

您还可以使用 ResponseEntity ,例如

@RequestMapping("/to-be-redirected")
public ResponseEntity<Object> redirectToExternalUrl() throws URISyntaxException {
    URI yahoo = new URI("http://www.yahoo.com");
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setLocation(yahoo);
    return new ResponseEntity<>(httpHeaders, HttpStatus.SEE_OTHER);
}

当然,返回 redirect:http://www.yahoo.com 正如其他人所提到的。

原文由 matsev 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题