1.关于springboot中过滤器的实现已经介绍过了。地址:https://blog.csdn.net/qq_38669394/article/details/106926739
2.现在介绍一下 基于过滤器实现长连接转 短链接
需求:公司最近有个需求,需要做一个分享的链接,由于需要记载分享人等信息,分享的链接就有点过长,需要采用短链接分享。
过滤器实现原理:在数据库中保存长链接的时候,同时生成一个十位数的随机字符串,保存随机字符串字段设置唯一索引。项目访问路径+/+十位数随机字符串的形式作为短链接分享出去
当用户点击链接时,获取用户请求的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() {
}
}