首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >从Spring MVC中的控制器操作重定向到外部URL

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

Stack Overflow用户
提问于 2013-07-31 03:32:01
回答 7查看 415.9K关注 0票数 150

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

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

然而,下面的重定向是正确的,但需要http://或https://

代码语言:javascript
复制
@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,无论它是否包含有效的协议,并且不希望重定向到视图。我该怎么做呢?

谢谢,

EN

回答 7

Stack Overflow用户

回答已采纳

发布于 2013-07-31 11:57:05

您可以使用两种方法来完成此操作。

首先:

代码语言:javascript
复制
@RequestMapping(value = "/redirect", method = RequestMethod.GET)
public void method(HttpServletResponse httpServletResponse) {
    httpServletResponse.setHeader("Location", projectUrl);
    httpServletResponse.setStatus(302);
}

第二:

代码语言:javascript
复制
@RequestMapping(value = "/redirect", method = RequestMethod.GET)
public ModelAndView method() {
    return new ModelAndView("redirect:" + projectUrl);
}
票数 247
EN

Stack Overflow用户

发布于 2013-08-01 19:58:00

查看UrlBasedViewResolverRedirectView的实际实现,如果您的重定向目标以contextRelative开头,则重定向将始终为/。因此,发送//yahoo.com/path/ to /resource也无助于获得协议相对重定向。

因此,要实现您正在尝试的目标,您可以这样做:

代码语言:javascript
复制
@RequestMapping(method = RequestMethod.POST)
public String processForm(HttpServletRequest request, LoginForm loginForm, 
                          BindingResult result, ModelMap model) 
{
    String redirectUrl = request.getScheme() + "://www.yahoo.com";
    return "redirect:" + redirectUrl;
}
票数 50
EN

Stack Overflow用户

发布于 2019-03-29 01:00:11

您可以使用ResponseEntity以非常简洁的方式完成此操作,如下所示:

代码语言:javascript
复制
  @GetMapping
  ResponseEntity<Void> redirect() {
    return ResponseEntity.status(HttpStatus.FOUND)
        .location(URI.create("http://www.yahoo.com"))
        .build();
  }
票数 41
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17955777

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档