import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
/** *
* <pre>
* HTTP过滤器,根据请求协议进行过滤,http的都强转到https。注意本类采用lombok的slf4j日志,Servlet要求3.0以上的才可以进行注解定义一个过滤器
* </pre>
* @author Nicky
* @date:2018年01月19日 下午11:55:57
* <pre>
* 修改记录
* 修改后版本: 修改人: 修改日期: 修改内容:
* </pre>
*/
@Slf4j
@WebFilter(filterName="/Http2HttpsFilter",urlPatterns="/*")
public class Http2HttpsFilter implements Filter {
public Http2HttpsFilter() {
}
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest)request;
HttpServletResponse res = (HttpServletResponse)response;
//获取请求协议
String scheme = request.getScheme();
log.info("转换前的链接为:"+req.getRequestURL()+"?"+req.getQueryString());
//http的url换成https的url
try{
if(req.getQueryString()!=null && !"".equals(req.getQueryString())){
reqUri = new URI(req.getRequestURL()+"?"+req.getQueryString());
}else{
reqUri = new URI(req.getRequestURL().toString());
}
newUri = new URI("https", reqUri.getUserInfo(),
reqUri.getHost(), reqUri.getPort(), reqUri.getPath(),
reqUri.getQuery(), reqUri.getFragment());
}catch(URISyntaxException e){
e.printStackTrace();
}
//根据请求协议进行过滤,请求协议为HTTP的都进行过滤
if(scheme.equals("http")){
log.info("转换后的链接为:"+newUri.toString());
//重定向
res.sendRedirect(newUri.toString());
// res.sendRedirect(sbd.toString());
//chain.doFilter(req, res);
return;
}else{
chain.doFilter(req, res);
}
}
@Override
public void init(FilterConfig fConfig) throws ServletException {
}
}