springboot项目防止sql注入

原文地址:https://blog.csdn.net/weixin_39728880/article/details/101029681

 

在项目中我们经常会遇到这些sql注入的问题,这边我介绍的是通过filter拦截的方式进行过滤一些sql脚本的注入,在平时编程的时候我们也要注意,在程序中编写sql脚本(mapper.xml) 文件的时候能用#尽量用#,避免一个恶意攻击网站的人。

首先介绍一下#和$的区别:

  1. #{}:占位符号,好处防止sql注入,自带单引号变量
  2. ${}:sql拼接符号,原生变量

接下来介绍写在java项目中(springboot)如何通过webFilter防止sql注入:  

 

/**

* sql注入过滤器
*/
@Component
@WebFilter(urlPatterns = "/*", filterName = "SQLInjection", initParams = { @WebInitParam(name = "regx", value = "(?:')|(?:--)|(/\\*(?:.|[\\n\\r])*?\\*/)|" +
"(\\b(select|update|and|or|delete|insert|trancate|char|into|substr|ascii|declare|exec|count|master|into|drop|execute)\\b)") })
public class SqlInjectFilter implements Filter{

  private String regx;

  @Override

  public void init(FilterConfig filterConfig) throws ServletException {

    this.regx = filterConfig.getInitParameter("regx");

  }

  @Override

  public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

    HttpServletRequest req = (HttpServletRequest) servletRequest;

    Map parametersMap = servletRequest.getParameterMap();

    Iterator it = parametersMap.entrySet().iterator();

    while (it.hasNext()) {

      Map.Entry entry = (Map.Entry) it.next();

      String[] value = (String[]) entry.getValue();

      for (int i = 0; i < value.length; i++) {

        if (null != value[i] && value[i].matches(this.regx)) {

          log.error("您输入的参数有非法字符,请输入正确的参数!");

          servletRequest.setAttribute("err", "您输入的参数有非法字符,请输入正确的参数!");

          servletRequest.setAttribute("pageUrl",req.getRequestURI());

          servletRequest.getRequestDispatcher(servletRequest.getServletContext().getContextPath() + "/error").forward(servletRequest, servletResponse);

          return;

        }

      }

    }

  }

  filterChain.doFilter(servletRequest, servletResponse);

 }

  @Override

  public void destroy() {

  }

}

 

启动类上记得加注解:

@ServletComponentScan(basePackages ="xxxx.xxx.xxx.filter") //filter所在的包,扫描
posted @ 2020-10-29 20:57  韩小陌  阅读(6779)  评论(0编辑  收藏  举报