为什么 request.getRequestURL() return 非 https url?

Why does request.getRequestURL() return non-https url?

在我们的一个项目中,我们仍然必须使用 JSF 1.2 + Tomcat 6,问题是当我向服务器发送 https 请求并试图获得请求时 URL在managed bean中如下:

ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
HttpServletRequest request = (HttpServletRequest)context.getRequest();
String url = request.getRequestURL().toString()

发送请求的按钮只是一个提交按钮,如下所示:

<h:form id="contactform">
    <h:commandButton id="submit" action="#{forgotPasswordBean.doSend}"
 </h:form>

我得到基于 http 的 URL 而不是 https。 在网络浏览器的调试面板中,我确保 https-请求实际上已发送,但 URL 包含 link 到 http 请求。有什么问题还是只是一个错误?

HttpServletRequest#getRequestUrl() 包含协议、服务器名称、端口号和服务器路径,即如果连接实际上是安全的并且在 HTTP 下,它应该包含 https

但是,这不是确定连接是否安全的唯一方法。 ServelRequest interface defines two more options (ServletRequest#getScheme() and ServletRequest#isSecure()) 检测请求是否安全:

String scheme = request.getScheme(); //will return "https" when connection is secured
//or
boolean isSecured = request.isSecure(); //will return true when connection is secured

更多信息:

  • How to check if the request to a Servlet is secured or not?

如果您在应用程序前面有一个负载平衡器,就会发生这种情况。即使请求是在 HTTPS 中完成的,负载均衡器也会将它们重新发布为产生此行为的纯 http 请求。

一个例子是使用 GAE (Google App Engine)。您可以使用 HTTPS 端点 (https://my-app.appspot.com),但您的应用将继续接收 HTTP 中的所有请求。

@user3663882 在已批准答案的评论下指出了这一点。