Why “null” Strings Break Your Java Backend – and How to Fix It
The article explains how treating the literal string "null" as an empty value can cause serious bugs in Java backend registration, demonstrates the issue with code examples, and provides practical input‑sanitizing and validation techniques to prevent such errors and related security risks.
Many developers encounter a puzzling bug where a username value of "null" is accepted as valid, leading to ghost accounts and downstream failures.
In Java,
nullis a keyword representing a null reference, while "null" is a regular string containing characters; treating the latter as empty creates bugs.
A typical registration JSON might look like:
<code>{
"username": "null",
"password": "123456"
}</code>If the backend checks only for
nullreferences:
<code>if (user.getUsername() == null) {
throw new IllegalArgumentException("用户名不能为空");
}</code>the check passes because the value is a non‑null string, allowing the user to be registered with the literal name "null".
Demonstrating the difference:
<code>String a = null;
String b = "null";
System.out.println(a == null); // true
System.out.println(b == null); // false
System.out.println("null".equals(a)); // false
System.out.println("null".equals(b)); // true</code>To avoid such issues, preprocess all incoming strings:
<code>public static String sanitizeInput(String input) {
if (input == null) return null;
String trimmed = input.trim();
if ("null".equalsIgnoreCase(trimmed)) return null;
return trimmed;
}</code>Front‑end code that defaults empty values to "null" (e.g.,
username = username || "null";) propagates the problem to the server.
Database NOT NULL constraints do not help because the string "null" satisfies the constraint.
Robust validation should be applied both on the client and server, for example using a regular expression or blacklist:
<code>if (username.matches("(?i)null|nulI|nuli|n1ll")) {
throw new IllegalArgumentException("用户名非法");
}</code>For more advanced protection, visual‑similarity character detection can be employed.
Key pitfalls to watch out for:
Confusing the string "null" with the null reference.
Storing un‑sanitized input directly into the database.
Relying solely on database constraints for validation.
Lacking proper legality checks for username and password fields.
Ignoring character‑spoofing attacks such as "nulI".
macrozheng
Dedicated to Java tech sharing and dissecting top open-source projects. Topics include Spring Boot, Spring Cloud, Docker, Kubernetes and more. Author’s GitHub project “mall” has 50K+ stars.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.