Case Analysis of Ajax requests and filters, and case analysis of ajax

Source: Internet
Author: User

Case Analysis of Ajax requests and filters, and case analysis of ajax

Case Introduction

Now there is a problem: when a large text comment is submitted, the foreground receives the data and sends an ajax request to the background. Then there is a Filter in the background to prevent SQL injection, after the Filter obtains the data transmitted from the front-end, it checks validity. If no verification is successful, it will jump to error. the error message is displayed on the jsp page. Now let's see how to implement 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 injection to 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. httpServle TRequest; import javax. servlet. http. httpServletResponse; import net. sf. json. JSONObject; // Filter public class SQLFilter implements Filter for filtering SQL keywords {public void doFilter (ServletRequest request, response, FilterChain chain) throws IOException, ServletException {HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse res = (HttpServletResponse) response; // obtain all request parameter names Enumera Tion params = req. getParameterNames (); String SQL = ""; while (params. hasMoreElements () {// obtain the parameter name String name = params. nextElement (). toString (); // System. out. println ("name ========================" + name + //"--" ); // obtain the value String [] value = req. getParameterValues (name); for (int I = 0; I <value. length; I ++) {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) ;}// verify protected static boolean sqlValidate (String str) {str = str. toLowerCase (); // convert to lower case // String badStr = "and | exec "; string badStr = "'| and | exec | execute | insert | select | delete | update | count | drop | chr | mid | master | truncate | ch Ar | 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 | // |/| % | # "; * // The SQL keyword filtered out, you can manually add String [] badStrs = badStr. split ("\ |"); f Or (int I = 0; I <badStrs. length; I ++) {if (str. indexOf (badStrs [I])! =-1) {System. out. println ("matched 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

<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>

Analysis: ajax requests DemoServlet, and then the request is first filtered by the Filter that prevents SQL injection. Then, the filtered Request Parameters constitute a matching string, and then check whether it is malicious code. If yes, request forwarding. However, unfortunately, this is logically correct, but the ajax request is partially refreshed, and finally it is returned to the page initiated by the ajax request. Therefore, request Forwarding is not implemented, let's look at the following implementation logic.

Train of Thought 2: Determine the return value

The logic of this idea is as follows: when the Filter filters out information, it sends a json data back to the ajax request and then returns it to the foreground, the front-end uses this data to determine whether it is malicious code and good code. 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 (data. mssage! = "") {// Execute the logic for processing malicious code} else {}}, error: function () {// logic after error }});

Filter to prevent SQL Injection

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. httpServle TRequest; import javax. servlet. http. httpServletResponse; import net. sf. json. JSONObject; // Filter public class SQLFilter implements Filter for filtering SQL keywords {public void doFilter (ServletRequest request, response, FilterChain chain) throws IOException, ServletException {HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse res = (HttpServletResponse) response; // obtain all request parameter names Enumera Tion params = req. getParameterNames (); String SQL = ""; while (params. hasMoreElements () {// obtain the parameter name String name = params. nextElement (). toString (); // System. out. println ("name ========================" + name + //"--" ); // obtain the value String [] value = req. getParameterValues (name); for (int I = 0; I <value. length; I ++) {SQL = SQL + value [I] ;}} System. out. println ("submission method:" + req. getMethod (); System. out. println ("matched String: "+ SQL); if (sqlValidate (SQL) {// send 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) ;}// verify protected static boolean sqlValidate (String str) {str = str. toLowerCase (); // convert to lower case // 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 | // |/| % | #";*// /The SQL keyword that is filtered out. You can manually add String [] badStrs = badStr. split ("\ |"); for (int I = 0; I <badStrs. length; I ++) {if (str. indexOf (badStrs [I])! =-1) {System. out. println ("matched 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. ");}}

Thought 3: exception + jump implementation

The logic of this idea is as follows. The Filter in the background filters out malicious injection code, throws RuntimeException (), causes ajax request failure, and calls back the error method of the ajax request. But how can we transfer the error page data? After careful consideration, we can save an error_messgae value in the session, redirect the error method of the ajax request to the error page, and then render the error page with the value.

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 injection to 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. httpServle TRequest; import javax. servlet. http. httpServletResponse; import net. sf. json. JSONObject; // Filter public class SQLFilter implements Filter for filtering SQL keywords {public void doFilter (ServletRequest request, response, FilterChain chain) throws IOException, ServletException {HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse res = (HttpServletResponse) response; // obtain all request parameter names Enumera Tion params = req. getParameterNames (); String SQL = ""; while (params. hasMoreElements () {// obtain the parameter name String name = params. nextElement (). toString (); // System. out. println ("name ========================" + name + //"--" ); // obtain the value String [] value = req. getParameterValues (name); for (int I = 0; I <value. length; I ++) {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) ;}// verify protected static boolean sqlValidate (String str) {str = str. toLowerCase (); // convert to lower case // String badStr = "and | exec "; string badStr = "'| and | exec | execute | insert | select | delete | update | count | dro P | 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 | // |/| % | # "; * // You can manually add String [] bad Strs = badStr. split ("\ |"); for (int I = 0; I <badStrs. length; I ++) {if (str. indexOf (badStrs [I])! =-1) {System. out. println ("matched 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

<% @ 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"> 

In this way, the Filter interception and friendly prompt are achieved.

The above is the case analysis of Ajax requests and filters introduced by xiaobian. I hope it will help you. If you have any questions, please leave a message and I will reply to you in a timely manner. Thank you very much for your support for the help House website!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.