基于过滤器 实现长链接转短链接

1.关于springboot中过滤器的实现已经介绍过了。地址:https://blog.csdn.net/qq_38669394/article/details/106926739

2.现在介绍一下 基于过滤器实现长连接转 短链接

 需求:公司最近有个需求,需要做一个分享的链接,由于需要记载分享人等信息,分享的链接就有点过长,需要采用短链接分享。

长链接:https://*****/starposmall/pages/coupon/couponCenter?couponId=***2020061011252621932&storeId=DS2020061615452442820&sn=800301000018371

短链接:https://url.cn/g9Mo5***

过滤器实现原理:在数据库中保存长链接的时候,同时生成一个十位数的随机字符串,保存随机字符串字段设置唯一索引。项目访问路径+/+十位数随机字符串的形式作为短链接分享出去

当用户点击链接时,获取用户请求的url,如果用户点击短链接,可以获取到最后一个 / 后的字符串,使用字符串查询数据库,如果存在长链接,重定向到长链接地址,不存在,直接放行。

代码实现:一般我们会有一个专门的服务作为短链服务,这样不会影响主项目请求,也就不存在不存在的情况了。

package com.newland.marketmanage.webservice.filter;



import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.newland.marketmanage.webservice.v1.common.SpringContextHolder;
import com.newland.marketmanage.webservice.v1.wuliao.impl.WuLiaoV1ServiceImpl;
import com.newland.marketmanage.webservice.v1.wuliao.model.RobotInfo;
import com.newland.marketmanage.wuliao.dao.impl.RobotInfoDaoImpl;

import java.io.IOException;

public class ShortUrlFilter implements Filter{

	private Logger logger = LoggerFactory.getLogger(WuLiaoV1ServiceImpl.class);
	//这里我是通过spring getBean的方式获取Service层对象 查询长链接
	RobotInfoDaoImpl robotInfoDaoImpl = SpringContextHolder.getBean(RobotInfoDaoImpl.class);
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    

    }
    
	@SuppressWarnings("unlikely-arg-type")
	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpSession session = request.getSession(false);
        String uri = request.getRequestURI();
        logger.info("uri"+uri);
        //获取 / 后的字符串
        String short_url = uri.substring(uri.lastIndexOf("/")+1);;
        
        //通过短链字符串 查 长链 是否需要过滤
       RobotInfo robotInfo = robotInfoDaoImpl.findByShortUrl(short_url);
        //通过uri查询数据库是否存在映射,不存在 直接进入下个过滤器
        if (robotInfo == null) { //不需要过滤直接传给下一个过滤器
            filterChain.doFilter(servletRequest, servletResponse);
        	
            
        }else{
                    //存在重定向到映射的路径
          //   response.sendRedirect(request.getContextPath()+robotInfo.getCouponUrl());
        	response.sendRedirect(robotInfo.getCouponUrl());
                return;
            }
        }

	 
	    @Override
	    public void destroy() {

	    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值