目录
目的
核心方法
完整代码
创建拦截器
注册拦截器
测试效果
目的
在Springboot中创建拦截器拦截所有GET类型请求,获取请求参数验证内容合法性防止SQL注入(该方法仅适用拦截GET类型请求,POST类型请求参数是在body中,所以下面方法不适用)。
核心方法
1、拦截 http://127.0.0.1:8088/api/checkTechCertInfoCancel?name=ljh 类型:
Map<String, String[]> parameterMap = request.getParameterMap();
2、拦截 http://127.0.0.1:8088/api/checkTechCertInfoCancel/ljh 类型:
Map<String, String> pathVariables = (Map<String, String>) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
完整代码
创建拦截器
import com.alibaba.fastjson.JSON;
import com.boc.ljh.utils.Result;
import com.boc.ljh.utils.status.AppErrorCode;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.ModelAndView;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;/*** @Author: ljh* @ClassName SqlInterceptor* @Description 拦截器 用于拦截GET请求校验参数内容* @date 2023/8/9 10:12* @Version 1.0*/
@Component
public class SqlInterceptor implements HandlerInterceptor {/*** @Author: ljh* @Description: 在controller前拦截请求* @DateTime: 10:38 2023/8/9* @Params:* @Return*/@Overridepublic boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {System.err.println(request.getMethod());if (request.getMethod().equals("GET") && request.getRequestURI().contains("?")) {//获取EGT请求中的参数,例如http://127.0.0.1:8088/api/checkTechCertInfoCancel?name=ljh 请求中的参数ljhMap<String, String[]> parameterMap = request.getParameterMap();for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {String[] value = entry.getValue();for (String s : value) {//校验参数值是否合法if (verifySql(s)) {response.setContentType("application/json;charset=utf-8");Result result = new Result();result.setMessage("请求参数中含有非法字符!请检查重新输入");result.setStatus(500);response.getWriter().write(JSON.toJSONString(result));return false;}}}} else {//获取EGT请求中的参数,例如http://127.0.0.1:8088/api/checkTechCertInfoCancel/ljh 请求中的参数ljhMap<String, String> pathVariables = (Map<String, String>) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);for (String key : pathVariables.keySet()) {//校验参数值是否合法if (verifySql(pathVariables.get(key))) {//返回错误提示response.setContentType("application/json;charset=utf-8");Result result = new Result();result.setMessage("请求参数中含有非法字符!请检查重新输入");result.setStatus(500);response.getWriter().write(JSON.toJSONString(result));return false;}}}return true;}//处理请求完成后视图渲染之前的处理操作@Overridepublic void postHandle(HttpServletRequest request,HttpServletResponse response, Object handler,ModelAndView modelAndView) throws Exception {// TODO Auto-generated method stub}//视图渲染之后的操作@Overridepublic void afterCompletion(HttpServletRequest request,HttpServletResponse response, Object handler, Exception ex)throws Exception {// TODO Auto-generated method stub}/*** @Author: ljh* @Description: 校验非法字符* @DateTime: 11:15 2023/8/9* @Params:* @Return*/public boolean verifySql(String parameter) {String s = parameter.toLowerCase();// 过滤掉的sql关键字,特殊字符前面需要加\\进行转义String badStr ="select|update|and|or|delete|insert|truncate|char|into|substr|ascii|declare|exec|count|master|into|drop|execute|table|" +"char|declare|sitename|xp_cmdshell|like|from|grant|use|group_concat|column_name|" +"information_schema.columns|table_schema|union|where|order|by|" +"'\\*|\\;|\\-|\\--|\\+|\\,|\\//|\\/|\\%|\\#";//使用正则表达式进行匹配boolean matches = s.matches(badStr);return matches;}
注册拦截器
/*** @Author: ljh* @ClassName MvcInterceptorConfig* @Description 注册SqlInterceptor拦截器到容器中* @date 2023/8/9 10:21* @Version 1.0*/import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;@Configuration
public class MvcInterceptorConfig implements WebMvcConfigurer {@Overridepublic void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(new SqlInterceptor()) //需要注册到容器中的拦截器.addPathPatterns("/**"); //所有请求都被拦截,静态资源也被拦截
// .excludePathPatterns("/", "/login", "/css/**", "/fonts/**", "/images/**", "/js/**"); // 放行的请求}}
测试效果
请求内容合法:
请求内容不合法:
Springboot中使用过滤器校验PSOT类型请求参数内容https://blog.csdn.net/weixin_45151960/article/details/132187495?spm=1001.2014.3001.5501