java - 在 Dropwizard 中将 http 连接重定向到 https 的首选方法

标签 java redirect https http-redirect dropwizard

我想在 Dropwizard 中将传入的 http 连接重定向到 https,最好在配置文件中切换(例如,使用 YAML 文件,就像其他连接属性一样)。 [我看过this question ,而且我有理由相信这不是解决方案]

我在 several 中找到的解决方案places涉及 Hook Filter检查架构,如果找到“http”,则使用修改后的 URL 调用 sendRedirect。这涉及对行为进行硬编码以使其始终发生。

如果我扩展 HttpConnectorFactory ,似乎我可以在 YAML 中添加配置以决定是否要进行重定向。但是,我不清楚在不破坏其他代码的情况下添加属性会有多复杂。

这似乎是一项常见的任务;有没有标准的“首选”方法来做到这一点?我希望 Dropwizard 有优雅的内置支持,like Jetty does ,但我找不到它。

最佳答案

我不知道有一个“首选”的方式来做到这一点,但这样的事情怎么样(对于 Dropwizard 0.7.0):

void addHttpsForward(ServletContextHandler handler) {
  handler.addFilter(new FilterHolder(new Filter() {

    public void init(FilterConfig filterConfig) throws ServletException {}

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
      StringBuffer uri = ((HttpServletRequest) request).getRequestURL();
      if (uri.toString().startsWith("http://")) {
        String location = "https://" + uri.substring("http://".length());
        ((HttpServletResponse) response).sendRedirect(location);
      } else {
        chain.doFilter(request, response);
      }
    }

    public void destroy() {}
  }), "/*", EnumSet.of(DispatcherType.REQUEST));
}

@Override
public void run(ExampleConfiguration configuration, Environment environment) throws Exception {
  //...
  if (configuration.forwardHttps()) {
    addHttpsForward(environment.getApplicationContext());
  }
  //...      
}

您只需在应用程序配置中添加一个 boolean 值,然后您就可以使用 YAML 轻松切换 https 转发。

关于java - 在 Dropwizard 中将 http 连接重定向到 https 的首选方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23902576/

相关文章:

java - Java 是否支持像 Lisp 那样基于多个对象的类型分派(dispatch)到特定的实现?

Java 对象数组 Foreach 方法访问

.htaccess : http to https redirection does not work

swift - 在 Swift 5 中禁用 HTTPS GET 证书检查

PHP curl : SSL routines:SSL23_GET_SERVER_HELLO:reason(1112)

java - JXTreeTable、行条纹和适当的重画

java - 为什么 CTRL+C(用 Awt.Robot 模拟)不能正常工作?

jsf - 如何从 JAX-RS 方法重定向到 JSF 页面?

linux - 在我的 htaccess 中重定向导致 503 服务器太忙

ssl - 什么是 SSL,它与 HTTPS 有什么关系?