我确信这段代码可以稍微修饰一下,它可能会错过一些极端情况,但这里有一个通用的 servlet 过滤器,它将所有http
流量重定向到https
:
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class SecureFilter implements Filter {
public void init(FilterConfig arg0) throws ServletException {}
public void destroy() {}
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest hr = (HttpServletRequest) req;
HttpServletResponse hs = (HttpServletResponse) res;
if(req.isSecure() ||
(hr.getHeader("X-Forwarded-Proto")!=null &&
hr.getHeader("X-Forwarded-Proto").equals("https"))) {
chain.doFilter(req,res);
} else {
hs.sendRedirect("https://"+
hr.getHeader("Host")+
hr.getRequestURI()+
(hr.getQueryString()!=null? "?"+hr.getQueryString():""));
}
}
}
通过在中插入以下内容将其添加到您的应用程序中web.xml
:
<filter>
<filter-name>SecureFilter</filter-name>
<filter-class>SecureFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SecureFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>