Chaturmind
LearnDSASystem DesignInterview PrepDevOpsEngineering GrowthBlog
Start learning
Chaturmind

Structured learning paths for engineers who want to go deep. Written by practitioners.

Learn

  • Java
  • DSA
  • System Design
  • Spring Boot
  • AI / ML
  • DevOps
  • Engineering Growth
  • Java Interview Prep

Company

  • Blog
  • Contact

Legal

  • Privacy Policy
  • Terms of Service

© 2026 Chaturmind. All rights reserved.

Built for engineers who want to go deep.


← Java Interview Prep: Fresher to 2 Years

Java Basics, JVM & Memory

  • JDK, JRE, JVM & the main Method — Interview Questions
  • JVM Memory & Garbage Collection — Interview Questions
  • Data Types, Wrapper Classes & Equality — Interview Questions

Object-Oriented Programming

  • Classes, Objects, Packages & Access Modifiers — Interview Questions
  • Inheritance, Composition, this & super — Interview Questions
  • Polymorphism, Overloading & Overriding — Interview Questions
  • Abstraction, Interfaces & Encapsulation — Interview Questions
  • Constructors, Singleton, Anonymous Classes & Immutability — Interview Questions
  • Design Patterns & SOLID Basics — Interview Questions

Strings, Keywords, Exceptions & Serialization

  • Strings, String Pool, StringBuilder & StringBuffer — Interview Questions
  • static & final Keywords — Interview Questions
  • Exceptions, Generics, Enums & Reflection — Interview Questions
  • Serialization & transient — Interview Questions

Collections Framework

  • Collections Framework Basics — Interview Questions
  • HashMap, HashSet & TreeMap Internals — Interview Questions

Multithreading Basics

  • Threads, Synchronization & volatile Basics — Interview Questions

Java 8+ & Stream API

  • Java 8 to Java 21 Features — Interview Questions
  • Stream API Coding Questions (Part 1) — Interview Questions
  • Stream API Coding Questions (Part 2) — Interview Questions

Coding Round Programs

  • Classic Number & String Programs — Interview Questions
  • String & Collection Programs — Interview Questions
  • Array & String Problem Solving — Interview Questions

Spring Framework Core

  • Spring IoC, Dependency Injection & Beans — Interview Questions
  • Spring Injection Types, Scopes, Profiles & WebFlux — Interview Questions

Spring Boot Essentials

  • Spring Boot Fundamentals — Interview Questions
  • Spring Boot Runners, Servers & Configuration — Interview Questions
  • Spring Boot Controllers, Profiles, Actuator & DevTools — Interview Questions
  • Spring Boot Testing, Exceptions & Auto-Configuration — Interview Questions
  • REST APIs, Swagger, Embedded Servers & Key Annotations — Interview Questions

Spring MVC

  • Spring MVC Architecture & DispatcherServlet — Interview Questions
  • Spring MVC Request Mapping & Controllers — Interview Questions
  • Spring MVC Forms, Views & Interceptors — Interview Questions
  • Spring MVC Exceptions, Security & Dependency Injection — Interview Questions
  • Spring MVC Data Binding, Static Resources & Path Variables — Interview Questions
  • Spring MVC i18n, Testing, File Uploads & Scaling — Interview Questions

Hibernate & Spring Data JPA

  • Hibernate & JPA Core Concepts — Interview Questions
  • Hibernate Performance, Mapping & Scenarios — Interview Questions

SQL

  • SQL Basics, Keys, Normalization & Transactions — Interview Questions
  • SQL Joins, Triggers, Procedures, Functions & Indexes — Interview Questions
  • SQL "Difference Between" Questions — Interview Questions
  • SQL Query Writing (Part 1) — Interview Questions
  • SQL Query Writing (Part 2) — Interview Questions

Microservices Basics

  • Microservices, API Gateway & Communication — Interview Questions
  • Service Discovery, Data Consistency & Deployment — Interview Questions
  • Microservices Monitoring, Security & Resilience — Interview Questions

Maven & Git

  • Maven — Interview Questions
  • Git — Interview Questions
Chaturmind
← Java Interview Prep: Fresher to 2 Years

Java Basics, JVM & Memory

  • JDK, JRE, JVM & the main Method — Interview Questions
  • JVM Memory & Garbage Collection — Interview Questions
  • Data Types, Wrapper Classes & Equality — Interview Questions

Object-Oriented Programming

  • Classes, Objects, Packages & Access Modifiers — Interview Questions
  • Inheritance, Composition, this & super — Interview Questions
  • Polymorphism, Overloading & Overriding — Interview Questions
  • Abstraction, Interfaces & Encapsulation — Interview Questions
  • Constructors, Singleton, Anonymous Classes & Immutability — Interview Questions
  • Design Patterns & SOLID Basics — Interview Questions

Strings, Keywords, Exceptions & Serialization

  • Strings, String Pool, StringBuilder & StringBuffer — Interview Questions
  • static & final Keywords — Interview Questions
  • Exceptions, Generics, Enums & Reflection — Interview Questions
  • Serialization & transient — Interview Questions

Collections Framework

  • Collections Framework Basics — Interview Questions
  • HashMap, HashSet & TreeMap Internals — Interview Questions

Multithreading Basics

  • Threads, Synchronization & volatile Basics — Interview Questions

Java 8+ & Stream API

  • Java 8 to Java 21 Features — Interview Questions
  • Stream API Coding Questions (Part 1) — Interview Questions
  • Stream API Coding Questions (Part 2) — Interview Questions

Coding Round Programs

  • Classic Number & String Programs — Interview Questions
  • String & Collection Programs — Interview Questions
  • Array & String Problem Solving — Interview Questions

Spring Framework Core

  • Spring IoC, Dependency Injection & Beans — Interview Questions
  • Spring Injection Types, Scopes, Profiles & WebFlux — Interview Questions

Spring Boot Essentials

  • Spring Boot Fundamentals — Interview Questions
  • Spring Boot Runners, Servers & Configuration — Interview Questions
  • Spring Boot Controllers, Profiles, Actuator & DevTools — Interview Questions
  • Spring Boot Testing, Exceptions & Auto-Configuration — Interview Questions
  • REST APIs, Swagger, Embedded Servers & Key Annotations — Interview Questions

Spring MVC

  • Spring MVC Architecture & DispatcherServlet — Interview Questions
  • Spring MVC Request Mapping & Controllers — Interview Questions
  • Spring MVC Forms, Views & Interceptors — Interview Questions
  • Spring MVC Exceptions, Security & Dependency Injection — Interview Questions
  • Spring MVC Data Binding, Static Resources & Path Variables — Interview Questions
  • Spring MVC i18n, Testing, File Uploads & Scaling — Interview Questions

Hibernate & Spring Data JPA

  • Hibernate & JPA Core Concepts — Interview Questions
  • Hibernate Performance, Mapping & Scenarios — Interview Questions

SQL

  • SQL Basics, Keys, Normalization & Transactions — Interview Questions
  • SQL Joins, Triggers, Procedures, Functions & Indexes — Interview Questions
  • SQL "Difference Between" Questions — Interview Questions
  • SQL Query Writing (Part 1) — Interview Questions
  • SQL Query Writing (Part 2) — Interview Questions

Microservices Basics

  • Microservices, API Gateway & Communication — Interview Questions
  • Service Discovery, Data Consistency & Deployment — Interview Questions
  • Microservices Monitoring, Security & Resilience — Interview Questions

Maven & Git

  • Maven — Interview Questions
  • Git — Interview Questions
HomeLearnJava Interview PrepJava Interview Prep: Fresher to 2 YearsSpring MVC
✓ FreeBeginner· 7 min read

Spring MVC Data Binding, Static Resources & Path Variables — Interview Questions

How data binding works, @RequestParam, customising binding with @InitBinder and converters, binding pitfalls (including mass assignment), serving static resources and making them fast, Spring's Resource abstraction, and @PathVariable design.

Published September 25, 2026


How to use this lesson

Data binding looks like magic until it binds a field you didn't intend. That's why "challenges of data binding" is really a security question. The static-resource and URL-design questions reward practical, performance-minded answers.

Q1. How does Spring MVC support data binding?

Short answer: Spring's WebDataBinder copies request data (query parameters, form fields, path variables) into handler arguments and objects, converting types along the way through its ConversionService (String → int, LocalDate, enums, …). Binding and validation errors are collected in a BindingResult. JSON bodies take a different path: @RequestBody is deserialised by message converters (Jackson), not by the data binder.

Key points to cover:

  • Forms and query parameters go through the data binder. JSON goes through Jackson. Different annotations, and different error types (BindException vs HttpMessageNotReadableException).

Learn it in depth → Bean Validation

Q2. What does @RequestParam do?

Short answer: It binds a query-string or form parameter to a method argument, with optional required, defaultValue and type conversion.

@GetMapping("/products")
Page<ProductDto> search(@RequestParam(required = false) String q,
                        @RequestParam(defaultValue = "0") int page,
                        @RequestParam(defaultValue = "20") int size,
                        @RequestParam(name = "tag", required = false) List<String> tags) {   // ?tag=a&tag=b
    …
}

Key points to cover:

  • A missing required parameter causes a 400 (MissingServletRequestParameterException). A conversion failure (?page=abc) also gives a 400.
  • @RequestParam Map<String, String> captures all the parameters.

Q3. How do you customise data binding for complex objects?

Short answer: In increasing scope:

  • @InitBinder methods in a controller or @ControllerAdvice: register custom editors, set allowed or disallowed fields, trim strings.
  • Global Converter/Formatter beans, registered through WebMvcConfigurer.addFormatters, or simply as beans in Spring Boot.
  • Annotations such as @DateTimeFormat and @NumberFormat.
@ControllerAdvice
class BindingConfig {
    @InitBinder
    void init(WebDataBinder binder) {
        binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));   // "  " → null
    }
}

@Component
class SkuConverter implements Converter<String, Sku> {          // ?sku=AB-123 → Sku value object
    public Sku convert(String source) { return Sku.parse(source); }
}

Q4. What are the challenges with data binding, and how do you address them?

Short answer:

  • Type-conversion errors: handle them through BindingResult, or a global handler that returns clear 400 messages.
  • Complex and nested types: use converters and formatters.
  • Validation: Bean Validation, plus custom validators.
  • Security, meaning mass assignment: an attacker can add parameters such as role=ADMIN or price=0, and the binder will happily set any matching property.

Key points to cover:

  • Defend against mass assignment with dedicated form or request DTOs that contain only the fields a user may set. Or restrict binding with binder.setAllowedFields(...). Never bind directly onto entities.

Common trap: binding an @Entity straight from a form. It's the classic mass-assignment hole (see OWASP's Mass Assignment cheat sheet).

Q5. How do you handle static resources in Spring MVC?

Short answer:

  • In Spring Boot, files in classpath:/static/, /public/, /resources/ or /META-INF/resources/ are served automatically from the root path. For example, src/main/resources/static/css/app.css is served at /css/app.css.
  • In classic Spring MVC, register resource handlers:
@Configuration
class StaticResourceConfig implements WebMvcConfigurer {
    @Override public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/assets/**")
                .addResourceLocations("classpath:/static/assets/")
                .setCacheControl(CacheControl.maxAge(Duration.ofDays(365)).cachePublic());
    }
}

Common trap: adding @EnableWebMvc in a Boot app while doing this. It turns off Boot's default static-resource handling.

Q6. How do you configure Spring MVC to serve CSS, JavaScript or images?

Short answer: Put them in a static location (Boot), or map a URL pattern to a location with addResourceHandlers. Reference them from templates with context-aware URLs (for example, Thymeleaf's @{/css/app.css}), so they keep working behind a context path.

Q7. How does resource handling affect application performance?

Short answer: Static files are a large share of page weight, so how they're served matters:

  • HTTP caching: long Cache-Control max-age for immutable files, plus ETag or Last-Modified for validation.
  • Cache-busting versioned URLs: Spring's VersionResourceResolver produces content-hash file names such as app-3f9a1c.css, so they can be cached "forever" but change the moment the content does.
  • Compression: server.compression.enabled=true, or pre-compressed gzip/brotli files.
  • Offloading to a CDN or reverse proxy, so application threads aren't spent streaming files.
registry.addResourceHandler("/assets/**")
        .addResourceLocations("classpath:/static/assets/")
        .setCacheControl(CacheControl.maxAge(Duration.ofDays(365)))
        .resourceChain(true)
        .addResolver(new VersionResourceResolver().addContentVersionStrategy("/**"));

Q8. How does Spring manage resources differently in a web application context?

Short answer: Spring's Resource abstraction loads files uniformly from different places:

  • classpath: → ClassPathResource;
  • file: → FileSystemResource;
  • http: → UrlResource;
  • and, in a web application context, paths relative to the web app root, resolved as ServletContextResource (such as /WEB-INF/…).

A WebApplicationContext resolves unprefixed paths against the servlet context rather than the classpath. It also adds the web-specific bean scopes (request, session, application).

@Value("classpath:templates/invoice.html") Resource invoiceTemplate;
Resource logo = applicationContext.getResource("/WEB-INF/images/logo.png");   // ServletContextResource

Key points to cover:

  • Inside a packaged JAR, classpath resources aren't files. Read them with getInputStream(), not getFile().

Q9. What is the role of @PathVariable?

Short answer: It binds a segment of the URL path (a URI template variable) to a method parameter. It identifies which resource the request is about, as in /orders/{orderId}.

@GetMapping("/customers/{customerId}/orders/{orderId}")
OrderDto get(@PathVariable long customerId, @PathVariable long orderId) { … }

Q10. How do you extract values from a URL with @PathVariable?

Short answer: Declare placeholders in the mapping, and matching parameters (by name, or @PathVariable("id")). Spring converts the text to the parameter type. You can also constrain the format with a regex: @GetMapping("/files/{name:[a-z0-9-]+}.{ext}").

Key points to cover:

  • @PathVariable Map<String, String> captures all the variables.
  • Parameter-name matching relies on compiling with -parameters. Spring Boot's parent POM enables it. Otherwise, name the variable explicitly.

Q11. What should you consider when designing URLs with @PathVariable?

Short answer:

  • Use path variables for identity (/orders/42), and query parameters for filters and options (/orders?status=PAID).
  • Use clear, stable names and plural nouns, and keep nesting shallow (/customers/7/orders, not five levels deep).
  • Avoid ambiguity between literal and variable segments. /orders/latest vs /orders/{id} works, because literals win, but it's fragile.
  • Never trust IDs from the URL for authorisation. Check that the current user may access that resource (avoid IDOR).
  • Prefer opaque or UUID identifiers when sequential IDs would leak business data.

Q12. How does @PathVariable interact with other request mappings?

Short answer: Class-level and method-level patterns are combined, so variables can appear at either level. @PathVariable works alongside @RequestParam, @RequestBody and headers in the same method. When several mappings could match, Spring chooses the most specific (fewest variables and wildcards). Two equally specific mappings cause a startup error.

@RestController
@RequestMapping("/tenants/{tenantId}/invoices")
class InvoiceController {
    @GetMapping("/{invoiceId}")
    InvoiceDto get(@PathVariable String tenantId, @PathVariable long invoiceId,
                   @RequestParam(defaultValue = "false") boolean includeLines) { … }
}

Follow-up questions this topic invites — and their answers

Q: What's the difference between @RequestParam and @ModelAttribute? A: @RequestParam binds a single parameter. @ModelAttribute binds many parameters onto an object's properties (and adds the object to the model). It's useful for search forms with many optional filters.

Q: How do you make a path variable optional? A: Map two paths to the same method (@GetMapping({"/reports", "/reports/{year}"})), and declare @PathVariable(required = false) Integer year, or use Optional<Integer>.

Q: How do you trim whitespace from all incoming string parameters? A: Register a StringTrimmerEditor in an @InitBinder method inside a @ControllerAdvice. For JSON bodies, configure a Jackson deserialiser instead.

Q: Where should static files live in a modern setup? A: For SPAs, usually on a CDN or object storage, built by the frontend pipeline. The Spring app then serves only the API. Serving from /static is fine for server-rendered apps and admin pages.

Previous

Spring MVC Exceptions, Security & Dependency Injection — Interview Questions

Next

Spring MVC i18n, Testing, File Uploads & Scaling — Interview Questions

AI Tutor

Lesson: Spring MVC Data Binding, Static Resources & Path Variables — Interview Questions

Quick actions

AI responses can be inaccurate. Verify critical information.