Prevents SQL injection and SQL Injection
In fact, it is to pass the keywords of some databases to the backend after the user inputs the parameters, and verify that the input parameters are sufficient to contain the keywords of the database and are filtered out. There may be some vulnerabilities in this way, and we hope the experts will come to correct the mistakes. Paste the following code.
1 public class SQLInjectionFilter implements Filter {2 public void destroy () {3 // TODO Auto-generated method stub 4} 5 6 public void init (FilterConfig arg0) throws ServletException {7 // TODO Auto-generated method stub 8} 9 10 public void doFilter (ServletRequest request, ServletResponse response, 11 FilterChain chain) throws IOException, servletException {12 HttpServletRequest req = (HttpServletR Equest) request; 13 HttpServletResponse res = (HttpServletResponse) response; 14 // obtain all request parameter names 15 Enumeration params = req. getParameterNames (); 16 String SQL = ""; 17 // get the request's URL18 while (params. hasMoreElements () {19 // obtain the parameter name 20 String name = params. nextElement (). toString (); 21 // obtain the parameter value 22 String [] value = req. getParameterValues (name); 23 if (value! = Null &&! Value [0]. equals ("-1") {24 for (int I = 0; I <value. length; I ++) {25 SQL = SQL + value [I]; 26} 27} 28} 29 30 // check whether the output parameter contains the keyword 31 if (sqlValidate (SQL) {32 PrintWriter out = res. getWriter (); 33 out. print ("<script> alert ('the request parameter you sent contains invalid characters') </script>"); 34 out. close (); 35} else {36 chain. doFilter (request, response); 37} 38} 39 40 // total SQL keyword 41 protected static boolean sqlValidate (String str) {42 str = str. toLowerCase (); // convert to lowercase 43 String badStr = "'| and | exec | waitfot | delay | sysusers | html | function | group by | database | user | system_user | session_user | substring |" + 44 "sysobjects | chongqing | script | ajax | execute | insert | select | delete | update | count | drop | * | % | chr | mid | master | truncate |" + 45 "char | declare | sitename | net user | xp_shareshell | like '| create | table | from | grant | use | group_concat | column_name |" + 46 "information_schema.columns | table_schema | union | where | order | by | -- | + | like | #"; // filter out the SQL keywords. You can manually add 47 String [] badStrs = badStr. split ("\\|"); 48 for (int I = 0; I <badStrs. length; I ++) {49 // loop check to determine whether the request parameter contains the SQL keyword 50 if (str. indexOf (badStrs [I])> = 0) {51 return true; 52} 53} 54 return false; 55}