Java anti-SQL injection, the simplest way is to eliminate SQL splicing, SQL injection attack can be successful because the original SQL statement added to the new logic, if using PreparedStatement instead of statement to execute the SQL statement, followed by the input parameters, The SQL injection attack will be ineffective because PreparedStatement does not allow the logical structure of the query to change at different insertion times, and most of the SQL injection has been blocked, At the web level, we can filter the user input to prevent SQL injection, such as filtering global form parameters with filter
Java.io.IOException import;
Java.util.Iterator import;
Geneva Import Javax.servlet.Filter;
Javax.servlet.FilterChain import;
Import Javax.servlet.FilterConfig;
Javax.servlet.ServletException import;
From import javax.servlet.ServletRequest;
Javax.servlet.ServletResponse import;
Javax.servlet.http.HttpServletRequest import;
Ten import Javax.servlet.http.HttpServletResponse;
11/**
12 * Anti-SQL injection attack with filter filter
* www.2cto.com
14 */
public class Sqlfilter implements Filter {
Private String inj_str = "' |and|exec|insert|select|delete|update|count|*|%| chr|mid|master|truncate|char|declare|; |or|-|+|, ";
protected Filterconfig filterconfig = null;
18/**
* Should a character encoding specified by the client being ignored?
20 */
Protected Boolean ignore = true;
public void init (Filterconfig config) throws servletexception {
this.filterconfig = config;
This.inj_str = filterconfig.getinitparameter ("keywords");
25}
public void DoFilter (ServletRequest request, servletresponse response,
Filterchain chain) throws IOException, Servletexception {
HttpServletRequest req = (httpservletrequest) request;
HttpServletResponse res = (httpservletresponse) response;
Iterator values = Req.getparametermap (). VALUES (). Iterator ();//Get all the form parameters
while (Values.hasnext ()) {
String[] Value = (string[]) values.next ();
for (int i = 0;i < value.length;i++) {
if (Sql_inj (Value[i])) {
//todo Find the business logic code for SQL injection code here
return;
37}
38}
39}
Chain.dofilter (request, response);
41}
public boolean Sql_inj (String str)
43 {
String[] Inj_stra=inj_str.split ("\\|");
(int i=0; i < inj_stra.length; i++)
46 {
if (Str.indexof ("+inj_stra[i]+") >=0)
48 {
The return true;
50}
51}
The return is false;
53}
54}
You can also individually filter on JavaBean fields that need to be protected from SQL injection:
1/**
2 * Prevent SQL injection
3 *
4 * @param sql
5 * @return
6 */
7 public static string Transactsqlinjection (String sql) {
8 return Sql.replaceall (". *" ([';] +| (--)+).*", " ");
9}
Several ways to prevent SQL injection in Java