主頁 > 知識(shí)庫 > Ajax請(qǐng)求和Filter配合案例解析

Ajax請(qǐng)求和Filter配合案例解析

熱門標(biāo)簽:怎樣在地圖標(biāo)注文字 東平縣地圖標(biāo)注app 大眾點(diǎn)評(píng)400電話怎么申請(qǐng) 河間市地圖標(biāo)注app 立陶宛地圖標(biāo)注 地圖標(biāo)注推銷坑人 上海企業(yè)外呼系統(tǒng)價(jià)錢 中國地圖標(biāo)注不明確情況介紹表 電銷機(jī)器人 長(zhǎng)春

案例引入

現(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ò)誤信息。現(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配置

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請(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+"/";
%>
!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
html>
head>
base href="%=basePath%>">
title>錯(cuò)誤頁面/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)出錯(cuò)了,請(qǐng)稍后再試......
br />
br />
br />
br />
錯(cuò)誤信息是: ${ error_message}
/center> 
/body>
/html>

這樣就很巧妙得實(shí)現(xiàn)了Filter攔截并友好提示。

以上所述是小編給大家介紹的Ajax請(qǐng)求和Filter配合案例解析,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!

您可能感興趣的文章:
  • 淺談jQuery中ajaxPrefilter的應(yīng)用
  • JQuery中模擬image的ajaxPrefilter與ajaxTransport處理
  • asp.net ajaxControlToolkit FilteredTextBoxExtender的簡(jiǎn)單用法

標(biāo)簽:四川 本溪 玉樹 遼寧 內(nèi)江 銅川 益陽 營(yíng)口

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《Ajax請(qǐng)求和Filter配合案例解析》,本文關(guān)鍵詞  Ajax,請(qǐng),求和,Filter,配合,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 下面列出與本文章《Ajax請(qǐng)求和Filter配合案例解析》相關(guān)的同類信息!
  • 本頁收集關(guān)于Ajax請(qǐng)求和Filter配合案例解析的相關(guān)信息資訊供網(wǎng)民參考!
  • 推薦文章