2016-07-07 76 views
0

我想將http重定向到https,我找到的解決方案是使用過濾器來實現,我已經實現了用於將http協議重定向到https 的過濾器,但是當我嘗試打開網站,我得到谷歌的錯誤, 「嘗試: 重裝 頁面清除Cookie ERR_TOO_MANY_REDIRECTS」使用過濾器不工作將HTTP重定向到HTTPS

我不限於使用過濾器,如果有其他的方法可以解決以上,請註明他們

public class HTTPSFilter implements Filter { 

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws java.io.IOException, ServletException { 

     HttpServletRequest req = (HttpServletRequest) request; 
     HttpServletResponse res = (HttpServletResponse) response; 

     String uri = req.getRequestURI(); 
     String getProtocol = req.getScheme(); 
     String getDomain = req.getServerName(); 
     String getPort = Integer.toString(req.getServerPort()); 

     if (getProtocol.toLowerCase().equals("http")) { 

      // Set response content type 
      response.setContentType("text/html"); 

      // New location to be redirected 
      String httpsPath = "https" + "://" + getDomain + uri; 

      String site = new String(httpsPath); 
      res.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY); 
      res.setHeader("Location", site); 
     } 

     // Pass request back down the filter chain 
     chain.doFilter(req, res); 

    } 

    @Override 
    public void init(FilterConfig arg0) throws ServletException { 
     // TODO Auto-generated method stub 

    } 

    @Override 
    public void destroy() { 
     // TODO Auto-generated method stub 

    } 

} 

web.xml

<filter> 
     <filter-name>HTTPS</filter-name> 
     <filter-class>com.simsarak.filters.HTTPSFilter</filter-class> 
    </filter> 
    <filter-mapping> 
     <filter-name>HTTPS</filter-name> 
     <url-pattern>/*</url-pattern> 
    </filter-mapping> 
+0

我試圖修改服務器上的文件.htacess,也嘗試添加了「<安全約束>」我的web.xml中,最後使用上的cPanel重定向,但沒有一次成功 –

+0

我已經安裝SSL和使用https://訪問站點工作正常,但我想重定向http https –

+0

也嘗試過,但最終服務器支持團隊告訴我必須以編程方式完成 –

回答

0

修改過濾器如下。您無需將StatusLocation header設置爲response.sendRedirect()應該照顧它。

public class HTTPSFilter implements Filter { 

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws java.io.IOException, ServletException { 

     HttpServletRequest req = (HttpServletRequest) request; 
     HttpServletResponse res = (HttpServletResponse) response; 

     String uri = req.getRequestURI(); 
     String getProtocol = req.getScheme(); 
     String getDomain = req.getServerName(); 
     String getPort = Integer.toString(req.getServerPort()); 

     if (getProtocol.toLowerCase().equals("http")) { 
      // New location to be redirected 
      String httpsPath = "https" + "://" + getDomain + uri; 
      //redirect 
      res.sendRedirect(httpsPath); 
     } else { 
      chain.doFilter(req, res); 
     } 
    } 

    @Override 
    public void init(FilterConfig arg0) throws ServletException { 
     // TODO Auto-generated method stub 

    } 

    @Override 
    public void destroy() { 
     // TODO Auto-generated method stub 

    } 

}