java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringBoot项目接口过滤

SpringBoot过滤器实现项目内接口过滤详解

作者:黑子桑

这篇文章主要为大家详细介绍了SpringBoot如何利用过滤器实现项目内接口过滤,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起了解一下

业务

由于业务需求,存在两套项目,一套是路由中心,一套是业务系统.

现在存在问题是,路由中心集成了微信公众号与小程序模块功能,业务系统部署了多套服务.

现在需要通过调用路由中心将接口重新路由到指定的业务系统中

需要处理的问题

公众号用户信息与业务系统做绑定

处理步骤

业务系统存在手机号,如果用户注册将手机号发送给路由中心记录

将路由中心的接口与业务系统的接口判断

处理步骤

1.获取路由中心系统中接口映射

    private static List<String> URLS = new ArrayList<>();
    @Resource
    private WebApplicationContext applicationContext;
	
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        applicationContext
		.getBean(RequestMappingHandlerMapping.class)
		.getHandlerMethods()
		.forEach((k, v) -> { k.getPatternsCondition().getPatterns().stream().forEach(s-> URLS.add(s)); });
        log.info("过滤器初始化");
    }

2.获取请求接口路径

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestName = request.getRequestURI();

3.判断是否是路由中心的接口

        if (URLS.contains(requestName)) {
		//系统接口
            chain.doFilter(servletRequest, servletResponse);
        } else {
		//业务系统接口 需要代理
//            代理请求
            ResponseEntity<String> redirect = routerService.redirect(request, response, "xxx", "xxx");
            //设置将字符以"UTF-8"编码输出到客户端浏览器
            response.setCharacterEncoding("UTF-8");
            //通过设置响应头控制浏览器以UTF-8的编码显示数据,如果不加这句话,那么浏览器显示的将是乱码
            response.setHeader("content-type", "application/json; charset=utf-8");
            response.getWriter().write(redirect.getBody());
        }

全部代码

import com.jyw.router.miniapp.service.IRouterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.ResponseEntity;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 沈峻
 * @ClassName RouterFilter
 * @Description TODO
 * @Date 2023/4/20 12:23
 **/
@Configuration
@WebFilter(urlPatterns = "/*", filterName = "Router")
@Slf4j
public class RouterFilter implements Filter {

    private static List<String> URLS = new ArrayList<>();
    @Resource
    private WebApplicationContext applicationContext;

    @Resource
    private IRouterService routerService;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        applicationContext.getBean(RequestMappingHandlerMapping.class).getHandlerMethods().forEach((k, v) -> { k.getPatternsCondition().getPatterns().stream().forEach(s-> URLS.add(s)); });
        log.info("过滤器初始化");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestName = request.getRequestURI();

        /*顺手解决跨域问题*/
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");

        log.info(requestName);
        if (URLS.contains(requestName)) {
            chain.doFilter(servletRequest, servletResponse);
        } else {
//            代理请求
            ResponseEntity<String> redirect = routerService.redirect(request, response, "http://192.168.2.18/api", "/router");


            //设置将字符以"UTF-8"编码输出到客户端浏览器
            response.setCharacterEncoding("UTF-8");
            //通过设置响应头控制浏览器以UTF-8的编码显示数据,如果不加这句话,那么浏览器显示的将是乱码
            response.setHeader("content-type", "application/json; charset=utf-8");
            response.getWriter().write(redirect.getBody());
        }
        log.info("--------------------------------------------------------");
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }

代理转发实现

spring boot实现超轻量级网关的方法(反向代理、转发)

到此这篇关于SpringBoot过滤器实现项目内接口过滤详解的文章就介绍到这了,更多相关SpringBoot项目接口过滤内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文