案例描述
自定义拦截器,过滤前端传递的参数是否合法
实现思路
添加自定义拦截器
实现自定义参数过滤
操作步骤
1. 创建自定义拦截器MyCustomerFilter
package com.je.filter;
import com.je.core.base.JERequestWrapper;
import com.je.core.exception.PlatformException;
import com.je.core.exception.PlatformExceptionEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
/**
* 自定义过滤器
*/
public class MyCustomerFilter extends OncePerRequestFilter {
private static final Logger logger = LoggerFactory.getLogger(MyCustomerFilter.class);
private static final String[] STRS = new String[]{
"1",
"2",
"3",
"4"
};
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
//请求路径
String uri = request.getRequestURI();
//前端传递的参数
Map<String, String[]> parameters = request.getParameterMap();
//包装Request
JERequestWrapper requestWrapper = new JERequestWrapper(request);
//是否合法
Boolean isJustifiability = true;
for (String str : parameters.keySet()) {
//拿到参数值,进行校验
String[] value = parameters.get(str);
//自定义判断是否合法
if (value 不合法){
isJustifiability = false;
break;
}
}
if (!isJustifiability) {
//可以自定义一个异常信息
logger.info("参数不合法,url={}", uri);
throw new PlatformException("参数不合法,url" + uri, PlatformExceptionEnum.UNKOWN_ERROR, new Object[]{uri, request.getParameterMap()});
}
//继续执行
filterChain.doFilter(requestWrapper, response);
}
}
2. 添加自定义拦截器配置
打开web.xml,添加自定义拦截器,一般自定义的拦截器需要添加到解密拦截器之后
最后编辑: 于春辉 文档更新时间: 2024-08-21 10:58 作者:于春辉