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· 9 min read

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

LocaleResolver and switching languages, @SessionAttributes and @CookieValue (and their security), testing with MockMvc and Mockito, integration testing, file uploads end to end, JPA/WebSocket integration, high-traffic features, caching, async processing and horizontal scaling.

Published September 25, 2026


How to use this lesson

This lesson collects the "rounding out" Spring MVC questions: internationalisation, sessions and cookies, testing, uploads, and performance. For the scaling questions, show that you understand statelessness. It's the idea everything else depends on.

Q1. How does Spring MVC use a LocaleResolver?

Short answer: A LocaleResolver determines the locale of each request. MessageSource then uses it to pick translated messages (messages_hi.properties, messages_fr.properties), and formatters use it for dates and numbers.

ResolverWhere the locale comes from
AcceptHeaderLocaleResolver (Boot default)The browser's Accept-Language header
SessionLocaleResolverStored in the HTTP session
CookieLocaleResolverStored in a cookie
FixedLocaleResolverAlways the same locale

Q2. How do you let users change the language dynamically?

Short answer: Use a LocaleChangeInterceptor, which reads a request parameter such as ?lang=hi, together with a resolver that can store the choice (session or cookie). A language dropdown then just links to the current page with ?lang=….

@Configuration
class I18nConfig implements WebMvcConfigurer {
    @Bean LocaleResolver localeResolver() {
        CookieLocaleResolver r = new CookieLocaleResolver("lang");
        r.setDefaultLocale(Locale.ENGLISH);
        return r;
    }
    @Override public void addInterceptors(InterceptorRegistry registry) {
        LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
        lci.setParamName("lang");                                     // /products?lang=hi
        registry.addInterceptor(lci);
    }
}
// templates: <h1 th:text="#{products.title}">…</h1>  → looked up in messages_hi.properties

Key points to cover:

  • In SPAs, translation usually happens on the client (i18next and similar). The API can still honour Accept-Language for server-generated messages and validation errors.

Q3. What are @SessionAttributes and @CookieValue for?

Short answer:

  • @SessionAttributes("wizardForm"), on a controller class, stores the named model attributes in the HTTP session across requests. It's typical for multi-step forms and wizards. Call SessionStatus.setComplete() at the end to clear them.
  • @CookieValue("theme") binds a cookie's value to a handler parameter.
@Controller
@SessionAttributes("checkout")
class CheckoutWizard {
    @PostMapping("/checkout/address")  String address(@ModelAttribute("checkout") CheckoutForm f) { return "redirect:/checkout/payment"; }
    @PostMapping("/checkout/confirm")  String confirm(@ModelAttribute("checkout") CheckoutForm f, SessionStatus status) {
        orders.place(f);
        status.setComplete();                        // remove it from the session
        return "redirect:/orders";
    }
    @GetMapping("/")
    String home(@CookieValue(name = "theme", defaultValue = "light") String theme) { … }
}

Q4. What are the security considerations for @SessionAttributes and @CookieValue?

Short answer:

  • Sessions: don't store secrets or large objects. Always clear wizard state when it's done. Protect against session fixation (Spring Security changes the session ID on login). Set sensible timeouts.
  • Cookies: treat every cookie value as untrusted user input. Validate it, and never base authorisation decisions on it unless it's signed. Set the HttpOnly, Secure and SameSite flags. Don't put sensitive data in cookies unless it's encrypted.
  • Remember that session state blocks horizontal scaling unless the session is externalised (see Q15).

Q5. How do you test Spring MVC applications?

Short answer:

  • Unit-test controllers with mocked services.
  • Slice-test the web layer with @WebMvcTest and MockMvc, which performs requests without a real server and checks the status, headers, JSON and views.
  • Integration-test the whole stack with @SpringBootTest, using MockMvc, TestRestTemplate or WebTestClient.
@WebMvcTest(ProductController.class)
class ProductControllerTest {
    @Autowired MockMvc mvc;
    @MockitoBean ProductService service;

    @Test void rejectsInvalidProduct() throws Exception {
        mvc.perform(post("/api/v1/products").contentType(MediaType.APPLICATION_JSON)
                .content("{\"name\": \"\", \"price\": -5}"))
           .andExpect(status().isBadRequest());
        verifyNoInteractions(service);
    }
}

Q6. Which frameworks are used to test Spring MVC components?

Short answer:

  • JUnit 5 (the test engine).
  • Mockito (mocks).
  • Spring Test / Spring Boot Test: MockMvc, @WebMvcTest, @SpringBootTest, test slices.
  • AssertJ and Hamcrest (assertions), plus JsonPath for JSON.
  • Testcontainers (real databases and brokers).
  • WireMock (stubbed external HTTP APIs).
  • REST Assured, an alternative DSL for HTTP tests.
  • spring-security-test (@WithMockUser).

Q7. How do you mock Spring MVC dependencies for unit tests?

Short answer: In a pure unit test, create the controller with new, passing Mockito mocks. In a web-slice test, @WebMvcTest loads only the MVC components, and @MockitoBean (Boot 3.4+, formerly @MockBean) replaces each service bean in the context with a mock that you stub.

Key points to cover:

  • Keep controllers thin. Then controller tests verify HTTP concerns (mapping, validation, status codes, serialisation), and business logic is tested separately.

Q8. What are the best practices for integration testing Spring MVC?

Short answer:

  • Use @SpringBootTest sparingly, for real end-to-end flows.
  • Use real infrastructure through Testcontainers (@ServiceConnection) instead of in-memory substitutes.
  • Stub third-party HTTP services with WireMock.
  • Isolate test data: transactional rollback, or cleaning up per test.
  • Keep context configuration consistent, so Spring's context cache gets reused.
  • Test security rules and error responses, not only the happy paths.

Q9. How does Spring MVC support file uploads?

Short answer: Multipart requests (enctype="multipart/form-data") are parsed by a MultipartResolver. Spring Boot auto-configures StandardServletMultipartResolver, which uses the Servlet API's built-in multipart support. Each uploaded file arrives as a MultipartFile, giving you its name, size and content type, an InputStream, and transferTo.

Q10. What configuration is needed to enable file uploads?

Short answer: In Spring Boot, multipart support is on by default. Set the limits:

spring:
  servlet:
    multipart:
      max-file-size: 10MB        # per file (default 1MB)
      max-request-size: 25MB     # whole request (default 10MB)

The HTML form needs method="post" and enctype="multipart/form-data". In classic Spring MVC, register a MultipartResolver bean named multipartResolver, and configure the servlet's MultipartConfigElement.

Q11. How do you handle a file upload in a controller?

Short answer: Take a MultipartFile parameter with @RequestParam (or @RequestPart for mixed JSON-plus-file requests). Validate it, then stream it to storage.

@PostMapping(value = "/documents", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
ResponseEntity<DocumentDto> upload(@RequestParam("file") MultipartFile file) throws IOException {
    if (file.isEmpty()) throw new BadRequestException("empty file");
    if (!Set.of("application/pdf", "image/png").contains(file.getContentType()))
        throw new BadRequestException("unsupported type");
    String key = UUID.randomUUID() + ".bin";                         // never trust the client's file name as a path
    try (InputStream in = file.getInputStream()) {
        storage.put(key, in, file.getSize());                        // e.g. S3 or blob storage
    }
    return ResponseEntity.status(HttpStatus.CREATED).body(new DocumentDto(key, file.getOriginalFilename()));
}

Q12. What are the common file-upload problems, and their solutions?

Short answer:

ProblemSolution
Files exceed the limits (MaxUploadSizeExceededException)Set max-file-size and max-request-size; handle the exception with a clear 413 response
Wrong or dangerous file typesCheck the extension and the actual content (magic bytes, for example with Apache Tika); scan for malware
Path traversal (a file name containing .. segments that climbs out of the upload folder)Generate your own storage names; never build paths from getOriginalFilename()
Slow or huge uploads tying up app threadsUpload directly to object storage with pre-signed URLs; raise timeouts only for the upload endpoints
Memory pressureStream (getInputStream) instead of getBytes(); set file-size-threshold so large files spill to disk

Q13. How can Spring MVC be integrated with technologies such as JPA or WebSocket?

Short answer:

  • JPA: controllers call services that use Spring Data JPA repositories, with @Transactional in the service layer. Keep entities out of the web layer by mapping them to DTOs.
  • WebSocket: for real-time features, use @EnableWebSocketMessageBroker with STOMP (@MessageMapping handlers, SimpMessagingTemplate to push messages to subscribers), or raw handlers with @EnableWebSocket. Server-Sent Events (SseEmitter) are a simpler option for one-way pushes.

Q14. What Spring MVC features help high-traffic applications?

Short answer:

  • Asynchronous request processing frees container threads during slow I/O.
  • Caching with @Cacheable and HTTP caching (ETags).
  • Connection pooling (HikariCP) and HTTP client pooling.
  • Pagination and lean DTOs.
  • Compression.
  • Virtual threads (spring.threads.virtual.enabled=true, Java 21+), which make blocking code scale cheaply.
  • Rate limiting and observability (Micrometer metrics, tracing), so you can find the bottlenecks.

Q15. How do you implement caching in Spring MVC?

Short answer: Enable Spring's cache abstraction with @EnableCaching, annotate service methods with @Cacheable, and evict with @CacheEvict (or update with @CachePut) when the data changes. Plug in a provider: Caffeine for local caching, Redis for a cache shared across instances.

@Cacheable(cacheNames = "products", key = "#id")
public ProductDto find(long id) { return mapper.toDto(repository.findById(id).orElseThrow()); }

@CacheEvict(cacheNames = "products", key = "#id")
public void update(long id, UpdateProduct cmd) { … }

Key points to cover:

  • Also use HTTP caching: ResponseEntity.ok().eTag(...) and Cache-Control headers, so clients and CDNs avoid repeat requests entirely.
  • Caching is proxy-based, so self-invocation bypasses it.

Learn it in depth → Caching Strategies

Q16. What strategies exist for asynchronous processing in Spring MVC?

Short answer: A handler can return a type that lets the container thread go back to the pool while the work finishes elsewhere:

  • Callable<T>: Spring runs it on a task executor.
  • DeferredResult<T>: completed later by another thread, for example when a message arrives.
  • CompletableFuture<T>.
  • WebAsyncTask: a Callable with a timeout and a custom executor.
  • SseEmitter/ResponseBodyEmitter: stream events.

Separately, @Async runs a service method in the background ("fire and forget", or a returned future).

@GetMapping("/reports/{id}")
CompletableFuture<ReportDto> report(@PathVariable long id) {
    return reportService.generateAsync(id);          // the request thread is released while the report builds
}

Q17. How do you scale a Spring MVC application horizontally?

Short answer:

  • Run multiple identical instances behind a load balancer.
  • Keep the application stateless: token-based authentication, or sessions externalised to Spring Session with Redis, so any instance can serve any request.
  • Share caches (Redis), and make scheduled jobs cluster-safe (ShedLock).
  • Scale the data tier with read replicas, connection limits, and sharding when needed.
  • Automate scaling with container orchestration (the Kubernetes HPA), guided by metrics.

Key points to cover:

  • Sticky sessions are a stop-gap. They break failover and even load distribution.

Learn it in depth → Horizontal vs Vertical Scaling

Follow-up questions this topic invites — and their answers

Q: What does MockMvc not test? A: The real servlet container, and the network: real HTTP connectors, TLS, compression, and some filter orderings. Use @SpringBootTest(webEnvironment = RANDOM_PORT) with a real HTTP client for those.

Q: How do you serve a large file download efficiently? A: Stream it, with ResponseEntity<Resource> (such as an InputStreamResource or FileSystemResource) or StreamingResponseBody, and set Content-Disposition and Content-Length. Or redirect to a pre-signed object-storage URL.

Q: What's the difference between @Async and async request processing? A: @Async runs a method on another thread, and the caller carries on without waiting for the method to finish. Async request processing, by returning Callable or DeferredResult, keeps the HTTP request open, but releases the container thread until the result is ready.

Q: How do you share the HTTP session across instances? A: Add spring-session-data-redis. Spring Session replaces the container's session with one stored in Redis, transparently, so HttpSession works the same on every instance.

Previous

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

Next

Hibernate & JPA Core Concepts — Interview Questions

AI Tutor

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

Quick actions

AI responses can be inaccurate. Verify critical information.