JSF" faces-redirect = true"由于Apache ProxyPass,从https://重定向到http:// URL

时间:2014-04-11 16:47:25

标签: jsf redirect glassfish java-ee-7

由于我有一个Apache Web服务器为Glassfish服务器执行ProxyPass,后者不知道客户正在说“https”。

因此在使用

之类的东西时
return "shop.xhtml?faces-redirect=true";

生成的HTTP Location:标头包含“http://”URL。

我看过JSF redirects from HTTPS to HTTP,但发现这个解决方案并不是很优雅。有没有办法告诉Glassfish这个或所有传入的请求都是https,这样我就不必摆弄生成的导航规则了?

1 个答案:

答案 0 :(得分:2)

您可以尝试添加一些可以在java端解释的请求标头,例如' X-redirect-to-https'。然后创建将包装HttpServletResponse的过滤器,并在该包装器中覆盖sendRedirect方法,以便在重定向URL中将http替换为https,当X-redirect-to-https'标题存在。

代码(有点乱,但说明了一个解决方案)改编自: http://javahunter.wordpress.com/2011/06/01/why-does-https-become-http-on-a-sendredirect/

@WebFilter("/*")
public class HttpsSendRedirectFilter implements Filter {

   @Override
   public void init(FilterConfig filterConfig) throws ServletException {
   }

   @Override
   public void destroy() {
   }

   @Override
   public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
         ServletException {
      chain.doFilter(request, new HttpsRedirectResponseWrapper((HttpServletRequest) request,
            (HttpServletResponse) response));
   }
}

public class HttpsRedirectResponseWrapper extends HttpServletResponseWrapper {

   private HttpServletRequest req;
   private String prefix = null;

   public HttpsRedirectResponseWrapper(HttpServletRequest req, HttpServletResponse res) {
      super(res);
      this.req = req;
      prefix = getPrefix(req);
   }

   @Override
   public void sendRedirect(String location) throws IOException {
      String finalurl = null;

      if (isUrlAbsolute(location)) {
         finalurl = location;
      } else {
         finalurl = fixForScheme(prefix + location);
      }
      super.sendRedirect(finalurl);
   }

   public boolean isUrlAbsolute(String url) {
      String lowercaseurl = url.toLowerCase();
      if (lowercaseurl.startsWith("http") == true) {
         return true;
      } else {
         return false;
      }
   }

   public String fixForScheme(String url) {
      if (this.req.getHeader("X-redirect-to-https") != null) {
         return url.replaceFirst("http", "https");
      } else {
         return url;
      }
   }

   public String getPrefix(HttpServletRequest request) {
      StringBuffer str = request.getRequestURL();
      String url = str.toString();
      String uri = request.getRequestURI();
      int offset = url.indexOf(uri);
      String prefix_t = url.substring(0, offset);
      return prefix_t;
   }
}