Spring Cloud Zuul:RedirectView重定向到服务而不是网关

时间:2017-05-18 13:13:15

标签: java spring-mvc spring-cloud netflix-zuul

我对微服务和Spring有点新鲜。我有Spring Cloud微服务(端口:8xxx-8xxx),在端口9000上运行Zuul网关。在UI服务的控制器内有一个方法,应该登录然后返回index.html页面:

@RequestMapping(value="/do-login", method = RequestMethod.POST)
    public RedirectView doLogin (@ModelAttribute("authEntity") final AuthEntity authEntity, final Model model) {
        model.addAttribute(VERSION, applicationVersion);
        model.addAttribute("authEntity", new AuthEntity());
        authenticatedStatus = true;
        model.addAttribute(AUTHENTICATED, authenticatedStatus);

        return new RedirectView("index");
    }

问题是,当上面的方法完成时,它返回微服务本身的网址localhost:8888/index,但不返回localhost:9000/services/ui/

如果我使用更简单的方法:

@RequestMapping(value="/do-login", method = RequestMethod.POST)
public String doLogin (@ModelAttribute("authEntity") final AuthEntity authEntity, final Model model) {
    model.addAttribute(VERSION, applicationVersion);
    model.addAttribute("authEntity", new AuthEntity());
    authenticatedStatus = true;
    model.addAttribute(AUTHENTICATED, authenticatedStatus);

    return "index";
}

这会正确返回网关localhost:9000/services/ui/do-login的网址,但是我不需要/do-login

也许我可以摆脱/do-login/部分网址?或者可能有错误重定向的解决方案?

提前致谢!

2 个答案:

答案 0 :(得分:0)

如果您使用return "index";中的相对路径,则发送到POST的{​​{1}}请求的结果将包含http://localhost:9000/services/ui/do-login的网址,除非在jsp / freemarker /中另有编码thymeleaf文件。

如果你想摆脱http://localhost:9000/...,你需要实现所谓的Post Post后重定向(或表单提交后重定向)方法,以便页面刷新不会重新提交表单。如果您采用这种方法,这似乎是您在使用do-login时所做的事情,我可以考虑修复URL并将其设置为代理主机的几种方法。

1)http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/servlet/view/RedirectView.html,有一些构造函数接受主机参数,您需要在控制器类中注入代理主机,并且最有可能在每个实现重定向后发布的控制器类中。 / p>

2)http://tuckey.org/urlrewrite/,包括UrlRewriteFilter并配置规则,以便在webapp http状态代码响应为302时从webapp主机重写为代理主机。使用此方法只需一次规则,无需注入代理主机控制器类或更改返回新的RedirectView(“index”);`

3)也许这种重写是在return new RedirectView("index");中实现的,您不需要按照2)中的建议包含和配置Zuul

作为旁注,我已经将Nginx的proxy_pass配置为Java webapps(我在Post Post之后实现了Redirect),我不记得有这个问题。必须查看UrlRewriteFilterUrlRewriteFilter个配置文件才能对此进行扩展。

答案 1 :(得分:0)

我发现这(感谢这里的回答:Spring redirect url issue when behind Zuul proxy)似乎按要求工作(但被认为是'解决方法'):

@RequestMapping(value="/do-login", method = RequestMethod.POST)
    public void doLogin (@ModelAttribute("authEntity") final AuthEntity authEntity,
                         final Model model,
                         HttpServletResponse servletResponse) throws IOException {
        ...

        String rUrl = ServletUriComponentsBuilder.fromCurrentContextPath().path("/").build().toUriString();
        servletResponse.sendRedirect(rUrl);
    }
相关问题