案例引入
現在有這樣一個問題,就是在提交大片文字評論的時候,前台拿到資料之後給後台發送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配合案例解析,希望對大家有所協助,如果大家有任何疑問請給我留言,小編會及時回複大家的。在此也非常感謝大家對雲棲社區網站的支援!