HTTP系列之http链接强转为https链接Filter

December 09, 2023
测试
测试
测试
测试
5 分钟阅读
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 {
		
	}

}

继续阅读

更多来自我们博客的帖子

如何安装 BuddyPress
由 测试 December 17, 2023
经过差不多一年的开发,BuddyPress 这个基于 WordPress Mu 的 SNS 插件正式版终于发布了。BuddyPress...
阅读更多
Filter如何工作
由 测试 December 17, 2023
在 web.xml...
阅读更多
如何理解CGAffineTransform
由 测试 December 17, 2023
CGAffineTransform A structure for holding an affine transformation matrix. ...
阅读更多