Source: https://blog.csdn.net/seesun2012
Objective
Talking about SQL injection:
The so-called SQL injection, by inserting a SQL command into a Web form or entering a query string for a domain name or page request, eventually achieves a malicious SQL command to spoof the server for a certain illegal purpose.
Solutions
1, Configuration Web-inf/web.xml
<web-app>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<!-- Anti-SQL Injection Filter -->
<filter>
<filter-name>SqlInjectFilter</filter-name>
<filter-class>com.seesun2012.web.core.filter.SqlInjectFilter</filter-class>
<!-- Filter the parameters passed in the foreground, you can manually add or delete, split by "|" -->
<init-param>
<param-name>sqlInjectStrList</param-name>
<param-value>‘|or|and|;|-|--|+|,|like|//|/|*|%|#</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>SqlInjectFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
2, Filter Sqlinjectfilter.java class
Package com.seesun2012.web.core.filter;
Import java.io.IOException;
Import java.util.Enumeration;
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;
/**
* SQL injection filter
* @author CSDN: seesun2012
* @version 0.0.1-SNAPSHOT
* @Date 2018-01-14
*/
Public class SqlInjectFilter implements Filter{
Public FilterConfig config;
@Override
Public void destroy() {
This.config = null;
}
@Override
Public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httprequest = (HttpServletRequest) request;
// Get all request parameter names
Enumeration<?> params = httprequest.getParameterNames();
String sql = "";
While (params.hasMoreElements()) {
/ / Get the parameter name
String name = params.nextElement().toString();
/ / Get the corresponding value of the parameter
String[] value = httprequest.getParameterValues(name);
For (int i = 0; i < value.length; i++) {
Sql = sql + value[i];
}
}
// Filtered SQL keywords can be added manually
String sqlInjectStrList = config.getInitParameter("sqlInjectStrList");
If (sqlValidate(sql, sqlInjectStrList)) {
Throw new IOException("Please enter a valid character");
// redirect or jump, slightly...
} else {
chain.doFilter(request, response);
}
}
// Verify SQL
Protected static boolean sqlValidate(String str, String sqlInjectStrList) {
// Unified to lowercase
Str = str.toLowerCase();
/ / Convert to an array
String[] badStrs = sqlInjectStrList.split("\\|");
For (int i = 0; i < badStrs.length; i++) {
// search
If (str.indexOf(badStrs[i]) >= 0) {
Return true;
}
}
Return false;
}
@Override
Public void init(FilterConfig filterConfig) throws ServletException {
Config = filterConfig;
}
}
Java anti-SQL injection Filter (Interceptor) code