Skip to content

    System Design

    Input Validation and Injection Prevention

    Validate input with allow-lists and Bean Validation, keep user text out of SQL with prepared statements, and handle file paths, JSON and output safely.

    By Published 14 min read

    Share

    Standard lessonintermediateSpring Boot labBackend System Design

    Before this: Authentication vs Authorization, Sessions vs Tokens

    What you'll learn: By the end of this lesson you will be able to separate two jobs that are often confused, validating input and preventing injection, validate a request body with Bean Validation and an allow-list, keep user text out of SQL with a prepared statement, handle the things a placeholder cannot (such as a sort column), contain file paths, read JSON and Java-serialized data defensively, and hand output encoding to the layer that knows the context. A Spring Boot lab runs each case against an in-memory H2 database through MockMvc.

    A restaurant kitchen has a receiving door where deliveries are checked against the order: only what was ordered goes in. That is validation. The kitchen also has a rule that does not depend on the door: nobody pours an unlabelled liquid into the soup, because recipes keep the method separate from the ingredients and an ingredient can never rewrite the method. That is injection prevention.

    They are different jobs. Validation reduces malformed data and invalid operations. Injection prevention keeps data from being read as code by whatever consumes it: a SQL engine, a file system, a deserializer, a browser. A system that relies on validation alone fails the day a legitimate value looks like code, such as a name with an apostrophe.

    This lesson follows data from the edge of a Spring application to where it ends up. Whether a caller may act on an object is a separate question, covered in Authentication vs Authorization, Sessions vs Tokens and RBAC, ABAC and ReBAC. SSRF and the OWASP API Security Top 10 covers a related input risk.

    Verified with Spring Boot 4.1.2, Hibernate Validator 9.1.5, Jackson 3.1.7, H2 2.4.240, Java 25 language level and the documentation pages listed at the end, on 2026-12-01.

    The core idea

    Validate at the boundary with rules that say what is acceptable; then, separately, never let untrusted text become part of an instruction. For SQL that means a fixed statement with bound values; for a column name, a mapping to names you own; for a file path, a containment check; for output, encoding for the place it appears.

    Three labelled illustrations run through the lesson:

    • Minimal example: a NewProduct body with Bean Validation, and a name lookup that is first concatenated and then prepared.
    • Realistic example: ShopStream's seller product import and search, in "In practice".
    • Failure example: a customer called "Farmer's Cheese" breaking a concatenated query, and the string .. slipping past a file-name pattern.

    Every payload here is a textbook-benign string and the data is invented.

    Validation at the boundary

    OWASP's Input Validation Cheat Sheet says validation "checks whether data meets an application's requirements before the application uses it", both syntactically (type and format) and semantically (does the value make sense for the operation). It favours allow-lists: "Define what the application accepts and reject values outside those rules", and "Do not try to recognize every malicious string". Its example against deny-lists is the apostrophe: "Blocking apostrophes, for example, rejects legitimate names without making a database query safe." Validation must run on the server even if the browser checks the same fields, because client-side checks can be bypassed.

    In Spring, Bean Validation is the usual tool, and a provider such as Hibernate Validator on the classpath is detected. @Valid on a @RequestBody parameter raises MethodArgumentNotValidException on failure; constraints written on controller parameters raise HandlerMethodValidationException, and the Spring documentation says to handle both. The lab's input type:

    public record NewProduct(
            @NotBlank @Size(max = 40) @Pattern(regexp = "[\\p{L}\\p{N} .,'&-]*") String name,
            @NotNull @Min(1) @Max(1_000_000) Integer priceCents,
            @NotNull Category category) {
    }

    The input type has only three fields, so a request cannot set an id (more below). The name rule is an allow-list that keeps the apostrophe and ampersand a deny-list would have thrown out, and category is an enum, so any other value is rejected while the JSON is read. The cheat sheet also warns that backtracking patterns can be attacked with near-matching input, and advises bounding length before matching; the lab's pattern is one character class and @Size bounds the length.

    The error handler returns field and constraint names only, never the rejected value, a stack trace or SQL text:

    @ExceptionHandler(MethodArgumentNotValidException.class)
    ResponseEntity<Map<String, List<String>>> body(MethodArgumentNotValidException ex) {
        List<String> errors = ex.getBindingResult().getFieldErrors().stream()
                .map(e -> e.getField() + ": " + e.getCode()).sorted().toList();
        return ResponseEntity.badRequest().body(Map.of("errors", errors));
    }

    Figure 1. Where each check sits

    Validation narrows what gets in; binding and mapping keep it from being read as codeClient to Parse (request); Parse to Validate (typed object); Validate to Business rules (acceptable); Business rules to Prepared SQL (bound values)TRUSTED: YOUR SERVERSClient: untrusted bytesClientuntrusted bytesParse: JSON into a fixed typeParseJSON into a fixedtypeValidate: allow-lists, rangesValidateallow-lists,rangesBusiness rules: meaning, ownershipBusiness rulesmeaning,ownershipPrepared SQL: values are boundPrepared SQLvalues are boundrequesttyped objectacceptablebound values

    How to read this: the first three stages decide whether the input is acceptable and what it means. The last stage is a separate defence: even a value that passed everything is sent to the database as a value, never as SQL text.

    SQL injection and the prepared statement

    The OWASP Query Parameterization Cheat Sheet explains the risk: "SQL Injection allows evil attacker code to change the structure of a web application's SQL statement." The cause is concatenation: the caller's text becomes part of the statement text. Here is the lab's deliberately unsafe version, kept only so the lesson can show it:

    public static String sqlFor(String name) {
        return "select id, name, price_cents, category from product where name = '" + name + "'";
    }

    For the name ' OR '1'='1, a textbook example, the statement the database receives is:

    select id, name, price_cents, category from product where name = '' OR '1'='1'

    The input closed the quote, added a condition that is always true and left the final quote to the original text, so the where clause now matches every row. The caller changed what the query means.

    Figure 2. Concatenation versus a bound value

    sequenceDiagram accTitle: Concatenated SQL versus a prepared statement accDescr: With concatenation the application builds one string containing the user text and the database parses all of it as SQL, so the text can change the statement. With a prepared statement the application sends the statement with a placeholder and the value separately, and the database treats the value as data. participant A as Application participant D as Database Note over A,D: concatenated A->>D: one string: statement text with the user text pasted in D->>D: parse everything as SQL Note over A,D: prepared A->>D: statement with a ? placeholder A->>D: the value, bound to parameter 1 D->>D: parse the statement, use the value as data

    How to read this: in the first exchange there is one channel and the user text travels in it. In the second there are two channels, and the value can never be parsed as part of the statement.

    The recommended pattern in OWASP's SQL Injection Prevention Cheat Sheet is parameterized queries, and its Java example binds the value with a PreparedStatement. The Java documentation describes a prepared statement as "a precompiled SQL statement" that can be executed many times. The lab's safe lookup:

    public List<Product> findByName(String name) throws SQLException {
        String sql = "select id, name, price_cents, category from product where name = ?";
        try (Connection c = dataSource.getConnection(); PreparedStatement ps = c.prepareStatement(sql)) {
            ps.setString(1, name);
            try (ResultSet rs = ps.executeQuery()) {
                return read(rs);
            }
        }
    }

    Three more rules from the cheat sheet. Escaping is not the plan: "Relying on manually escaping dynamic inputs is error-prone and is strongly discouraged." Validation "complements parameter binding; it does not replace it." And do not give an application account DBA or administrator rights, so a mistake elsewhere reaches less.

    What a placeholder cannot do

    A placeholder stands for a value. OWASP: "Parameter markers represent data values, not table names, column names, or SQL keywords such as ASC and DESC." So order by ? does not work as intended. The cheat sheet's answer is to map the caller's selection to "a small set of application-owned values allowed for that query and reject anything else". The lab does it with an enum, so the text the caller sent never reaches the SQL:

    public enum SortKey {
        NAME("name"), PRICE("price_cents");
    
        public static SortKey parse(String requested) {
            for (SortKey key : values()) {
                if (key.name().equalsIgnoreCase(requested)) {
                    return key;
                }
            }
            throw new BadInputException("sort must be one of name, price");
        }

    (The constructor and accessor that hold the column name are omitted from this excerpt.)

    Paths, JSON and Java objects

    File paths

    OWASP describes path traversal as using "dot-dot-slash (../)" sequences to reach files outside the intended folder. Its advice: avoid user input in file-system calls, accept only known-good values rather than sanitizing, never let the caller supply all parts of a path, and normalize input if it must be used. The page does not describe a "starts with the base folder" check; that step is this lesson's addition, built on Java's Path: normalize() removes . and .. without touching the file system, and startsWith compares name elements. The Java documentation warns that removing .. and the name before it can locate a different file if that name is a symbolic link, so path containment is a layer, not a guarantee.

    public Path resolveInside(String name) {
        if (name == null || !PLAIN_NAME.matcher(name).matches()) {
            throw new BadInputException("not a plain file name");
        }
        Path resolved = base.resolve(name).normalize();
        if (!resolved.startsWith(base)) {
            throw new BadInputException("outside the base folder");
        }
        return resolved;
    }

    The failure example is in the lab: the name .. matches the plain-name pattern, because dots are allowed in file names, and only the second check rejects it. Two layers, because each catches what the other misses.

    JSON into a fixed type, and mass assignment

    Binding a body to a type is where mass assignment lives: frameworks bind request data to objects, so attackers "can sometimes use this methodology to create new parameters that the developer never intended". OWASP's main defence: "create Data Transfer Objects and avoid binding input directly to domain objects", with only editable fields in the DTO. NewProduct is that DTO.

    What happens to extra fields depends on the mapper. In this lab the application's Jackson 3 mapper (Jackson 3 is the default library in Spring Boot 4) ignored id and admin and assigned its own id, while a plain mapper with FAIL_ON_UNKNOWN_PROPERTIES enabled rejected the same body. Neither lets the caller set the id, because the DTO has no such field. Decide on purpose whether unknown fields are errors.

    Native Java deserialization

    Java's built-in serialization can instantiate classes named in the data it reads. OWASP: "A great reduction of risk is achieved by avoiding native (de)serialization formats", for example by switching to JSON. If it cannot be avoided, configure a serialization filter with an application-specific class allow-list and resource limits, bearing in mind that "Filtering does not make arbitrary untrusted deserialization safe". The JDK's ObjectInputFilter is described as a way to "Filter classes, array lengths, and graph metrics during deserialization". The lab's filter accepts one class and rejects the rest:

    private static final ObjectInputFilter ALLOW_ONLY_NOTES =
            ObjectInputFilter.Config.createFilter("buildingai.labs.validation.ShippingNote;!*");

    Output encoding is someone else's turn

    Valid, safely bound data can still be shown somewhere that treats some characters as syntax. OWASP's XSS guidance is context-specific output encoding: HTML entity encoding for an HTML body and different encoders for attributes, URLs, JavaScript and CSS ("JavaScript and HTML encoding are not interchangeable"). Input validation "does not replace these protections". So the lab stores Fish & Chips <b>half price</b> as typed and encodes it when writing HTML, with Spring's HtmlUtils.htmlEscape. Refusing < in a product name is a product decision for that field, not a substitute: imported data and older rows may still contain it.

    The other side of this topic

    The browser side is in XSS Defenses and Content Security Policy. The server's part is to store data faithfully and keep its own interpreters, SQL above all, free of untrusted text.

    Figure 3. Which defence for which destination

    flowchart TD accTitle: Choosing a defence by destination accDescr: Untrusted text is first validated. Then the defence depends on where it goes: a SQL value is bound, a SQL identifier is mapped from a key, a file path gets a plain-name allow-list and a containment check, a structured payload is read into a fixed type, and HTML output is encoded for its context. A["Untrusted text"] --> V["Validate: allow-list, length, range"] V --> B{"Where does it go?"} B -->|"SQL value"| P["Bind to a ? placeholder"] B -->|"column or ASC/DESC"| M["Map a key to a name you own"] B -->|"file path"| F["Plain name, then containment"] B -->|"JSON or objects"| D["Read into a fixed DTO or filtered type"] B -->|"HTML page"| E["Encode for that context"]

    How to read this: validation is the same first step for everything. The second step is different for each destination, which is why one "sanitize" function cannot cover them all.

    Build it: validation and injection in Spring

    This is the minimal example and its failure cases. Goal: see each defence refuse a benign textbook input, and what the same input does without it. The database is H2 2.4.240 in memory with four invented rows, reached through plain JDBC (no Docker); the web layer is tested with MockMvc.

    Setup. From the repository:

    cd examples/spring-labs
    ./gradlew :labs:input-validation-injection:test

    It runs 11 tests, one of which compares the report below with the golden file examples/spring-labs/golden/input-validation-injection.txt. The code is in examples/spring-labs/labs/input-validation-injection/. Nothing in the application calls the unsafe class UnsafeProductQueries; the tests do.

    Bean validation. Each refusal names the field and the constraint, and the response never contains the rejected text.

    Expected output, captured from a real run (Spring Boot 4.1.2, Hibernate Validator 9.1.5, Java 25, 2026-12-01):

    valid product                              -> 201 {"id":5,"name":"Seeded rye"}
    blank name                                 -> 400 {"errors":["name: NotBlank"]}
    name of 41 characters                      -> 400 {"errors":["name: Size"]}
    name with angle brackets                   -> 400 {"errors":["name: Pattern"]}
    price 0                                    -> 400 {"errors":["priceCents: Min"]}
    price 1000001                              -> 400 {"errors":["priceCents: Max"]}
    price missing                              -> 400 {"errors":["priceCents: NotNull"]}
    category missing                           -> 400 {"errors":["category: NotNull"]}
    category not in the enum                   -> 400
    price is text                              -> 400
    two errors at once                         -> 400 {"errors":["name: NotBlank","priceCents: Min"]}
    extra fields id and admin in the JSON      -> 201 {"id":6,"name":"Rye loaf"}
    name with an apostrophe and an ampersand   -> 201 {"id":7,"name":"Ben's Rye & Oats"}

    The last two lines are the mass-assignment and allow-list points: the extra id of 999 did not become the id, and an apostrophe and an ampersand are accepted because real names contain them.

    Injection. Three inputs go to the concatenated query and to the prepared one. An ordinary name works in both. A legitimate name with an apostrophe breaks the concatenated query with a syntax error (SQLSTATE 42000), which is the first sign that the code is injectable. The textbook tautology returns every row through concatenation and none through the prepared statement, which looks for a product whose name is that literal text.

    Expected output, captured from a real run (the same run):

    input: Rye bread
      concatenated text: select id, name, price_cents, category from product where name = 'Rye bread'
      concatenated result: 1 row(s) [Rye bread]
      prepared statement result: 1 row(s) [Rye bread]
    input: Farmer's Cheese
      concatenated text: select id, name, price_cents, category from product where name = 'Farmer's Cheese'
      concatenated result: JdbcSQLSyntaxErrorException, SQLSTATE 42000
      prepared statement result: 1 row(s) [Farmer's Cheese]
    input: ' OR '1'='1
      concatenated text: select id, name, price_cents, category from product where name = '' OR '1'='1'
      concatenated result: 4 row(s) [Rye bread, Oat milk, Farmer's Cheese, Sourdough]
      prepared statement result: 0 row(s) []
    GET /products/search?name=' OR '1'='1 -> []
    GET /products/search with a 41-character name -> 400 {"errors":["name: Size"]}

    Sort keys, paths and deserialization. The sort key is mapped, so text that is not a key never reaches the SQL. The path check passes a plain name, refuses separators, and refuses .. only at the second layer. The class filter accepts the one class it names.

    Expected output, captured from a real run (the same run):

    GET /products?sort=name;-- -> 400 {"errors":["sort must be one of name, price"]}
    GET /products?sort=price_cents -> 400 {"errors":["sort must be one of name, price"]}
    
    == 4. Path traversal: a plain-name allow-list, then a check that the normalized path is still inside the folder
    GET /files?name=notes.txt -> 200 packing notes
    GET /files?name=missing.txt -> 404
    GET /files?name=../secret.txt -> 400 {"errors":["not a plain file name"]}
    GET /files?name=sub/notes.txt -> 400 {"errors":["not a plain file name"]}
    GET /files?name=.. -> 400 {"errors":["outside the base folder"]}
    without any check, ../secret.txt would point one level above the folder: true
    ".." passes the name pattern: true; resolveInside("..") says: outside the base folder
    
    == 5. Deserialization: a strict JSON mapper, and native Java deserialization with a class allow-list
    strict JSON mapper with unknown fields id and admin: UnrecognizedPropertyException
    ShippingNote bytes: ShippingNote[orderId=o-100, parcels=2]
    ArrayList bytes: InvalidClassException: filter status: REJECTED
    
    == 6. Output encoding belongs to the place the data is shown (here: an HTML page body)
    stored as typed: Fish & Chips <b>half price</b>
    HtmlUtils.htmlEscape: Fish &amp; Chips &lt;b&gt;half price&lt;/b&gt;

    What the lab does not show. Other databases and their error codes, an ORM, symbolic links in the path check, a real deserialization attack (the filter rejects a harmless class) and the browser side of output encoding.

    Break it. In ProductRepository.findByName, replace the body with return new UnsafeProductQueries(dataSource).findByName(name);. The test aPreparedStatementTreatsTheSameTextAsData asserts the opposite of what the concatenated query does, so it, and the golden-file comparison, should fail; this particular experiment was not run for the lesson, so confirm it yourself. Put the original body back and re-run the tests.

    Stretch. Add a price-range search with between ? and ?, bound as integers, and test a non-numeric value.

    Trade-offs

    Option Gain Cost Wrong when
    Allow-list validation Rejects the unexpected Rules must follow the product Free text needs broad characters: use length and encoding
    Deny-list or sanitizing Quick to add Rejects real input, misses new forms It is the only defence
    Prepared statements Value never parsed as SQL A placeholder cannot name a column Identifiers come from the caller
    Key-to-column mapping Caller text never reaches SQL A list to maintain The columns are open-ended
    Strict JSON (reject unknown fields) Finds wrong clients early Breaks tolerant clients Many client versions send extras
    Native deserialization with a filter Narrows classes read Still risky The source is untrusted: use JSON into a DTO

    This is the realistic example, an educational scenario on ShopStream, the course's running grocery marketplace. It describes no real company, and every number is an illustrative assumption.

    NOTE

    This is a realistic scenario, not a case history. It is a composite built from common production patterns.

    The situation

    Customers search products by name and sort by price or name. The first version builds the search SQL by concatenation ("it was only one query") and passes the sort parameter straight into order by. Names such as "Farmer's Cheese" already exist, and a security review asks what happens when the text is not a product name at all.

    Starting architecture

    Figure 4. Starting point: user text goes into the statement

    Starting architecture: search text and sort text are pasted into the SQLStorefront to Search API (name, sort); Search API to Catalogue (concatenated SQL)Storefront: search box, sort menuStorefrontsearch box, sortmenuSearch API: builds SQL stringsSearch APIbuilds SQLstringsCatalogue: one shared accountCatalogueone sharedaccountname, sortconcatenated SQL

    How to read this: both warning boxes matter. The API turns caller text into statement text, and the database account it uses can do more than a search needs.

    Options considered

    Option What it fixes What it costs Risk
    A. Reject quotes and keywords in the name Looks safe for now Little code Rejects real names; new forms get through
    B. Prepared statements and key-to-column mapping Text never becomes SQL A rewrite of the query code Another route may still concatenate
    C. B plus Bean Validation and a read-only search account Narrow input, less damage A rule per request, a second account Two accounts to manage

    The decision

    Field Decision record
    Context Names contain apostrophes and ampersands; sort has two choices; search needs read access only.
    Decision Every query uses placeholders; sort is an enum; inputs have Bean Validation with length limits; search uses a read-only account.
    Consequences, good Benign punctuation works; hostile text is only data; a mistake elsewhere can read less.
    Consequences, bad Every new query needs the same review; rules must follow the product.
    Revisit when Search needs free-form filters that tempt dynamic SQL: use a query builder that binds values.

    Rollout and verification

    1. Add tests first: an ordinary name, a name with an apostrophe and the textbook tautology, against both endpoints.
    2. Search the code for concatenation near createStatement and executeQuery, and fail review for any new one.
    3. Check the account: the search service should not be able to write.
    4. Watch for SQL syntax errors on search endpoints: they signal injectable code, or a typo.

    The 2 a.m. failure

    Support reports that searching for "Farmer's Cheese" returns an error page. The logs show a SQL syntax error from the search service. A new "recent searches" feature added a query that concatenates the term, copied from an old example.

    First three checks: (1) find the statement text in the error and the line that built it; (2) search the repository for other concatenated queries; (3) check which database account the service uses. Mitigation: revert the deploy; do not patch with quote-stripping. Follow-up: use a placeholder, add the apostrophe test and a review rule against concatenated SQL.

    Architect's notes

    • Validate for meaning, bind for safety. Both jobs are needed.
    • Prefer allow-lists close to the data type, and never trust the browser's checks.
    • Return field and rule names in errors, not the value, the stack or the SQL.
    • Give each service the least database access it needs.

    Common mistakes

    • Treating validation as the SQL defence.
    • Deny-lists and quote stripping, which reject real names and still miss cases.
    • Trying to bind a column name or ASC/DESC. Map a key instead.
    • Binding domain objects directly to request bodies.
    • Native Java serialization for data from outside.
    • Encoding on input instead of on output for each context.

    Key takeaways

    • Validation checks acceptability; injection prevention keeps data from being read as code.
    • Use allow-lists, validate on the server, and bound lengths before matching with a regular expression.
    • Prepared statements send the value separately from the statement; concatenation does not.
    • Placeholders cannot name columns, so map a key to a column you own.
    • Path checks combine a plain-name allow-list with a normalized-path containment check.
    • Bind requests to small DTOs; native Java deserialization needs a class allow-list and is better avoided.
    • Encode output for the context where it appears.

    Practice exercises

    Exercise 1 (20 min). For a field quantity, a field notes (free text), a country code and a sortBy parameter, write the rule you would apply to each and say whether it is syntactic or semantic.

    Exercise 2 (1 hour). In the lab, add a category filter to search with a placeholder, and tests for an unknown category, a category with an apostrophe, and a missing category.

    Exercise 3 (half day). Review a service you know for every place text becomes something else: a query, a file name, a command line, a URL, a template, an object stream. List what stands between the input and each.

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments