這篇文章主要為大家展示了“Ajax請(qǐng)求和Filter配合的示例分析”,內(nèi)容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領(lǐng)大家一起研究并學(xué)習(xí)一下“Ajax請(qǐng)求和Filter配合的示例分析”這篇文章吧。
網(wǎng)站建設(shè)哪家好,找創(chuàng)新互聯(lián)建站!專注于網(wǎng)頁設(shè)計(jì)、網(wǎng)站建設(shè)、微信開發(fā)、微信平臺(tái)小程序開發(fā)、集團(tuán)企業(yè)網(wǎng)站建設(shè)等服務(wù)項(xiàng)目。為回饋新老客戶創(chuàng)新互聯(lián)還提供了蘇仙免費(fèi)建站歡迎大家使用!
案例引入
現(xiàn)在有這樣一個(gè)問題,就是在提交大片文字評(píng)論的時(shí)候,前臺(tái)拿到數(shù)據(jù)之后給后臺(tái)發(fā)送ajax請(qǐng)求,然后后臺(tái)有一個(gè)防止SQL注入的Filter,這個(gè)Filter得到這個(gè)前臺(tái)傳過來的數(shù)據(jù)之后,進(jìn)行合法性校驗(yàn),如果沒有校驗(yàn)成功,那么要跳轉(zhuǎn)到error.jsp頁面進(jìn)行顯示錯(cuò)誤信息?,F(xiàn)在讓我們看看怎么實(shí)現(xiàn)這個(gè)需求。
思路一:請(qǐng)求轉(zhuǎn)發(fā)實(shí)現(xiàn)
ajax請(qǐng)求
$.ajax({ method:'post', url:'servlet/DemoServlet', dataType:'json', data:{ 'userName':userName, 'passWord':passWord, 'text': text }, success:function(data){ //成功之后的邏輯 }, error:function(){ //錯(cuò)誤之后的邏輯 } });
防止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關(guān)鍵字的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; // 獲得所有請(qǐng)求參數(shù)名 Enumeration params = req.getParameterNames(); String sql = ""; while (params.hasMoreElements()) { // 得到參數(shù)名 String name = params.nextElement().toString(); // System.out.println("name===========================" + name + // "--"); // 得到參數(shù)對(duì)應(yīng)值 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)) { //請(qǐng)求轉(zhuǎn)發(fā) req.getRequestDispatcher("error.jsp"). forward(req, res); } else { String request_uri = req.getRequestURI(); chain.doFilter(request, response); } } // 校驗(yàn) protected static boolean sqlValidate(String str) { str = str.toLowerCase();// 統(tǒng)一轉(zhuǎn)為小寫 // 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關(guān)鍵字,可以手動(dòng)添加 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配置
SQLFilter SQLFilter com.yiyexiaoyuan.filter.SQLFilter SQLFilter /servlet/*
分析,ajax請(qǐng)求DemoServlet,然后請(qǐng)求先被防止SQL注入這個(gè)Filter過濾器先過濾,然后過濾到的請(qǐng)求參數(shù)構(gòu)成一個(gè)匹配字符串,然后檢查是否是惡意代碼,如果是的話,請(qǐng)求轉(zhuǎn)發(fā)。但是很遺憾,邏輯上這個(gè)是對(duì)的,但是ajax請(qǐng)求是局部刷新的,最后是要回到ajax請(qǐng)求發(fā)起的這個(gè)頁面的,所以請(qǐng)求轉(zhuǎn)發(fā)不會(huì)實(shí)現(xiàn),我們看下一種實(shí)現(xiàn)邏輯。
思路二:返回值進(jìn)行判斷
這個(gè)思路的邏輯是這樣的:在Filter過濾掉信息的時(shí)候,給ajax請(qǐng)求回送一個(gè)json數(shù)據(jù),然后返回給前臺(tái),前臺(tái)拿這個(gè)數(shù)據(jù)進(jìn)行判斷是否是惡意代碼和良好代碼。再進(jìn)行下一步的處理。
ajax請(qǐng)求
$.ajax({ method:'post', url:'servlet/DemoServlet', dataType:'json', data:{ 'userName':userName, 'passWord':passWord, 'text': text }, success:function(data){ //成功之后的邏輯 if (data.mssage!=""){ //執(zhí)行處理惡意代碼的邏輯 } else{ } }, error:function(){ //錯(cuò)誤之后的邏輯 } });
防止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關(guān)鍵字的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; // 獲得所有請(qǐng)求參數(shù)名 Enumeration params = req.getParameterNames(); String sql = ""; while (params.hasMoreElements()) { // 得到參數(shù)名 String name = params.nextElement().toString(); // System.out.println("name===========================" + name + // "--"); // 得到參數(shù)對(duì)應(yīng)值 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數(shù)據(jù) JSONObject json = new JSONObject(); json.accumulate("message", "惡意代碼注入"); res.getWriter().print(json.toString()); } else { String request_uri = req.getRequestURI(); chain.doFilter(request, response); } } // 校驗(yàn) protected static boolean sqlValidate(String str) { str = str.toLowerCase();// 統(tǒng)一轉(zhuǎn)為小寫 // 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關(guān)鍵字,可以手動(dòng)添加 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."); } }
思路三:異常+跳轉(zhuǎn)實(shí)現(xiàn)
這個(gè)思路的邏輯是這樣的。后臺(tái)的Filter過濾掉惡意注入代碼的話,拋出RuntimeException(),然后導(dǎo)致ajax請(qǐng)求失敗,然后回調(diào)ajax請(qǐng)求的error方法。但是我們錯(cuò)誤頁面的數(shù)據(jù)怎么傳送過去呢?經(jīng)過我認(rèn)真思考之后,我們可以這樣做,在session存一個(gè)error_messgae值,然后ajax請(qǐng)求的error方法跳轉(zhuǎn)到錯(cuò)誤頁面,然后進(jìn)行取值渲染錯(cuò)誤頁面。
ajax請(qǐng)求
$.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關(guān)鍵字的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; // 獲得所有請(qǐng)求參數(shù)名 Enumeration params = req.getParameterNames(); String sql = ""; while (params.hasMoreElements()) { // 得到參數(shù)名 String name = params.nextElement().toString(); // System.out.println("name===========================" + name + // "--"); // 得到參數(shù)對(duì)應(yīng)值 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); } } // 校驗(yàn) protected static boolean sqlValidate(String str) { str = str.toLowerCase();// 統(tǒng)一轉(zhuǎn)為小寫 // 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關(guān)鍵字,可以手動(dòng)添加 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實(shí)現(xiàn)
<%@ 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+"/"; %>"> 錯(cuò)誤頁面 系統(tǒng)出錯(cuò)了,請(qǐng)稍后再試......
錯(cuò)誤信息是: ${ error_message}
這樣就很巧妙得實(shí)現(xiàn)了Filter攔截并友好提示。
以上是“Ajax請(qǐng)求和Filter配合的示例分析”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!