”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 如何从 Spring MVC 控制器操作重定向到外部 URL?

如何从 Spring MVC 控制器操作重定向到外部 URL?

发布于2024-11-20
浏览:644

How to Redirect to External URLs from Spring MVC Controller Actions?

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

在 Spring MVC 中,使用redirect: 前缀重定向到项目内的 URL 非常简单。但是,重定向到外部 URL 可能会很棘手,尤其是在 URL 未指定有效协议的情况下。

考虑以下代码,它将重定向到项目内的 URL:

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

此代码不会重定向到预期的外部 URL,而是重定向到具有给定名称的视图。要重定向到外部 URL,必须在 URL 中包含协议,如下所示:

@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,有两种方法:

方法一:

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

在此方法中,HttpServletResponse对象用于设置位置标头和状态代码,强制重定向。

方法2:

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

此方法采用 ModelAndView 重定向到给定的 URL。

最新教程 更多>

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3