现在有这样一个问题,就是在提交大片文字评论的时候,前台拿到数据之后给后台发送ajax请求,然后后台有一个防止SQL注入的Filter,这个Filter得到这个前台传过来的数据之后,进行合法性校验,如果没有校验成功,那么要跳转到error.jsp页面进行显示错误信息。现在让我们看看怎么实现这个需求。
思路一:请求转发实现
ajax请求
$.ajax({ method:'post', url:'servlet/DemoServlet', dataType:'json', data:{ 'userName':userName, 'passWord':passWord, 'text': text }, success:function(data){ //成功之后的逻辑 }, error:function(){ //错误之后的逻辑 } });
防止SQL注入Filter
package com.yiyexiaoyuan.filter; import java.io.IOException; import java.util.Enumeration; import javax.security.auth.message.callback.PrivateKeyCallback.Request; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONObject; //过滤sql关键字的Filter public class SQLFilter implements Filter { public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse res = (HttpServletResponse) response; // 获得所有请求参数名 Enumeration params = req.getParameterNames(); String sql = ""; while (params.hasMoreElements()) { // 得到参数名 String name = params.nextElement().toString(); // System.out.println("name===========================" + name + // "--"); // 得到参数对应值 String[] value = req.getParameterValues(name); for (int i = 0; i < value.length; i++) { sql = sql + value[i]; } } System.out.println("提交方式:"+req.getMethod()); System.out.println("被匹配字符串:" + sql); if (sqlValidate(sql)) { //请求转发 req.getRequestDispatcher("error.jsp"). forward(req, res); } else { String request_uri = req.getRequestURI(); chain.doFilter(request, response); } } // 校验 protected static boolean sqlValidate(String str) { str = str.toLowerCase();// 统一转为小写 // String badStr = "and|exec"; String badStr = "'|and|exec|execute|insert|select|delete|update|count|drop|chr|mid|master|truncate|char|declare|sitename|net user|xp_cmdshell|or|like|;|--|+|,|*|/"; /* * String badStr = * "'|and|exec|execute|insert|create|drop|table|from|grant|use|group_concat|column_name|" * + * "information_schema.columns|table_schema|union|where|select|delete|update|order|by|count|*|" * + "chr|mid|master|truncate|char|declare|or|;|-|--|+|,|like|//|/|%|#"; */// 过滤掉的sql关键字,可以手动添加 String[] badStrs = badStr.split("\\|"); for (int i = 0; i < badStrs.length; i++) { if (str.indexOf(badStrs[i]) != -1) { System.out.println("匹配到:" + badStrs[i]); return true; } } return false; } public void init(FilterConfig filterConfig) throws ServletException { // throw new UnsupportedOperationException("Not supported yet."); } public void destroy() { // throw new UnsupportedOperationException("Not supported yet."); } }
web.xml配置
<filter> <display-name>SQLFilter</display-name> <filter-name>SQLFilter</filter-name> <filter-class>com.yiyexiaoyuan.filter.SQLFilter</filter-class> </filter> <filter-mapping> <filter-name>SQLFilter</filter-name> <url-pattern>/servlet/*</url-pattern> </filter-mapping> <filter>
分析,ajax请求DemoServlet,然后请求先被防止SQL注入这个Filter过滤器先过滤,然后过滤到的请求参数构成一个匹配字符串,然后检查是否是恶意代码,如果是的话,请求转发。但是很遗憾,逻辑上这个是对的,但是ajax请求是局部刷新的,最后是要回到ajax请求发起的这个页面的,所以请求转发不会实现,我们看下一种实现逻辑。
思路二:返回值进行判断
这个思路的逻辑是这样的:在Filter过滤掉信息的时候,给ajax请求回送一个json数据,然后返回给前台,前台拿这个数据进行判断是否是恶意代码和良好代码。再进行下一步的处理。
ajax请求
$.ajax({ method:'post', url:'servlet/DemoServlet', dataType:'json', data:{ 'userName':userName, 'passWord':passWord, 'text': text }, success:function(data){ //成功之后的逻辑 if (data.mssage!=""){ //执行处理恶意代码的逻辑 } else{ } }, error:function(){ //错误之后的逻辑 } });
防止SQL注入的Filter
package com.yiyexiaoyuan.filter; import java.io.IOException; import java.util.Enumeration; import javax.security.auth.message.callback.PrivateKeyCallback.Request; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONObject; //过滤sql关键字的Filter public class SQLFilter implements Filter { public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse res = (HttpServletResponse) response; // 获得所有请求参数名 Enumeration params = req.getParameterNames(); String sql = ""; while (params.hasMoreElements()) { // 得到参数名 String name = params.nextElement().toString(); // System.out.println("name===========================" + name + // "--"); // 得到参数对应值 String[] value = req.getParameterValues(name); for (int i = 0; i < value.length; i++) { sql = sql + value[i]; } } System.out.println("提交方式:"+req.getMethod()); System.out.println("被匹配字符串:" + sql); if (sqlValidate(sql)) { //传送json数据 JSONObject json = new JSONObject(); json.accumulate("message", "恶意代码注入"); res.getWriter().print(json.toString()); } else { String request_uri = req.getRequestURI(); chain.doFilter(request, response); } } // 校验 protected static boolean sqlValidate(String str) { str = str.toLowerCase();// 统一转为小写 // String badStr = "and|exec"; String badStr = "'|and|exec|execute|insert|select|delete|update|count|drop|chr|mid|master|truncate|char|declare|sitename|net user|xp_cmdshell|or|like|;|--|+|,|*|/"; /* * String badStr = * "'|and|exec|execute|insert|create|drop|table|from|grant|use|group_concat|column_name|" * + * "information_schema.columns|table_schema|union|where|select|delete|update|order|by|count|*|" * + "chr|mid|master|truncate|char|declare|or|;|-|--|+|,|like|//|/|%|#"; */// 过滤掉的sql关键字,可以手动添加 String[] badStrs = badStr.split("\\|"); for (int i = 0; i < badStrs.length; i++) { if (str.indexOf(badStrs[i]) != -1) { System.out.println("匹配到:" + badStrs[i]); return true; } } return false; } public void init(FilterConfig filterConfig) throws ServletException { // throw new UnsupportedOperationException("Not supported yet."); } public void destroy() { // throw new UnsupportedOperationException("Not supported yet."); } }
思路三:异常+跳转实现