Java 防止SQL注入
作者:互联网
package com.filter; import com.utils.StringUtils; import org.springframework.stereotype.Component; import javax.servlet.*; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import java.io.IOException; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; /** * sql注入过滤器 */ @Component @WebFilter(urlPatterns = "/*", filterName = "SQLInjection") public class SqlInjectFilter implements Filter { private static String regx = "(?:')|(?:--)|(/\\*(?:.|[\\n\\r])*?\\*/)|(\\b(select|update|and|or|delete|insert|trancate|char|into|substr|ascii|declare|exec|count|master|into|drop|execute)\\b)"; private static Set<String> notAllowedKeyWords = new HashSet<String>(0); private static String replacedString = "INVALID"; static { String keyStr[] = regx.split("\\|"); for (String str : keyStr) { notAllowedKeyWords.add(str); } } @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] && checkSqlKeyWords(value[i])) {
/*可根据业务场景切换*/ value[i] = cleanSqlKeyWords(value[i]); // servletRequest.setAttribute("err", "您输入的参数有非法字符,请输入正确的参数!"); // servletRequest.setAttribute("pageUrl", req.getRequestURI()); // servletRequest.getRequestDispatcher(servletRequest.getServletContext().getContextPath() + "/error").forward(servletRequest, servletResponse); // return ; } } } filterChain.doFilter(servletRequest,servletResponse); } private String cleanSqlKeyWords(String value){ String paramValue = value; for (String keyWord : notAllowedKeyWords) { if (paramValue.length() > keyWord.length() && (paramValue.contains(" "+keyWord)||paramValue.contains(keyWord+" ")||paramValue.contains(" "+keyWord+" ")||paramValue.contains(keyWord))) { paramValue = paramValue.replace(keyWord,""); } } return paramValue; } public boolean checkSqlKeyWords(String value){ String paramValue = value; for (String keyword : notAllowedKeyWords) { if (paramValue.length() > keyword.length() && (paramValue.contains(" "+keyword)||paramValue.contains(keyword+" ")||paramValue.contains(" "+keyword+" ")||paramValue.contains(keyword))) { return true; } } return false; } @Override public void destroy(){ } }
标签:Java,String,contains,value,paramValue,SQL,import,servletRequest,注入 来源: https://www.cnblogs.com/yyhhblog/p/15211847.html