您好,登錄后才能下訂單哦!
這篇文章主要為大家展示了“Ajax請求和Filter配合的示例分析”,內(nèi)容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領(lǐng)大家一起研究并學習一下“Ajax請求和Filter配合的示例分析”這篇文章吧。
案例引入
現(xiàn)在有這樣一個問題,就是在提交大片文字評論的時候,前臺拿到數(shù)據(jù)之后給后臺發(fā)送ajax請求,然后后臺有一個防止SQL注入的Filter,這個Filter得到這個前臺傳過來的數(shù)據(jù)之后,進行合法性校驗,如果沒有校驗成功,那么要跳轉(zhuǎn)到error.jsp頁面進行顯示錯誤信息?,F(xiàn)在讓我們看看怎么實現(xiàn)這個需求。
思路一:請求轉(zhuǎn)發(fā)實現(xiàn)
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關(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; // 獲得所有請求參數(shù)名 Enumeration params = req.getParameterNames(); String sql = ""; while (params.hasMoreElements()) { // 得到參數(shù)名 String name = params.nextElement().toString(); // System.out.println("name===========================" + name + // "--"); // 得到參數(shù)對應值 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)) { //請求轉(zhuǎn)發(fā) 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();// 統(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)鍵字,可以手動添加 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過濾器先過濾,然后過濾到的請求參數(shù)構(gòu)成一個匹配字符串,然后檢查是否是惡意代碼,如果是的話,請求轉(zhuǎn)發(fā)。但是很遺憾,邏輯上這個是對的,但是ajax請求是局部刷新的,最后是要回到ajax請求發(fā)起的這個頁面的,所以請求轉(zhuǎn)發(fā)不會實現(xiàn),我們看下一種實現(xiàn)邏輯。
思路二:返回值進行判斷
這個思路的邏輯是這樣的:在Filter過濾掉信息的時候,給ajax請求回送一個json數(shù)據(jù),然后返回給前臺,前臺拿這個數(shù)據(jù)進行判斷是否是惡意代碼和良好代碼。再進行下一步的處理。
ajax請求
$.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(){ //錯誤之后的邏輯 } });
防止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; // 獲得所有請求參數(shù)名 Enumeration params = req.getParameterNames(); String sql = ""; while (params.hasMoreElements()) { // 得到參數(shù)名 String name = params.nextElement().toString(); // System.out.println("name===========================" + name + // "--"); // 得到參數(shù)對應值 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); } } // 校驗 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)鍵字,可以手動添加 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)實現(xiàn)
這個思路的邏輯是這樣的。后臺的Filter過濾掉惡意注入代碼的話,拋出RuntimeException(),然后導致ajax請求失敗,然后回調(diào)ajax請求的error方法。但是我們錯誤頁面的數(shù)據(jù)怎么傳送過去呢?經(jīng)過我認真思考之后,我們可以這樣做,在session存一個error_messgae值,然后ajax請求的error方法跳轉(zhuǎn)到錯誤頁面,然后進行取值渲染錯誤頁面。
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關(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; // 獲得所有請求參數(shù)名 Enumeration params = req.getParameterNames(); String sql = ""; while (params.hasMoreElements()) { // 得到參數(shù)名 String name = params.nextElement().toString(); // System.out.println("name===========================" + name + // "--"); // 得到參數(shù)對應值 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();// 統(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)鍵字,可以手動添加 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實現(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+"/"; %> <!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> 系統(tǒng)出錯了,請稍后再試...... <br /> <br /> <br /> <br /> 錯誤信息是: ${ error_message} </center> </body> </html>
這樣就很巧妙得實現(xiàn)了Filter攔截并友好提示。
以上是“Ajax請求和Filter配合的示例分析”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學習更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道!
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。