SpringBoot中如何处理Filter抛出的异常
package com.chinachg.tbsp.filters;
import com.chinachg.tbsp.utils.IpUtil;
import com.chinachg.tbsp.utils.aware.CustomerAware;
import com.chinachg.tbsp.utils.exception.IpException;
import com.chinachg.tbsp.utils.exception.IpNotAllowedException;
import com.chinachg.tbsp.utils.redis.RedisUtil;
import com.chinachg.tbsp.utils.values.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.util.CollectionUtils;
import org.springframework.web.servlet.HandlerExceptionResolver;
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.List;
/**
* @Author Christy
* @DESC
* @Date 2020/12/9 16:56
**/
@WebFilter(urlPatterns = "/*", filterName = "ipNotAllowedFilter")
@Slf4j
public class IpFilter implements Filter {
private RedisUtil redisUtil;
/** 在Filter中注入HandlerExceptionResolver **/
@Autowired
@Qualifier("handlerExceptionResolver")
private HandlerExceptionResolver resolver;
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
redisUtil = CustomerAware.getBean(RedisUtil.class);
//先获取相关需要验证的ip列表
//过滤ip,若用户在白名单内,则放行
String ipAddress = IpUtil.getRealIP(request);
//所用需要验证的ip,暂时批量验证
List<Object> objectList = redisUtil.lGetAll(Constants.REDIS_IP_ADDRESS_LIST_KEY);
if (!CollectionUtils.isEmpty(objectList)){
List<String> ipAddressList = (List<String>)(List)objectList.get(0);
if(!ipAddressList.contains(ipAddress)){
log.error("{}禁止访问",ipAddress);
/** 通过HandlerExceptionResolver抛出可被全局异常处理捕获到的异常 **/
resolver.resolveException(request, response, null, new IpNotAllowedException(403,"当前IP无权访问"));
return;
}
}
filterChain.doFilter(request, response);
}
}
参考文章来源:https://blog.csdn.net/bbxylqf126com/article/details/110948838
https://blog.csdn.net/qq_40058629/article/details/112857305
本作品采用 知识共享署名-相同方式共享 4.0 国际许可协议 进行许可。