猿问
下载APP

从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,无论它是否具有有效的协议,并且都不想重定向到视图。我怎样才能做到这一点?


慕容森
浏览 130回答 3
3回答

吃鸡游戏

您可以通过两种方式来实现。第一:@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);}

拉丁的传说

您可以使用RedirectView。从JavaDoc复制:重定向到绝对,上下文相关或当前请求相对URL的视图例:@RequestMapping("/to-be-redirected")public RedirectView localRedirect() {&nbsp; &nbsp; RedirectView redirectView = new RedirectView();&nbsp; &nbsp; redirectView.setUrl("http://www.yahoo.com");&nbsp; &nbsp; return redirectView;}您也可以使用ResponseEntity,例如@RequestMapping("/to-be-redirected")public ResponseEntity<Object> redirectToExternalUrl() throws URISyntaxException {&nbsp; &nbsp; URI yahoo = new URI("http://www.yahoo.com");&nbsp; &nbsp; HttpHeaders httpHeaders = new HttpHeaders();&nbsp; &nbsp; httpHeaders.setLocation(yahoo);&nbsp; &nbsp; return new ResponseEntity<>(httpHeaders, HttpStatus.SEE_OTHER);}当然,还可以redirect:http://www.yahoo.com像其他人提到的那样返回。

互换的青春

如果您的重定向目标以/开头,则在查看UrlBasedViewResolver和RedirectView的实际实现时,重定向始终为contextRelative。因此,发送//yahoo.com/path/to/resource也无助于获得协议的相对重定向。因此,要实现您想要的目标,您可以执行以下操作:@RequestMapping(method = RequestMethod.POST)public String processForm(HttpServletRequest request, LoginForm loginForm,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; BindingResult result, ModelMap model)&nbsp;{&nbsp; &nbsp; String redirectUrl = request.getScheme() + "://www.yahoo.com";&nbsp; &nbsp; return "redirect:" + redirectUrl;}
打开App,查看更多内容
随时随地看视频慕课网APP
我要回答