我注意到下面的代码将用户重定向到项目中的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,无论它是否包含有效的协议,并且不希望重定向到视图。我该怎么做呢?
谢谢,
发布于 2013-07-31 11:57:05
您可以使用两种方法来完成此操作。
首先:
@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);
}
发布于 2013-08-01 19:58:00
查看UrlBasedViewResolver和RedirectView的实际实现,如果您的重定向目标以contextRelative开头,则重定向将始终为/。因此,发送//yahoo.com/path/ to /resource也无助于获得协议相对重定向。
因此,要实现您正在尝试的目标,您可以这样做:
@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;
}
发布于 2019-03-29 01:00:11
您可以使用ResponseEntity
以非常简洁的方式完成此操作,如下所示:
@GetMapping
ResponseEntity<Void> redirect() {
return ResponseEntity.status(HttpStatus.FOUND)
.location(URI.create("http://www.yahoo.com"))
.build();
}
https://stackoverflow.com/questions/17955777
复制相似问题