


Detailed 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拦截并友好提示。
相关推荐:
jQuery中find()和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!

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python are both high-level programming languages that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Atom editor mac version download
The most popular open source editor