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 Forms, Views & Interceptors — Interview Questions

Managing and submitting form data, @ModelAttribute, form validation with BindingResult, ViewResolvers and their types, InternalResourceViewResolver, ContentNegotiatingViewResolver, HandlerInterceptor methods, global interceptors and interceptor vs filter.

Published September 25, 2026


How to use this lesson

Form and view questions come up for server-rendered applications (Thymeleaf or JSP). Interceptor questions come up everywhere. For forms, the pattern to know by heart is PRG: POST, validate, then Redirect to a GET.

Q1. How do you manage form data in Spring MVC?

Short answer: Bind the form fields to a form-backing object with @ModelAttribute. Spring's data binder matches request parameters to properties by name, and converts their types. Use @RequestParam for one-off fields.

public class SignupForm {                                  // form-backing object
    @NotBlank private String name;
    @Email @NotBlank private String email;
    @Size(min = 8) private String password;
    // getters and setters (the binder uses them), or a record with a matching constructor
}

@GetMapping("/signup")
String showForm(Model model) {
    model.addAttribute("signupForm", new SignupForm());    // empty object for the form
    return "signup";
}

Learn it in depth → Bean Validation

Q2. How do you handle form submission?

Short answer: Use a @PostMapping method that takes the @Valid @ModelAttribute object and a BindingResult. If there are errors, redisplay the form. On success, process the data and redirect (Post/Redirect/Get), so that refreshing the page doesn't resubmit the form.

@PostMapping("/signup")
String submit(@Valid @ModelAttribute SignupForm form, BindingResult errors, RedirectAttributes flash) {
    if (errors.hasErrors()) return "signup";              // same view, with the field errors
    userService.register(form);
    flash.addFlashAttribute("message", "Welcome aboard!");
    return "redirect:/dashboard";                         // PRG: avoids duplicate submissions
}

Common trap: BindingResult must come immediately after the object it validates. Otherwise Spring throws a MethodArgumentNotValidException / BindException instead of giving you the errors.

Q3. What is @ModelAttribute for?

Short answer: It has two roles:

  1. On a parameter, it binds request data to an object, creating or retrieving it, and adds that object to the model.
  2. On a method, it adds data to the model before every handler in that controller. That's useful for reference data such as dropdown lists.
@ModelAttribute("countries")
List<String> countries() { return List.of("India", "Singapore", "Germany"); }   // available to every view of this controller

Q4. How does form validation work in Spring MVC?

Short answer: Annotate the form class with Bean Validation constraints (@NotBlank, @Email, @Size, @Pattern, and custom ones), and trigger validation with @Valid (or @Validated for validation groups). Errors land in the BindingResult, and the view shows them next to each field (in Thymeleaf, th:errors="*{email}").

Key points to cover:

  • Cross-field rules, such as "password equals confirmPassword", need a class-level constraint or a custom Validator.
  • Always validate on the server, even when the client validates too. Client-side checks are easily bypassed.

Learn it in depth → Bean Validation

Q5. What is a ViewResolver, and how does it work?

Short answer: A ViewResolver turns the logical view name a controller returns ("order-details") into an actual View object that renders the output. Controllers therefore never hard-code template paths or technologies. The DispatcherServlet asks each configured resolver in turn (by order) until one returns a view.

Q6. What types of ViewResolver exist?

Short answer:

  • InternalResourceViewResolver: JSPs.
  • ThymeleafViewResolver: Thymeleaf. This is Spring Boot's usual choice.
  • FreeMarkerViewResolver: FreeMarker.
  • BeanNameViewResolver: a view defined as a bean whose name matches the view name.
  • ContentNegotiatingViewResolver: delegates to other resolvers based on the requested media type.
  • Views such as MappingJackson2JsonView can render the model as JSON.

Key points to cover:

  • XmlViewResolver and ResourceBundleViewResolver were deprecated and removed in Spring 6.
  • For REST APIs you don't need a view resolver at all. Message converters write the body.

Q7. How does InternalResourceViewResolver work?

Short answer: It builds a path from prefix + view name + suffix, and forwards the request to that JSP inside the web application.

@Bean
InternalResourceViewResolver jspViewResolver() {
    InternalResourceViewResolver r = new InternalResourceViewResolver();
    r.setPrefix("/WEB-INF/views/");      // under WEB-INF, so JSPs can't be requested directly
    r.setSuffix(".jsp");
    return r;                            // "home" → /WEB-INF/views/home.jsp
}

Key points to cover:

  • It always "succeeds", because it can't check whether the JSP exists. So it must be the last resolver in the chain.

Q8. What are the advantages of ContentNegotiatingViewResolver?

Short answer: One controller method can serve several formats: HTML for browsers, JSON or XML for API clients. The resolver chooses the view from the requested media type (the Accept header, or a path extension or parameter if configured), and delegates to the matching view resolvers and default views.

Key points to cover:

  • In modern applications, separate @RestController endpoints, with produces and message converters, are the more common way to serve JSON.

Q9. How are interceptors used in Spring MVC?

Short answer: A HandlerInterceptor runs code before and after the handler executes. It's used for cross-cutting web concerns that need to know which handler runs: request timing, audit logging, tenant resolution, locale or theme changes, simple API-key checks, and adding common model attributes.

public class RequestTimingInterceptor implements HandlerInterceptor {
    @Override public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) {
        req.setAttribute("startNanos", System.nanoTime());
        return true;                                       // false = stop the chain (you write the response)
    }
    @Override public void afterCompletion(HttpServletRequest req, HttpServletResponse res, Object handler, Exception ex) {
        long ms = (System.nanoTime() - (long) req.getAttribute("startNanos")) / 1_000_000;
        log.info("{} {} took {} ms (status {})", req.getMethod(), req.getRequestURI(), ms, res.getStatus());
    }
}

Q10. What methods does the HandlerInterceptor interface have?

Short answer:

  1. preHandle: runs before the handler. Returning false stops processing.
  2. postHandle: runs after the handler, before the view renders. It can modify the ModelAndView. It's not called if the handler threw an exception, and for @ResponseBody methods the response has already been written.
  3. afterCompletion: runs after the request completes, even on exceptions (it receives the exception). Use it for cleanup and timing.

Key points to cover:

  • All three are default methods since Spring 5, so you override only the ones you need.

Q11. How do you apply an interceptor globally?

Short answer: Register it in a WebMvcConfigurer. Without path patterns, it applies to every handler. Narrow it with addPathPatterns and excludePathPatterns.

@Configuration
class WebConfig implements WebMvcConfigurer {
    @Override public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new RequestTimingInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns("/actuator/**", "/static/**");
    }
}

Q12. What's the difference between a Spring MVC interceptor and a servlet filter?

Short answer:

Servlet filterSpring MVC interceptor
LayerServlet container, before the DispatcherServletInside Spring MVC, around handler execution
Applies toEvery request (static resources, other servlets)Requests dispatched to Spring handlers
Knows the handler?NoYes (method, annotations)
Can replace request/response objectsYes (wrap them)No
Typical usesSecurity (Spring Security), CORS, compression, encoding, request loggingTiming, auditing, handler-specific checks, model enrichment

Follow-up questions this topic invites — and their answers

Q: What is a flash attribute? A: A value stored temporarily (in the session) so that it survives one redirect, typically a success message after a PRG redirect. It's added with RedirectAttributes.addFlashAttribute.

Q: How do you protect forms against CSRF? A: Spring Security's CSRF protection (on by default for session-based apps) requires a token in each state-changing request. Thymeleaf adds it to forms automatically. Stateless token-authenticated APIs usually disable CSRF.

Q: How do you bind a date field from a form? A: Annotate the field with @DateTimeFormat(iso = ISO.DATE), or register a Formatter or Converter. java.time types such as LocalDate are supported directly.

Q: Where would you put authentication checks: filter or interceptor? A: In the filter chain, through Spring Security, so that every entry point is protected before any MVC processing happens. Interceptors are fine for finer, handler-aware checks on top of that.

Previous

Spring MVC Request Mapping & Controllers — Interview Questions

Next

Spring MVC Exceptions, Security & Dependency Injection — Interview Questions

AI Tutor

Lesson: Spring MVC Forms, Views & Interceptors — Interview Questions

Quick actions

AI responses can be inaccurate. Verify critical information.