search
HomeBackend DevelopmentPHP TutorialDetailed explanation of Ajax request and Filter cooperation cases

本文主要介绍了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 <p>web.xml配置</p><pre class="brush:php;toolbar:false"><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></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 <p>思路三:异常+跳转实现</p><p>这个思路的逻辑是这样的。后台的Filter过滤掉恶意注入代码的话,抛出RuntimeException(),然后导致ajax请求失败,然后回调ajax请求的error方法。但是我们错误页面的数据怎么传送过去呢?经过我认真思考之后,我们可以这样做,在session存一个error_messgae值,然后ajax请求的error方法跳转到错误页面,然后进行取值渲染错误页面。</p><p>ajax请求</p><pre class="brush:php;toolbar:false">$.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 <p>error.jsp实现</p><pre class="brush:php;toolbar:false">


nbsp;HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">


<base>">
<title>错误页面</title>
<meta>
<meta>
<meta> 
<meta>
<meta>
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->


<center> 
系统出错了,请稍后再试......
<br>
<br>
<br>
<br>
错误信息是: ${ error_message}
</center> 

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

相关推荐:

ajax的简单应用和filter的编写方法

jQuery中find()和filter()操作用法实例详解

CSS3中filter(滤镜)属性详解

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

Statement
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
PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

See all articles

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 Article

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool