本文介绍了从Spring MVC中的控制器操作重定向到外部URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have noticed the following code is redirecting the User to a URL inside the project,

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

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

whereas, the following is redirecting properly as intended, but requires http:// or 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,无论它是否有是否有效的协议,不想重定向到视图。我怎么能这样做?

I want the redirect to always redirect to the URL specified, whether it has a valid protocol in it or not and do not want to redirect to a view. How can I do that?

谢谢,

推荐答案

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

You can do it with two ways.

首先:

@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);
}

这篇关于从Spring MVC中的控制器操作重定向到外部URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 02:33