Home Web Front-end JS Tutorial Ajax request and Filter parsing

Ajax request and Filter parsing

Apr 03, 2018 am 09:53 AM
ajax filter parse

这次给大家带来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(){
//错误之后的逻辑
}
});
Copy after login

防止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 = "&#39;|and|exec|execute|insert|select|delete|update|count|drop|chr|mid|master|truncate|char|declare|sitename|net user|xp_cmdshell|or|like|;|--|+|,|*|/";
/*
* String badStr =
* "&#39;|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.");
}
}
Copy after login

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>
Copy after login

分析,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(){
//错误之后的逻辑
}
});
Copy after login

防止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 = "&#39;|and|exec|execute|insert|select|delete|update|count|drop|chr|mid|master|truncate|char|declare|sitename|net user|xp_cmdshell|or|like|;|--|+|,|*|/";
/*
* String badStr =
* "&#39;|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.");
}
}
Copy after login

思路三:异常+跳转实现

这个思路的逻辑是这样的。后台的Filter过滤掉恶意注入代码的话,抛出RuntimeException(),然后导致ajax请求失败,然后回调ajax请求的error方法。但是我们错误页面的数据怎么传送过去呢?经过我认真思考之后,我们可以这样做,在session存一个error_messgae值,然后ajax请求的error方法跳转到错误页面,然后进行取值渲染错误页面。

ajax请求

$.ajax({
method:&#39;post&#39;,
url:&#39;servlet/DemoServlet&#39;,
dataType:&#39;json&#39;,
data:{
&#39;userName&#39;:userName,
&#39;passWord&#39;:passWord,
&#39;text&#39;: text
},
success:function(data){
//成功之后的逻辑
},
error:function(){
window.location.href="error.jsp";
}
});
Copy after login

防止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 = "&#39;|and|exec|execute|insert|select|delete|update|count|drop|chr|mid|master|truncate|char|declare|sitename|net user|xp_cmdshell|or|like|;|--|+|,|*|/";
/*
* String badStr =
* "&#39;|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.");
}
}
Copy after login

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>
Copy after login

这样就很巧妙得实现了Filter拦截并友好提示。

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

ajax跨域访问报错501怎么处理

ajax操作图层遮挡页面

The above is the detailed content of Ajax request and Filter parsing. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed explanation of Oracle error 3114: How to solve it quickly Detailed explanation of Oracle error 3114: How to solve it quickly Mar 08, 2024 pm 02:42 PM

Detailed explanation of Oracle error 3114: How to solve it quickly, specific code examples are needed. During the development and management of Oracle database, we often encounter various errors, among which error 3114 is a relatively common problem. Error 3114 usually indicates a problem with the database connection, which may be caused by network failure, database service stop, or incorrect connection string settings. This article will explain in detail the cause of error 3114 and how to quickly solve this problem, and attach the specific code

PHP and Ajax: Building an autocomplete suggestion engine PHP and Ajax: Building an autocomplete suggestion engine Jun 02, 2024 pm 08:39 PM

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

Parsing Wormhole NTT: an open framework for any Token Parsing Wormhole NTT: an open framework for any Token Mar 05, 2024 pm 12:46 PM

Wormhole is a leader in blockchain interoperability, focused on creating resilient, future-proof decentralized systems that prioritize ownership, control, and permissionless innovation. The foundation of this vision is a commitment to technical expertise, ethical principles, and community alignment to redefine the interoperability landscape with simplicity, clarity, and a broad suite of multi-chain solutions. With the rise of zero-knowledge proofs, scaling solutions, and feature-rich token standards, blockchains are becoming more powerful and interoperability is becoming increasingly important. In this innovative application environment, novel governance systems and practical capabilities bring unprecedented opportunities to assets across the network. Protocol builders are now grappling with how to operate in this emerging multi-chain

Analysis of the meaning and usage of midpoint in PHP Analysis of the meaning and usage of midpoint in PHP Mar 27, 2024 pm 08:57 PM

[Analysis of the meaning and usage of midpoint in PHP] In PHP, midpoint (.) is a commonly used operator used to connect two strings or properties or methods of objects. In this article, we’ll take a deep dive into the meaning and usage of midpoints in PHP, illustrating them with concrete code examples. 1. Connect string midpoint operator. The most common usage in PHP is to connect two strings. By placing . between two strings, you can splice them together to form a new string. $string1=&qu

How to solve the problem of jQuery AJAX error 403? How to solve the problem of jQuery AJAX error 403? Feb 23, 2024 pm 04:27 PM

How to solve the problem of jQueryAJAX error 403? When developing web applications, jQuery is often used to send asynchronous requests. However, sometimes you may encounter error code 403 when using jQueryAJAX, indicating that access is forbidden by the server. This is usually caused by server-side security settings, but there are ways to work around it. This article will introduce how to solve the problem of jQueryAJAX error 403 and provide specific code examples. 1. to make

How to get variables from PHP method using Ajax? How to get variables from PHP method using Ajax? Mar 09, 2024 pm 05:36 PM

Using Ajax to obtain variables from PHP methods is a common scenario in web development. Through Ajax, the page can be dynamically obtained without refreshing the data. In this article, we will introduce how to use Ajax to get variables from PHP methods, and provide specific code examples. First, we need to write a PHP file to handle the Ajax request and return the required variables. Here is sample code for a simple PHP file getData.php:

Analysis of new features of Win11: How to skip logging in to Microsoft account Analysis of new features of Win11: How to skip logging in to Microsoft account Mar 27, 2024 pm 05:24 PM

Analysis of new features of Win11: How to skip logging in to a Microsoft account. With the release of Windows 11, many users have found that it brings more convenience and new features. However, some users may not like having their system tied to a Microsoft account and wish to skip this step. This article will introduce some methods to help users skip logging in to a Microsoft account in Windows 11 and achieve a more private and autonomous experience. First, let’s understand why some users are reluctant to log in to their Microsoft account. On the one hand, some users worry that they

Apache2 cannot correctly parse PHP files Apache2 cannot correctly parse PHP files Mar 08, 2024 am 11:09 AM

Due to space limitations, the following is a brief article: Apache2 is a commonly used web server software, and PHP is a widely used server-side scripting language. In the process of building a website, sometimes you encounter the problem that Apache2 cannot correctly parse the PHP file, causing the PHP code to fail to execute. This problem is usually caused by Apache2 not configuring the PHP module correctly, or the PHP module being incompatible with the version of Apache2. There are generally two ways to solve this problem, one is

See all articles