Ajax请求和Filter配合案例解析
案例引入
现在有这样一个问题,就是在提交大片文字评论的时候,前台拿到数据之后给后台发送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."); } }
思路三:异常+跳转实现
这个思路的逻辑是这样的。后台的filter过滤掉恶意注入代码的话,抛出runtimeexception(),然后导致ajax请求失败,然后回调ajax请求的error方法。但是我们错误页面的数据怎么传送过去呢?经过我认真思考之后,我们可以这样做,在session存一个error_messgae值,然后ajax请求的error方法跳转到错误页面,然后进行取值渲染错误页面。
ajax请求
$.ajax({ method:'post', url:'servlet/demoservlet', datatype:'json', data:{ 'username':username, 'password':password, 'text': text }, success:function(data){ //成功之后的逻辑 }, error:function(){ window.location.href="error.jsp"; } });
防止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.getsession().setattribute("error_message","恶意注入了"); throw new runtimeexception("恶意注入"); } 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."); } }
error.jsp实现
<%@ page language="java" import="java.util.*" pageencoding="utf-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <% string path = request.getcontextpath(); string basepath = request.getscheme()+"://"+request.getservername()+":"+request.getserverport()+path+"/"; %> <!doctype html public "-//w3c//dtd html 4.01 transitional//en"> <html> <head> <base href="<%=basepath%>"> <title>错误页面</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="this is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <center> 系统出错了,请稍后再试...... <br /> <br /> <br /> <br /> 错误信息是: ${ error_message} </center> </body> </html>
这样就很巧妙得实现了filter拦截并友好提示。
以上所述是小编给大家介绍的ajax请求和filter配合案例解析,希望对大家有所帮助