Skip to content
Tutorials Center
My learning

Topics

Lesson 66 of 119 ยท Spring Framework

Spring MVC

How Spring MVC handles a web request - the DispatcherServlet, handler mappings, controllers, models, view resolvers, Thymeleaf templates and redirects.

Spring MVC is the part of the Spring Framework that turns HTTP requests into calls to your Java methods. You write small, focused controller classes; Spring finds the right method for each URL, converts the request into method arguments, calls your code, and turns the result into a response: an HTML page rendered from a template, or JSON for an API. Almost every Spring web application, including every Spring Boot web app, runs on it.

In this lesson you will follow a request through Spring MVC step by step. You will see the DispatcherServlet (the single entry point), handler mappings (which method handles which URL), handler adapters (how arguments are prepared), and view resolvers (how a view name becomes HTML). Because Spring itself can't run on this page, each idea comes with a small runnable program that rebuilds the mechanism in plain Java. You should know Servlets and Beans, Configuration and Component Scanning first.

The front controller pattern

In a plain servlet application, each servlet is mapped to its own URL, and each one repeats the same chores: parse parameters, convert types, pick a view, handle errors. Spring MVC replaces that with one servlet, the DispatcherServlet, mapped to /. It receives every request and delegates the work to specialized components. This design is called the front controller pattern.

Here is the full journey of GET /products/42:

TEXT
Browser โ”€โ”€ GET /products/42 โ”€โ”€โ–ถ Servlet container (Tomcat, Jetty)
                                   โ”‚
                         Servlet filters (security, encoding, ...)
                                   โ”‚
                                   โ–ผ
                          DispatcherServlet
   1. HandlerMapping      which handler?        โ†’ ProductController#show
   2. Interceptors        preHandle(...)
   3. HandlerAdapter      resolve arguments, call the method
                          @PathVariable 42 โ†’ long id; Model โ†’ returns "products/detail"
   4. Interceptors        postHandle(...)
   5. ViewResolver        "products/detail"     โ†’ templates/products/detail.html
   6. View                render(model)         โ†’ HTML
   7. Interceptors        afterCompletion(...)
                                   โ”‚
Browser โ—€โ”€โ”€ 200 text/html โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Each numbered step is an interface with one or more implementations that Spring registers for you:

Component Job Typical implementation
HandlerMapping Find the handler for a request RequestMappingHandlerMapping (reads @RequestMapping annotations)
HandlerAdapter Invoke the handler, whatever its shape RequestMappingHandlerAdapter (resolves arguments, handles return values)
HandlerInterceptor Run code before/after handlers Your own: logging, locale, timing
ViewResolver Turn a view name into a View ThymeleafViewResolver, InternalResourceViewResolver (JSP)
HandlerExceptionResolver Turn exceptions into responses ExceptionHandlerExceptionResolver (@ExceptionHandler)

You rarely touch these classes directly, but knowing them explains most surprises: a 404 means no HandlerMapping matched; an "unresolvable argument" error comes from the adapter; a "template not found" error comes from the view resolver.

Your first controller

A controller is a bean annotated with @Controller. Its methods are mapped to URLs with @GetMapping, @PostMapping and friends (all shortcuts for @RequestMapping(method = ...)). A method that renders a page adds data to a Model and returns a view name:

Java
package com.example.shop.web;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/products")              // prefix for every method in this class
public class ProductController {

    private final ProductService products;

    public ProductController(ProductService products) {   // constructor injection
        this.products = products;
    }

    @GetMapping                            // GET /products
    public String list(Model model) {
        model.addAttribute("products", products.findAll());
        return "products/list";            // โ†’ templates/products/list.html
    }

    @GetMapping("/{id}")                   // GET /products/42
    public String show(@PathVariable long id, Model model) {
        model.addAttribute("product", products.get(id));
        return "products/detail";
    }

    @GetMapping("/search")                 // GET /products/search?q=lamp
    public String search(@RequestParam(defaultValue = "") String q, Model model) {
        model.addAttribute("query", q);
        model.addAttribute("results", products.search(q));
        return "products/search";
    }
}

The controller contains no servlet code at all: no HttpServletRequest, no getParameter, no string-to-number conversion. Those chores belong to the framework. That also makes the class easy to unit test: call show(42, model) and check the model.

The program below rebuilds steps 1, 3, 5 and 6 of the flow in about 80 lines. A HandlerMapping scans controller beans for a custom @GetMapping annotation with reflection, an adapter fills in method arguments (here only Model), and a view resolver finds a template and renders it. Watch the log: it prints each step for each request.

Java A tiny DispatcherServlet

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The controller never mentions templates, HTML or HTTP. It only decides what to show (the model) and which page shows it (the view name). The framework decides how. Real Spring adds the missing pieces: HTTP methods, path patterns, dozens of argument types, content negotiation and error handling.

Mapping requests

@RequestMapping and its shortcuts can match on much more than the path:

Java
@GetMapping("/orders/{id}")                              // path variable
@GetMapping("/files/**")                                 // any sub-path
@GetMapping(value = "/report", params = "format=csv")    // only if ?format=csv is present
@GetMapping(value = "/report", produces = "text/csv")    // only if the client accepts text/csv
@PostMapping(value = "/orders", consumes = "application/json")
@GetMapping({"/", "/home"})                              // several paths

When several mappings match, Spring picks the most specific one: /products/search beats /products/{id}, and both beat /products/**. Order in the source file doesn't matter.

Handler methods can declare many kinds of parameters, and the adapter fills each one in:

Parameter Filled with
@PathVariable long id A part of the URL, converted to the declared type
@RequestParam String q A query string or form parameter (required unless required = false, defaultValue or Optional)
@RequestHeader("Accept-Language") String lang A request header
@CookieValue("theme") String theme A cookie
@ModelAttribute ProductForm form A new object whose fields are bound from request parameters
@RequestBody OrderInput input The body, converted from JSON (used in REST controllers)
Model, Locale, Principal, HttpSession Framework objects for the current request

Type conversion is automatic. If the URL says /products/abc and the parameter is a long, Spring answers 400 Bad Request before your method runs. Parameter names come from the compiled class (Spring Boot compiles with the -parameters flag), so @PathVariable long id needs no explicit "id". Without that flag you would write @PathVariable("id").

Views and Thymeleaf

A view resolver turns the view name into something that can render. With Spring Boot and the Thymeleaf starter, "products/detail" becomes src/main/resources/templates/products/detail.html. Thymeleaf templates are valid HTML with extra th: attributes, so designers can open them in a browser:

HTML
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="en">
<head>
  <title th:text="${product.name}">Product name</title>
</head>
<body>
  <h1 th:text="${product.name}">Placeholder name</h1>
  <p>Price: <span th:text="${#numbers.formatDecimal(product.price, 1, 2)}">0.00</span></p>

  <ul th:if="${not #lists.isEmpty(product.tags)}">
    <li th:each="tag : ${product.tags}" th:text="${tag}">tag</li>
  </ul>

  <a th:href="@{/products/search(q=${product.category})}">More in this category</a>
</body>
</html>

th:text replaces the element's content and escapes HTML special characters, which protects you from cross-site scripting (XSS) when the data came from users. th:utext would insert raw HTML; use it only for content you trust completely. @{...} builds URLs and encodes parameters. The same ideas appear in JSP with JSTL (see JSTL and Expression Language), but Thymeleaf is the common choice for new server-rendered Spring apps. Other options are FreeMarker, Mustache, and JTE.

The next program runs the same flow over real HTTP. Path variables are declared with annotations and converted to int, query parameters have defaults, a missing product becomes a 404, a non-numeric id becomes a 400, and the view escapes every model value like th:text does. Look at the last request: the <script> tag that a user typed comes back harmless.

Java Path variables, request parameters and escaped views over HTTP

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

In real Spring, the 400 and 404 come from built-in exception resolvers, and you customize them with @ExceptionHandler methods (see Validation and Error Handling). The easiest way to send a 404 from a controller is to throw new ResponseStatusException(HttpStatus.NOT_FOUND, "No product " + id).

View resolvers, Model and ModelAndView

So far a controller returned a String and Spring found the template. Three details sit behind that: how the model is passed, what a controller may return, and how the view name is turned into a view.

Model, ModelMap and ModelAndView

All three carry the data the view needs:

Type How you use it
Model An interface you declare as a method parameter: model.addAttribute("products", list). The usual choice
ModelMap or Map<String, Object> Also accepted as parameters. ModelMap is a LinkedHashMap with addAttribute helpers
ModelAndView A return value that bundles a view name and a model: new ModelAndView("invoice", "total", 42)

addAttribute(value) without a name derives one from the type: a Product becomes product, a List<Product> becomes productList. That is handy and a little magic, so give names explicitly when it matters. A handler method may return a String (view name), a ModelAndView, an @ResponseBody object, or void. For a void method that did not write the response itself, Spring derives the view name from the request URL (/pages/about becomes pages/about). ModelAndView is the older style, and you will see it in older code, in tests (MockMvc exposes it through andReturn().getModelAndView()), and in methods that must decide the status or add attributes late:

Java
@GetMapping("/legacy/invoice")
public ModelAndView invoice() {
    var mav = new ModelAndView("invoice");
    mav.addObject("total", 42);
    mav.setStatus(HttpStatus.OK);
    return mav;
}

Controllers can also contribute attributes to every request in the class. A method annotated with @ModelAttribute runs before each handler method of that controller (or of every controller, if it lives in a @ControllerAdvice class):

Java
@ModelAttribute("categories")
public List<String> categories() {
    return categoryService.names();      // available in every template this controller renders
}

Remember that it runs on every request to that controller, including those whose view never uses the attribute, so keep it cheap.

Request parameters and path variables in more detail

Java
@GetMapping("/search")
public String search(@RequestParam(defaultValue = "everything") String q,   // missing -> default
                     @RequestParam(defaultValue = "1") int page,             // converted to int
                     @RequestParam List<String> tag,                          // ?tag=java&tag=spring
                     @RequestParam Optional<String> sort,                     // optional without a default
                     @RequestParam Map<String, String> all,                   // every parameter
                     Model model) { /* ... */ return "pages/results"; }

@GetMapping({"/blog", "/blog/{year}"})                                        // one method, two URLs
public String blog(@PathVariable(required = false) Integer year, Model model) {
    model.addAttribute("year", year != null ? year : Year.now().getValue());
    return "pages/blog";
}

A @RequestParam is required by default, so a missing one gives 400. Giving it a defaultValue or Optional makes it optional. A path variable can only be optional when the same method is mapped to more than one URL pattern, as above.

View resolvers

The DispatcherServlet asks each configured ViewResolver to turn the view name into a View, in order of their order value. The first one that returns a view wins. Some resolvers return null when the name isn't theirs, so the next can try. Others accept every name. The common ones are:

  • Thymeleaf (ThymeleafViewResolver, from the starter): templates such as templates/products/list.html. It can be limited to certain names with setViewNames("pages/*").
  • InternalResourceViewResolver: forwards to a JSP: prefix /WEB-INF/views/, suffix .jsp. It always produces a view, even for names that don't exist, so it must be the last resolver.
  • BeanNameViewResolver: the name is the bean name of a View bean you defined (for a CSV download, say).
  • ContentNegotiatingViewResolver: picks among other resolvers by the Accept header or a file extension.

Without Boot, you configure them in the WebMvcConfigurer:

Java
@Configuration
@EnableWebMvc
@ComponentScan("com.example.shop.web")
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        registry.jsp("/WEB-INF/views/", ".jsp");          // InternalResourceViewResolver
    }

    @Bean
    public ViewResolver beanNameViewResolver() {
        var resolver = new BeanNameViewResolver();
        resolver.setOrder(0);                              // asked first
        return resolver;
    }
}

The program below models the chain: a bean-name resolver (order 0), a template resolver for pages/* (order 1), and a catch-all JSP resolver (Integer.MAX_VALUE). It also shows the four ways a handler can return, and what happens when the catch-all resolver is put first. It is plain Java, not Spring.

Java Chained view resolvers, ModelAndView and @ModelAttribute

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

With the right order, /report found its view bean and the templates kept their .html files. With the JSP resolver first, every name was swallowed by it, and csvReport became a missing JSP. With only the template resolver, an unknown name ends with "Could not resolve view" (the real message continues with in servlet with name 'dispatcher'). The appName attribute in every model came from the @ModelAttribute stand-in.

Forms, binding and Post/Redirect/Get

HTML forms post application/x-www-form-urlencoded data. Spring binds the fields to an object annotated with @ModelAttribute (the annotation is optional for non-simple types), and validation errors land in a BindingResult that must come right after it:

Java
@Controller
@RequestMapping("/todos")
public class TodoController {

    public record TodoForm(@NotBlank @Size(max = 100) String title) {}

    @GetMapping
    public String list(Model model) {
        model.addAttribute("todos", todoService.findAll());
        model.addAttribute("form", new TodoForm(""));
        return "todos/list";
    }

    @PostMapping
    public String add(@Valid @ModelAttribute("form") TodoForm form, BindingResult errors,
                      Model model, RedirectAttributes redirect) {
        if (errors.hasErrors()) {
            model.addAttribute("todos", todoService.findAll());
            return "todos/list";                      // show the form again with messages
        }
        todoService.add(form.title());
        redirect.addFlashAttribute("message", "Added โ€œ" + form.title() + "โ€");
        return "redirect:/todos";                     // Post/Redirect/Get
    }
}

The redirect: prefix is special: instead of rendering a template, Spring sends a redirect response with a Location header (302 Found by default), and the browser follows it with a GET. This Post/Redirect/Get (PRG) pattern matters because browsers repeat the last request on refresh. If a POST rendered the page directly, pressing F5 would submit the form again and create a duplicate. After a redirect, the last request is a harmless GET. A flash attribute survives exactly one redirect (Spring keeps it in the session briefly), which is how the "Added" message reaches the next page. The prefix forward: also exists: it hands the request to another handler on the server, without the browser knowing.

On a validation error the method returns the view name, not a redirect, so the user sees the form again with their input and the error messages. Here is that flow, plus the duplicate-submit problem it avoids:

Java Post/Redirect/Get versus rendering after POST

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

With PRG, refreshing repeats the GET and nothing changes. Without it, refreshing repeats the POST and "Pay rent" appears twice. Real browsers at least show a "Confirm form resubmission" dialog, but users click through it all the time.

Data binding, DTOs and custom validators

The @ModelAttribute parameter in the previous section hides a lot. Before your method runs, a WebDataBinder copies request parameters into your object, converting each string to the field type (int, LocalDate, enums, your own types), and collects problems in a BindingResult. You can configure that binder per controller with an @InitBinder method, and what you configure is also your first line of defense.

Bind to a DTO, never to an entity

Binding copies every request parameter that matches a property. If the target is a JPA entity with an admin flag, isActive, or price, then anyone who adds &admin=true to the form post can set it. This attack is called mass assignment. The cure is a DTO (data transfer object, here also called a form object): a small class with exactly the fields the form offers. The controller validates the DTO, then copies the allowed values into the entity by hand or in a service. As a second layer, the binder can state an allow-list:

Java
@Controller
public class SignupController {

    public static class SignupForm {
        @NotBlank @Email private String email;
        @DateTimeFormat(pattern = "dd/MM/yyyy") private LocalDate birthDate;   // a format for this field
        @Min(18) private int age;
        private String password, confirm;
        // getters and setters
    }

    @InitBinder("signupForm")                       // only for the model attribute named signupForm
    public void initBinder(WebDataBinder binder) {
        binder.setAllowedFields("email", "birthDate", "age", "password", "confirm");   // everything else is ignored
        binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));       // trim; "" becomes null
        binder.addValidators(new SignupValidator());                                    // runs besides @Valid
    }

    @PostMapping("/signup")
    public String signup(@Valid @ModelAttribute SignupForm signupForm, BindingResult errors) {
        if (errors.hasErrors()) return "signup";     // redisplay with the user's input and messages
        accounts.register(signupForm);
        return "redirect:/welcome";
    }
}

@InitBinder methods run before binding for each request. Java records and other classes with a constructor can also be bound through the constructor, which lets a DTO be immutable. Spring ignores unknown parameter names by default (so role below is silently dropped) and reports type mismatches (a text where a number belongs) as binding errors instead of throwing.

Writing a validator

Bean Validation annotations (@NotBlank, @Min) are right for single-field rules. A rule that compares fields, or needs a database lookup, can use the Spring Validator interface:

Java
@Component
public class SignupValidator implements Validator {

    @Override
    public boolean supports(Class<?> type) {
        return SignupForm.class.isAssignableFrom(type);
    }

    @Override
    public void validate(Object target, Errors errors) {
        var form = (SignupForm) target;
        if (!Objects.equals(form.getPassword(), form.getConfirm())) {
            errors.rejectValue("confirm", "password.mismatch", "The passwords do not match");
        }
    }
}

rejectValue(field, code, defaultMessage) attaches the error to a field, where the form shows it next to the input; reject(code, message) attaches a global error to the whole object. The code is looked up in messages.properties, so messages can be translated. The alternative that stays inside Bean Validation is a custom constraint annotation with a ConstraintValidator, including class-level annotations like @PasswordsMatch. Validation and Error Handling builds one step by step. Use @InitBinder plus Validator for rules that depend on the web layer, and a constraint annotation for rules that should also apply outside it.

The program below models the binder: it copies parameters through setters, converts types with registered "editors", applies an allow-list, and runs a validator afterwards. It is plain Java, not Spring, but it shows the same behavior, including the mass-assignment problem in the first case.

Java Mass assignment, a binder with an allow-list, and a custom validator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Case 1 shows the danger: with no filter, admin=true went straight into the entity. In case 2 the DTO simply has no admin property, so the parameter was ignored. Cases 3 and 4 use one binder configuration: the padded e-mail was trimmed, the date was parsed using the dd/MM/yyyy format, and role was dropped by the allow-list. In case 4 the ISO date and the word seventeen became type-mismatch errors (the real framework would also keep the rejected text so that the form can show it again), and the validator reported the unequal passwords. Notice that age still shows must be at least 18, because the failed conversion left the default 0. Real forms usually hide such a follow-up message when a field already has a conversion error.

Two-way binding and the form tags

"Two-way" means the same object is used in both directions. On GET, the controller puts a SignupForm into the model and the template shows its values in the inputs. On POST, the binder fills a new object from the inputs, and if validation fails the template renders again with what the user typed. Tag libraries make that wiring short. This is the older JSP form tag library next to its Thymeleaf equivalent:

Input JSP (spring-form tags) Thymeleaf
Form <form:form modelAttribute="signupForm" method="post"> <form th:object="${signupForm}" method="post">
Text <form:input path="email"/> <input th:field="*{email}">
Password <form:password path="password"/> <input type="password" th:field="*{password}">
Checkbox <form:checkbox path="newsletter"/> <input type="checkbox" th:field="*{newsletter}">
Radio buttons <form:radiobuttons path="plan" items="${plans}"/> <input type="radio" th:field="*{plan}" value="free">
Drop-down <form:select path="country" items="${countries}"/> <select th:field="*{country}"><option th:each="c : ${countries}" th:value="${c}" th:text="${c}"></option></select>
Hidden <form:hidden path="id"/> <input type="hidden" th:field="*{id}">
Error <form:errors path="email" cssClass="error"/> <span th:errors="*{email}">error</span>

Two details matter. A browser sends nothing for an unchecked checkbox, so both libraries add a hidden marker field (named like _newsletter) that lets Spring tell "unchecked" from "not on this form". And for the JSP tags, the form must be rendered with a model attribute named like modelAttribute, otherwise the page fails with "Neither BindingResult nor plain target object for bean name" - a very common first error. Thymeleaf covers th:field and th:errors further.

Interceptors

A HandlerInterceptor runs around handler methods, inside the DispatcherServlet. It is like a servlet filter (see Filters and Listeners), but it knows which handler was chosen and can see the model before rendering:

Java
public class TimingInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        request.setAttribute("startNanos", System.nanoTime());
        return true;                               // false stops the request here
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, Exception ex) {
        long ms = (System.nanoTime() - (long) request.getAttribute("startNanos")) / 1_000_000;
        log.info("{} {} took {} ms", request.getMethod(), request.getRequestURI(), ms);
    }
}

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

WebMvcConfigurer is the general customization hook for Spring MVC: interceptors, CORS mappings, static resources, formatters and message converters all go there. Use filters for concerns that apply to every request before Spring sees it (security, compression), and interceptors for concerns tied to controllers.

Setting it up, with and without Boot

With Spring Boot, adding spring-boot-starter-webmvc (called spring-boot-starter-web before Boot 4) registers the DispatcherServlet, starts an embedded Tomcat, and configures Jackson, static resources from src/main/resources/static, and the Thymeleaf view resolver if its starter is present. You write only controllers and templates. Spring Boot Introduction explains how.

Without Boot, you register the DispatcherServlet yourself and deploy a WAR to a servlet container:

Java
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
    @Override protected Class<?>[] getRootConfigClasses()    { return new Class<?>[] {AppConfig.class}; }
    @Override protected Class<?>[] getServletConfigClasses() { return new Class<?>[] {WebConfig.class}; }
    @Override protected String[] getServletMappings()        { return new String[] {"/"}; }
}

@Configuration
@EnableWebMvc                                 // registers the MVC infrastructure beans
@ComponentScan("com.example.shop.web")
public class WebConfig implements WebMvcConfigurer { /* view resolvers, interceptors, ... */ }

The servlet container finds this initializer automatically (through ServletContainerInitializer, no web.xml needed). This is how Spring web apps were built for years, and you will still meet it in older projects. Don't add @EnableWebMvc to a Spring Boot app: it switches off Boot's MVC auto-configuration.

Server-rendered pages or a JSON API?

Spring MVC serves both. A @Controller method that returns a String names a view. Add @ResponseBody to the method (or use @RestController on the class, which adds it to every method), and the return value is written to the response body instead, usually as JSON via Jackson. Many applications mix both: Thymeleaf pages for an admin area, JSON endpoints for a JavaScript or mobile front end. The JSON style is the subject of Building REST APIs with Spring Boot.

Spring also has a second web stack, Spring WebFlux, built on non-blocking I/O with Reactor. Its annotations look the same, but the runtime is different. For most applications Spring MVC with virtual threads (spring.threads.virtual.enabled=true in Boot) is simpler and scales well. See Reactive Programming.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A request arrives for a URL that no controller method maps. Which component decides that, and what does the client get?

    The DispatcherServlet asks its HandlerMappings for a handler. If none matches, the result is a 404.
  2. 2. A controller method returns the string "redirect:/orders". What happens?

    The redirect prefix creates a RedirectView. The browser follows it with a GET, which is the basis of Post/Redirect/Get.
  3. 3. Why should a successful form POST end with a redirect instead of rendering a page directly?

    Browsers repeat the last request on refresh. After a redirect, that request is a GET, so no duplicate is created.
  4. 4. A user searches for <b>hi</b> and the template shows it with th:text. What appears on the page?

    th:text escapes the value, so user input cannot inject markup or scripts. th:utext would insert it unescaped.
  5. 5. A method is declared as show(@PathVariable long id) and the request is GET /products/abc. What happens?

    The handler adapter converts arguments before calling the method. A conversion failure is a client error, 400.

Summary

  • Spring MVC uses one front controller, the DispatcherServlet, which delegates to HandlerMapping, HandlerAdapter, interceptors, ViewResolver and exception resolvers.
  • @Controller classes map URLs with @GetMapping/@PostMapping; the most specific mapping wins.
  • Method parameters are filled from the request: @PathVariable, @RequestParam, @RequestHeader, @ModelAttribute, @RequestBody, plus framework objects like Model. Failed conversions give 400.
  • Page-rendering methods fill a Model and return a view name; the view resolver maps it to a template, such as a Thymeleaf file under templates/.
  • th:text escapes output; avoid th:utext for user data.
  • Use Post/Redirect/Get with redirect: and flash attributes after successful form submissions; re-render the form on validation errors.
  • View resolvers are tried in order; the catch-all JSP resolver goes last. Model, ModelMap and ModelAndView all carry view data, and @ModelAttribute methods add attributes before every handler.
  • Bind forms to DTOs, not entities, and use @InitBinder (allowed fields, converters, extra validators) to limit what the binder may set.
  • HandlerInterceptor and WebMvcConfigurer customize the MVC pipeline; @RestController turns the same machinery into a JSON API.

Next: Spring Boot Introduction shows how Boot sets up all of this, plus an embedded server, with almost no configuration.