How to Prevent SQL Injection in Java Projects: From PreparedStatement to Nginx Filters

This article explains what SQL injection is, demonstrates a vulnerable example, and presents four practical defenses for Java applications—including PreparedStatement, MyBatis #{} placeholders, request‑parameter filtering, and Nginx reverse‑proxy rules—complete with code snippets and configuration details.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
How to Prevent SQL Injection in Java Projects: From PreparedStatement to Nginx Filters

What is SQL Injection?

SQL injection occurs when a web application fails to properly validate or filter user input, allowing an attacker to append malicious SQL statements to a predefined query, causing the database to execute unauthorized commands and potentially expose data.

Example:

String sql = "delete from table1 where id = " + "id";

If the id parameter is manipulated as 1001 or 1 = 1, the final query becomes:

String sql = "delete from table1 where id = 1001 or 1 = 1";

This would delete all rows in the table.

Java Project Methods to Prevent SQL Injection

Four common approaches:

Use PreparedStatement to pre‑compile SQL.

Use MyBatis #{} placeholders.

Filter sensitive keywords in request parameters.

Configure Nginx reverse‑proxy rules.

1. PreparedStatement

PreparedStatement pre‑compiles the SQL, fixing the statement structure and allowing only parameter values. delete from table1 where id = ? If an attacker supplies 1001 or 1 = 1, the database will raise an error, preventing injection.

2. MyBatis #{} placeholders

MyBatis #{} works like PreparedStatement, safely handling parameters. Note that ${} performs string substitution and does not prevent injection; it should only be used for identifiers such as table names or ORDER BY clauses.

3. Filtering request parameters

Example Spring Boot filter that concatenates request parameters and validates them against a blacklist of SQL keywords and special characters.

import org.springframework.context.annotation.Configuration;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
import java.util.Enumeration;

@WebFilter(urlPatterns = "/*", filterName = "sqlFilter")
@Configuration
public class SqlFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {}
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        Enumeration<String> names = servletRequest.getParameterNames();
        StringBuilder sql = new StringBuilder();
        while (names.hasMoreElements()) {
            String name = names.nextElement();
            String[] values = servletRequest.getParameterValues(name);
            for (String v : values) {
                sql.append(v);
            }
        }
        if (sqlValidate(sql.toString())) {
            throw new IOException("Illegal characters in request parameters");
        } else {
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }
    protected static boolean sqlValidate(String str) {
        String s = str.toLowerCase();
        String badStr = "select|update|and|or|delete|insert|truncate|char|into|substr|ascii|declare|exec|count|master|drop|table|"
                + "char|declare|sitename|xp_cmdshell|like|from|grant|use|group_concat|column_name|"
                + "information_schema.columns|table_schema|union|where|order|by|"
                + "'\\*|\\;|\\-|\\--|\\+|\\,|\\//|\\/|\\%|\\#";
        return s.matches(badStr);
    }
    @Override
    public void destroy() {}
}

4. Nginx reverse‑proxy protection

Insert the following rules into the server block and restart Nginx to block suspicious request methods, query strings, and user‑agents.

if ($request_method !~* GET|POST) { return 444; }
# block SQL injection patterns in query string
if ($query_string ~* (\\$|'|--|union|insert|drop|truncate|update|from|grant|exec|where|select|and|or|count|chr|mid|like|iframe|<script>|javascript|alert|webscan|dbappsecurity|style|confirm\\(|innerhtml|innertext).*$) { return 555; }
# block malicious user agents
if ($http_user_agent ~* "YisouSpider|ApacheBench|WebBench|Jmeter|JoeDog|Havij|GetRight|TurnitinBot|GrabNet|masscan|mail2000|github|wget|curl|Java|python") { return 508; }
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaMyBatisSQL injectionWeb SecurityPreparedStatement
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.