您好,登錄后才能下訂單哦!
這篇文章主要為大家展示了“Ajax請求和Filter配合的示例分析”,內容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領大家一起研究并學習一下“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配合的示例分析”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。