spring 自定义空值过滤链

对接口进行统一的拦截,判断是否携带参数,携带的参数是否为空:

package com.gyk.xyt.chat.filter;

import javax.servlet.*;
import java.io.IOException;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;
import javax.servlet.annotation.WebFilter;

import org.apache.catalina.connector.RequestFacade;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;

/**
 * 轮子哥
 * 2023/3/21
 * 自定义空值过滤链
 */

@Component
@WebFilter(filterName = "nullFilter", urlPatterns = "/*")
public class NullFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //获取请求路径
        String requestUri = ((RequestFacade) request).getRequestURI();
        System.out.println(requestUri);
        //设置白名单路径
        String[] allowPath = {"/ws/emptyError", "/ws/getOnlineNum","/ws/WebSocket/*","/ws/sendImg"};
        //使用PathMatcher进行通配符路径匹配
        PathMatcher matcher = new AntPathMatcher();
        boolean isAllow =false;
        for (String url:allowPath) {
            //匹配则设置true
            isAllow=matcher.match(url, requestUri);
            if (isAllow){
                break;
            }
        }
        System.out.println(isAllow);
        //是否为空
        boolean isNull = false;
        //获取请求参数
        Map<String, String[]> parameterMap = request.getParameterMap();
        //获取请求参数的key
        Set<String> keys = parameterMap.keySet();
        if (isAllow) {
            //在白名单路径中,进行放行
            chain.doFilter(request, response);
        } else {
            //判断是否没有参数
            if (keys.toArray().length == 0) {
                isNull = true;
            }
            //判断参数是否为空
            for (String key : keys) {
                String[] value = parameterMap.get(key);
                if (Arrays.toString(value).equals("[]")) {
                    isNull = true;
                }
            }
            if (isNull) {
                //请求参数为空,进行拦截跳转到指定接口返回
                request.getRequestDispatcher("/ws/emptyError").forward(request, response);
            } else {
                //请求参数不为空,放行
                chain.doFilter(request, response);
            }
        }

    }

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


}

/ws/emptyError 接口:

    /**
     * 空值返回
     */
    @RequestMapping("/emptyError")
    public Map<String, Object> emptyError(){
        Map<String,Object> map=new HashMap<>();
        map.put("code",400);
        map.put("message","非法请求");
        return map;
    }

猜你喜欢

转载自blog.csdn.net/qq_46149597/article/details/129694571