Java Security: How to Protect Code from SQL Injections and XSS Attacks

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

How to Prevent Hackers from Breaking Your Java Code: SQL Injections and XSS Under the Microscope

\n\n

Imagine: you've written a perfect web application in Java. A beautiful interface, fast logic, clean architecture. You deploy it to the server, brew some tea, and... an hour later you get a message that the database has been deleted, and someone's cheeky ASCII art is displayed on the main page. Sound familiar? Unfortunately, for many developers — yes.

\n\n

The two most common and dangerous web application vulnerabilities — SQL injections and cross-site scripting (XSS) — keep administrators of thousands of sites up at night every year. And Java, despite its strictness, is no exception. But there's good news: protecting against them is possible. And it's not even very difficult.

\n\n

In this article, we'll break down exactly how attackers target Java applications, and most importantly — how to set up a reliable checkpoint using proven tools and proper coding habits. Buckle up: there will be lots of code, life hacks, and minimal fluff.

\n\n

SQL Injections: When the User Becomes a Programmer

\n\n

What Is It and Why Does It Work?

\n\n

SQL injection is an attack technique where an attacker "injects" malicious SQL code into a query through user input. If the application mindlessly concatenates strings, the attacker can gain access to other people's data, delete tables, or even take control of the database server.

\n\n

A classic example of bad Java code:

\n\n
String userInput = request.getParameter("username");\nString query = "SELECT * FROM users WHERE username = '" + userInput + "'";\nStatement stmt = connection.createStatement();\nResultSet rs = stmt.executeQuery(query);
\n\n

What happens if the user enters: admin' OR '1'='1? The query becomes:

\n\n
SELECT * FROM users WHERE username = 'admin' OR '1'='1'
\n\n

The condition '1'='1' is always true. Congratulations: the attacker just logged into the system as an administrator without even knowing the password. And if they enter '; DROP TABLE users; -- — say goodbye to your data.

\n\n

How to Protect Yourself: PreparedStatement Is Your Shield

\n\n

Rule number one in Java application security: never concatenate user data with SQL queries. Use parameterized queries via PreparedStatement.

\n\n

Here's what secure code should look like:

\n\n
String userInput = request.getParameter("username");\nString query = "SELECT * FROM users WHERE username = ?";\nPreparedStatement pstmt = connection.prepareStatement(query);\npstmt.setString(1, userInput);\nResultSet rs = pstmt.executeQuery();
\n\n

What happened here? The database receives the query and the data separately. Even if userInput contains malicious SQL code, it will be treated as a regular string, not as a command. PreparedStatement automatically escapes special characters. This is the first and most important line of defense.

\n\n

Additional Measures: Stored Procedures and Validation

\n\n

In addition to PreparedStatement, you should use:

\n\n
    \n
  • Stored procedures — calling a procedure via CallableStatement also separates code from data.
  • \n
  • Whitelists — if you need to substitute a table or column name (which is rare), never take it from user input. Use an enum or strictly defined constants.
  • \n
  • Input validation — check that an email actually looks like an email, and a number is a number. But remember: validation is an additional layer, not a replacement for PreparedStatement.
  • \n
\n\n

Example of safe handling of dynamic table names:

\n\n
public enum TableName {\n    USERS, PRODUCTS, ORDERS\n}\n\npublic void queryTable(TableName table) {\n    String que                

Blogs

Book Recommendations