In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly shows you the "sample analysis of Ajax request and Filter coordination", which is easy to understand and clear. I hope it can help you solve your doubts. Let the editor lead you to study and learn the article "sample analysis of Ajax request and Filter coordination".
Case introduction
Now there is such a problem, that is, when submitting a large text comment, the foreground gets the data and sends an ajax request to the backend, and then there is a Filter in the background to prevent SQL injection. After the Filter gets the data from the foreground, it verifies the validity. If the verification is not successful, you have to jump to the error.jsp page to display the error message. Now let's see how to achieve this requirement.
Idea 1: request forwarding implementation
Ajax request
$.ajax ({method:'post',url:'servlet/DemoServlet',dataType:'json',data: {'userName':userName,'passWord':passWord,'text': text}, success:function (data) {/ / logic after success}, error:function () {/ / logic after error}})
Prevent SQL from injecting into 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 / filter the Filter public class SQLFilter implements Filter {public void doFilter (ServletRequest request, ServletResponse response,FilterChain chain) throws IOException of the sql keyword, ServletException {HttpServletRequest req = (HttpServletRequest) request;HttpServletResponse res = (HttpServletResponse) response;// to get all request parameter names Enumeration params = req.getParameterNames (); String sql = ""; while (params.hasMoreElements ()) {/ / get the parameter name String name= params.nextElement (). ToString (); / / System.out.println ("name==" + name + / "-") / / get the corresponding parameter values String [] value = req.getParameterValues (name); for (int I = 0; I < value.length; iTunes +) {sql = sql + value [I];}} System.out.println ("submission method:" + req.getMethod ()); System.out.println ("matched string:" + sql); if (sqlValidate (sql)) {/ / request forwarding req.getRequestDispatcher ("error.jsp") .forward (req, res) } else {String request_uri = req.getRequestURI (); chain.doFilter (request, response);}} / / check protected static boolean sqlValidate (String str) {str = str.toLowerCase (); / / convert to lowercase / / String badStr = "and | exec"; String badStr = "'| and | exec | execute | insert | delete | update | count | drop | chr | mid | truncate | char | sitename | net user | or | like |;-- | + |, * | /"; / * String badStr = * "| and | and | exec | execute | exec | Con | Mao | bot | | | |-|-| + |, | like | / / | / |% | # "; * / / filtered sql keyword, you can manually add String [] badStrs = badStr.split ("\\ | "); for (int I = 0; I < badStrs.length; iTunes +) {if (str.indexOf (badStrings [I])! =-1) {System.out.println (" match to: "+ 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 configuration
SQLFilterSQLFiltercom.yiyexiaoyuan.filter.SQLFilterSQLFilter/servlet/*
Parsing, ajax requests DemoServlet, and then the request is first prevented from SQL injection. This Filter filter first filters, then the filtered request parameters form a matching string, and then checks for malicious code, and if so, the request is forwarded. Unfortunately, this is logically correct, but the ajax request is partially refreshed and finally goes back to the page initiated by the ajax request, so request forwarding will not be implemented, let's look at the next implementation logic.
Idea 2: return value to judge
The logic of this idea is as follows: when Filter filters out the information, send back a json data to the ajax request, and then return it to the foreground, and the foreground uses the data to determine whether it is malicious code and good code. And then proceed to the next step.
Ajax request
$.ajax ({method:'post',url:'servlet/DemoServlet',dataType:'json',data: {'userName':userName,'passWord':passWord,'text': text}, success:function (data) {/ / logic if after success (data.mssagekeeper = "") {/ / execute logic} else {}}, error:function () {/ / logic after error})
Prevent Filter injected by SQL
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 / filter the Filter public class SQLFilter implements Filter {public void doFilter (ServletRequest request, ServletResponse response,FilterChain chain) throws IOException of the sql keyword, ServletException {HttpServletRequest req = (HttpServletRequest) request;HttpServletResponse res = (HttpServletResponse) response;// to get all request parameter names Enumeration params = req.getParameterNames (); String sql = ""; while (params.hasMoreElements ()) {/ / get the parameter name String name= params.nextElement (). ToString (); / / System.out.println ("name==" + name + / "-") / / get the corresponding parameter values String [] value = req.getParameterValues (name); for (int I = 0; I < value.length; iTunes +) {sql = sql + value [I];}} System.out.println ("submission method:" + req.getMethod ()); System.out.println ("matched string:" + sql); if (sqlValidate (sql)) {/ / transmit json data JSONObject json = new JSONObject (); json.accumulate ("message", "malicious code injection") Res.getWriter (). Print (json.toString ());} else {String request_uri = req.getRequestURI (); chain.doFilter (request, response);}} / / check protected static boolean sqlValidate (String str) {str = str.toLowerCase (); / / convert to lowercase / / String badStr = "and | exec"; String badStr = "'| and | exec | execute | select | delete | update | count | chr | mid | master | truncate | char | declare | sitename | net user | xp_cmdshell | or | |-| + |, * | /" | / * * String badStr = * "'| and | exec | execute | create | create | drop | from | grant | use | group_concat | column_name |" * + * "information_schema.columns | table_schema | union | select | delete | order | by | * | truncate | mid | master | truncate | char | declare | or | |-|-| + | like | / / |% | #"; * / filtered sql keyword, String [] badStrs = badStr.split ("\\ |"); for (for I = 0; I < int) If (str.indexOf (badStrs [I])! =-1) {System.out.println ("match to:" + 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.");}}
Idea 3: exception + jump realization
The logic of this train of thought is like this. The background Filter filters out malicious injection code, throws RuntimeException (), causes the ajax request to fail, and then calls back the error method of the ajax request. But how can the data from our error page be transmitted? After I've thought about it, we can do this by storing an error_ message value in session, then the error method requested by ajax jumps to the error page, and then takes the value to render the error page.
Ajax request
$.ajax ({method:'post',url:'servlet/DemoServlet',dataType:'json',data: {'userName':userName,'passWord':passWord,'text': text}, success:function (data) {/ / logic after success}, error:function () {_ window.location.href= "error.jsp";}})
Prevent SQL from injecting into 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 / filter the Filter public class SQLFilter implements Filter {public void doFilter (ServletRequest request, ServletResponse response,FilterChain chain) throws IOException of the sql keyword, ServletException {HttpServletRequest req = (HttpServletRequest) request;HttpServletResponse res = (HttpServletResponse) response;// to get all request parameter names Enumeration params = req.getParameterNames (); String sql = ""; while (params.hasMoreElements ()) {/ / get the parameter name String name= params.nextElement (). ToString (); / / System.out.println ("name==" + name + / "-") / get the corresponding parameter values String [] value = req.getParameterValues (name); for (int I = 0; I < value.length; iTunes +) {sql = sql + value [I];}} System.out.println ("submission method:" + req.getMethod ()); System.out.println ("matched string:" + sql); if (sqlValidate (sql)) {req.getSession () .setAttribute ("error_message", "malicious injection"); throw new RuntimeException ("malicious injection") } else {String request_uri = req.getRequestURI (); chain.doFilter (request, response);}} / / check protected static boolean sqlValidate (String str) {str = str.toLowerCase (); / / convert to lowercase / / String badStr = "and | exec"; String badStr = "'| and | exec | execute | insert | delete | update | count | drop | chr | mid | truncate | char | sitename | net user | or | like |;-- | + |, * | /"; / * String badStr = * "| and | and | exec | execute | exec | Con | Mao | bot | | | |-|-| + |, | like | / / | / |% | # "; * / / filtered sql keyword, you can manually add String [] badStrs = badStr.split ("\\ | "); for (int I = 0; I < badStrs.length; iTunes +) {if (str.indexOf (badStrings [I])! =-1) {System.out.println (" match to: "+ 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 implementation
The error page system has gone wrong. Please try again later. The error message is: ${error_message}
This cleverly implements Filter interception and friendly prompts.
The above is all the contents of the article "sample Analysis of Ajax request and Filter Coordination". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.