问题描述:
解决方案:
通过建立过滤器方法
添加拦截器:
web.xml 文件配置拦截器
<filter><filter-name>sqlFilter</filter-name><filter-class>com.fh.filter.SqlFilter</filter-class></filter>
package com.fh.filter;import com.fh.controller.base.BaseController;import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;public class SqlFilter extends BaseController implements Filter {@Overridepublic void init(FilterConfig filterConfig) throws ServletException {}@Overridepublic void destroy() {}@Overridepublic void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {HttpServletRequest req = (HttpServletRequest)request;HttpServletResponse resp = (HttpServletResponse)response;PrintWriter writer = null;Enumeration params = req.getParameterNames();String sql = "";while(params.hasMoreElements()) {String name = params.nextElement().toString();String[] value = req.getParameterValues(name);for(int i=0;i<value.length;i++) {sql = sql+value[i];}}if(sqlValidate(sql)) {System.out.println("发现sql注入");response.setCharacterEncoding("GBK");writer = response.getWriter();writer.print("发现sql注入");return;}chain.doFilter(req,resp);}private boolean sqlValidate(String str) {str = str.toLowerCase();// 统一转为小写String badStr = "|exec|execute|insert|select|delete|update|drop|%|master|truncate|"+ "declare|sitename|net user|xp_cmdshell|like|exec|execute|insert|create|drop|"+ "table|grant|use|group_concat|column_name|information_schema.columns|table_schema|"+ "select|delete|update|master|truncate|declare|-- |like|//|%";// 过滤掉的sql关键字,可以手动添加String[] badStrs = badStr.split("\\|");for (int i = 0; i < badStrs.length; i++) {if (str.indexOf(badStrs[i]) >= 0) {return true;}}return false;}}