ChatGPT解决这个技术问题 Extra ChatGPT

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

谢谢,


b
buræquete

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

第一的:

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

如果您直接返回 String 而不是 ModelAndView,它会更简单。
似乎在第一种方法中,您应该将返回代码设置为 302。否则服务器将返回带有代码 200 和 Location 标头的响应,这在我的情况下不会导致重定向(Firefox 41.0)。
我们还可以在重定向到外部 URL 期间添加 cookie。
第一种方法需要 @ResponseStatus(HttpStatus.FOUND)
@Rinat Mukhamedgaliev 在这个 ModelAndView("redirect:" + projectUrl);声明如果添加的东西是 value ,默认的 key 是什么?
m
matsev

您可以使用 RedirectView。从 JavaDoc 复制:

重定向到绝对、上下文相对或当前请求相对 URL 的视图

例子:

@RequestMapping("/to-be-redirected")
public RedirectView localRedirect() {
    RedirectView redirectView = new RedirectView();
    redirectView.setUrl("http://www.yahoo.com");
    return redirectView;
}

您也可以使用 ResponseEntity,例如

@RequestMapping("/to-be-redirected")
public ResponseEntity<Object> redirectToExternalUrl() throws URISyntaxException {
    URI yahoo = new URI("http://www.yahoo.com");
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setLocation(yahoo);
    return new ResponseEntity<>(httpHeaders, HttpStatus.SEE_OTHER);
}

当然,如其他人所提到的,返回 redirect:http://www.yahoo.com


RedirectView 是唯一对我有用的!
我在使用重定向视图时有一个奇怪的行为,在 webshpere 上我得到:[code][27/04/17 13:45:55:385 CDT] 00001303 webapp E com.ibm.ws.webcontainer.webapp.WebApp logServletError SRVE0293E : [Error de servlet]-[DispatcherPrincipal]: java.io.IOException: 在 javax.servlet.http.HttpServletResponseWrapper 的 mx.isban.security.components.SecOutputFilter$WrapperRsSecured.sendRedirect(SecOutputFilter.java:234) 不允许模式。 sendRedirect(HttpServletResponseWrapper.java:145)[代码]
k
k13i

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

  @GetMapping
  ResponseEntity<Void> redirect() {
    return ResponseEntity.status(HttpStatus.FOUND)
        .location(URI.create("http://www.yahoo.com"))
        .build();
  }

这个答案是完美的,因为它允许重定向,而且您可以选择不重定向而只返回正文中的某些内容。它非常灵活。
@k13i 我在我的应用程序中遇到了同样的问题,我需要将存储在 DB 中的 URL 列表传递回控制器以进行重定向。如何用 Thymeleaf 处理的值替换 URI.create("http://www.yahoo.com")
d
daniel.eichten

查看 UrlBasedViewResolverRedirectView 的实际实现,如果您的重定向目标以 / 开头,则重定向将始终是 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;
}

但是通过这种方式,重定向是 GET 还是仍然是 POST?如何重定向为 POST?
好吧,实际上默认情况下这会返回一个 302,这意味着它应该针对提供的 url 发出一个 GET 。对于保持相同方法的重定向,您还应该设置不同的代码(从 HTTP/1.1 开始为 307)。但是我很确定如果由于安全问题而使用不同的主机/端口组合的绝对地址,浏览器会阻止它。
I
Ivan Mushketyk

另一种方法是使用 sendRedirect 方法:

@RequestMapping(
    value = "/",
    method = RequestMethod.GET)
public void redirectToTwitter(HttpServletResponse httpServletResponse) throws IOException {
    httpServletResponse.sendRedirect("https://twitter.com");
}

L
Lord Nighton

对我来说工作正常:

@RequestMapping (value = "/{id}", method = RequestMethod.GET)
public ResponseEntity<Object> redirectToExternalUrl() throws URISyntaxException {
    URI uri = new URI("http://www.google.com");
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setLocation(uri);
    return new ResponseEntity<>(httpHeaders, HttpStatus.SEE_OTHER);
}

我认为这种方法比 RedirectView 更好,因为它也在邮递员中工作。
s
sreeprasad

对于外部网址,您必须使用“http://www.yahoo.com”作为重定向网址。

这在 Spring 参考文档的 redirect: prefix 中有说明。

重定向:/myapp/some/resource

将相对于当前 Servlet 上下文进行重定向,而名称如

重定向:http://myhost.com/some/arbitrary/path

将重定向到绝对 URL


这是imo最准确的答案。该操作要求将 URL 重定向为绝对 URL,即使其中没有方案。答案是:不,你不能,你必须指定方案。我看到的所有其他答案都有效,因为他们使用 http://www.yahoo.comhttp://www.google.com 等作为他们解决方案的示例输入。如果他们使用 www.yahoo.com,无论是 ResponseEntity 还是 redirect:,它都会中断。尝试使用 Spring boot 2.5.2 和 Chrome、Firefox 和 Safari。
V
Vijay Kukkala

您是否尝试过可以提供 contextRelative 参数的 RedirectView


该参数对于以 / 开头(或不以 / 开头)的路径很有用,以检查它是否应该与 webapp 上下文相关。重定向请求仍将针对同一主机。
N
Neptune

这对我有用,并解决了“对预检请求的响应未通过访问控制检查......”问题。

控制器

    RedirectView doRedirect(HttpServletRequest request){

        String orgUrl = request.getRequestURL()
        String redirectUrl = orgUrl.replaceAll(".*/test/","http://xxxx.com/test/")

        RedirectView redirectView = new RedirectView()
        redirectView.setUrl(redirectUrl)
        redirectView.setStatusCode(HttpStatus.TEMPORARY_REDIRECT)
        return redirectView
    }

并启用安全性

@EnableWebSecurity
class SecurityConfigurer extends WebSecurityConfigurerAdapter{
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable()
    }
}

h
hd1

简而言之,"redirect://yahoo.com" 会将您借给 yahoo.com

"redirect:yahoo.com" 将借给您 your-context/yahoo.com 即为 ex- localhost:8080/yahoo.com


两种解决方案都有相同的命令:“简而言之,“redirect:yahoo.com”与“其中”作为“redirect:yahoo.com”,并且只有相对 url 重定向有效。