Skip to content
notes.vinhnq.com

Search

SpringMid20 min read

Spring MVC: DispatcherServlet, controllers and views

Review 15 cards
On this page

Spring MVC end to end series: 1. Maven and project layout · 2. DispatcherServlet and views · 3. Forms and validation · 4. Form login with Spring Security · 5. Sessions and remember-me · 6. File upload · 7. Cart and checkout · 8. Pagination and dynamic filters

Which parts of Spring does a request to /products pass through before it becomes an HTML page? This post follows that path, then walks through the everyday decisions: return a view or JSON, redirect or forward, Thymeleaf or JSP. The last part explains two real mistakes in the course material, with experiments run on Spring Boot 3.5.

1. MVC in Spring: who does what

Key idea: the controller receives the request and picks a view, the service holds business logic, the repository talks to the database. The “Model” in Spring MVC is the bundle of data the controller hands to the view, not the database tables.

MVC (Model, View, Controller) separates three jobs so each can change without dragging the others:

Part In the lab project Job
Controller ProductController, AdminUserController read parameters, call services, pick a view
Model Model (a name → value map) data for the view: page, form, message
View templates/products/list.html produce HTML from the model
Service, repository ProductService, ProductRepository business logic, queries (not part of MVC)

The course material says “the Model is the tables in the database”. That mixes two ideas: entities are the domain model, while MVC’s Model is data for the view. Keeping them apart matters, because rendering entities directly or binding forms straight onto entities is where lazy-loading errors and mass assignment come from (part 3).

Controllers are created and injected like any other bean; that mechanism is in IoC and DI.

2. The path of a request

Key idea: Tomcat runs the filter chain (Spring Security included), then hands the request to DispatcherServlet. DispatcherServlet doesn’t handle anything itself; it coordinates a chain of “strategies”, each one a replaceable interface.

flowchart TD
  A[Browser: GET /products?page=2] --> B[Tomcat: filter chain, incl. Spring Security]
  B --> C[DispatcherServlet]
  C --> D[HandlerMapping: URL + HTTP method to handler]
  D --> E[HandlerAdapter: invoke controller method]
  E --> F[Argument resolvers: build Pageable, Model, @PathVariable]
  F --> G[Controller calls service, returns view name products/list]
  G --> H[Return value handler]
  H -->|@Controller returns String| I[ViewResolver: view name to View]
  I --> J[View renders HTML into the response]
  H -->|@ResponseBody| K[HttpMessageConverter: object to JSON]

Step by step, with the lab’s code:

  1. Filters: run before DispatcherServlet. Spring Security lives here, so a blocked request (not logged in, missing CSRF token) never reaches a controller (part 4).
  2. HandlerMapping: RequestMappingHandlerMapping holds the table of @GetMapping/@PostMapping. No matching row: 404; matching URL but wrong method (GET on a @PostMapping): 405.
  3. HandlerAdapter: knows how to call that kind of handler. For annotated methods it’s RequestMappingHandlerAdapter.
  4. Argument resolvers: build each parameter. @PageableDefault Pageable reads page, size, sort; @AuthenticationPrincipal gives the logged-in user; Model is an empty map for the controller to fill.
  5. Return value handlers: a String is a view name; with @ResponseBody the object goes through an HttpMessageConverter (Jackson) into JSON.
  6. ViewResolver and View: turn "products/list" into the template classpath:/templates/products/list.html and render it.

Exceptions thrown in steps 3–5 go through HandlerExceptionResolver, where your @ControllerAdvice catches them; see error handling in Spring Boot. The lab’s GlobalErrors renders error/page with status 404, 400 or 409.

DispatcherServlet’s strategies in the lab, printed for real

A small test printed the HandlerMapping and ViewResolver beans in the lab’s context (Spring Boot 3.5.9 with Thymeleaf):

HandlerMapping:
  requestMappingHandlerMapping        RequestMappingHandlerMapping   # @GetMapping, @PostMapping...
  welcomePageHandlerMapping           WelcomePageHandlerMapping      # index.html for "/"
  beanNameHandlerMapping              BeanNameUrlHandlerMapping
  routerFunctionMapping               RouterFunctionMapping          # functional style
  resourceHandlerMapping              SimpleUrlHandlerMapping        # /css/**, /files/**
ViewResolver:
  viewResolver                        ContentNegotiatingViewResolver # picks among the ones below
  thymeleafViewResolver               ThymeleafViewResolver
  beanNameViewResolver                BeanNameViewResolver
  defaultViewResolver                 InternalResourceViewResolver   # JSP, prefix/suffix from spring.mvc.view.*

DispatcherServlet tries each HandlerMapping in order and the first one returning a handler wins. So a @GetMapping("/css/app.css") in a controller hides the static file at the same path.

ContentNegotiatingViewResolver asks the other resolvers and picks the view matching the Accept header. Thymeleaf comes before InternalResourceViewResolver, so mixing Thymeleaf and JSP in one app makes it hard to predict which view wins: pick one.

3. @Controller or @RestController

Key idea: same DispatcherServlet, different last step. @Controller returns a view name and the HTML is rendered on the server (server-side rendering, SSR); @RestController = @Controller + @ResponseBody and writes data (usually JSON) for the client to display.

@Controller
class ProductController {
    @GetMapping({"/", "/products"})
    String list(@ModelAttribute("filter") ProductFilter filter,
                @PageableDefault(size = 12, sort = "id") Pageable pageable, Model model) {
        model.addAttribute("page", service.search(filter, safeSort(pageable)));
        return "products/list";                   // a view name, not content
    }
}

@RestController
@RequestMapping("/api/products")
class ProductApi {
    @GetMapping
    Page<ProductDto> list(Pageable pageable) { ... }   // object becomes JSON
}

Both styles can live in one application, usually split by an /api/** prefix and two SecurityFilterChains (form login for pages, tokens for the API). The traditional web model versus Web APIs is covered in web and REST APIs; REST design with Spring in REST API design with Spring Boot.

4. Model, view names and ViewResolver

Key idea: the controller puts data into the Model and returns a logical name such as "admin/users/list". The ViewResolver adds a prefix and suffix to find the file; the controller doesn’t know whether the view is Thymeleaf or JSP.

Return type Meaning
String a view name (or redirect:, forward:)
ModelAndView view name and model in one object (older style, still fine)
void view name derived from the URL; hard to read, avoid
object + @ResponseBody written straight into the body, no view

Model, ModelMap and ModelAndView differ only in how you write them; they all end up in one map. A Model parameter is the tidiest.

For Thymeleaf, Boot presets the prefix classpath:/templates/ and the suffix .html. For JSP you declare them yourself:

spring.mvc.view.prefix=/WEB-INF/view/
spring.mvc.view.suffix=.jsp

These two lines are enough: Boot creates an InternalResourceViewResolver that reads them. No hand-written ViewResolver bean as in the material (section 6).

A convention worth keeping: view names don’t start with / and mirror the folder tree (admin/users/edit → templates/admin/users/edit.html). Section 8 shows how an extra / breaks things, with JSP and with Thymeleaf.

5. redirect:, forward: and PRG

Key idea: forward: hands the request to another URL inside the server; the browser never knows. redirect: returns 302 so the browser sends a new GET. After a POST that changes data, always redirect: that’s the Post/Redirect/Get (PRG) pattern.

sequenceDiagram
    participant B as Browser
    participant S as Server
    B->>S: POST /admin/users/7 (edit user form)
    S->>S: save, add flash "Saved"
    S-->>B: 302 Location /admin/users
    B->>S: GET /admin/users
    S-->>B: 200 list page + "Saved"
    Note over B: F5 only repeats the GET, not the form

Without PRG, pressing F5 after placing an order resubmits the form and may create a second order. The server still has to reject duplicates (part 7); PRG only removes the browser-side accident.

The lab follows this pattern. When the form has errors it does not redirect but renders the view again, keeping the input and the errors:

@PostMapping("/{id}")
String update(@PathVariable Long id, @Valid @ModelAttribute("form") UserForm form, BindingResult result,
              Model model, RedirectAttributes ra) {
    if (result.hasErrors()) { model.addAttribute("user", find(id)); return "admin/users/edit"; }
    // ... save
    ra.addFlashAttribute("message", "Saved");
    return "redirect:/admin/users";
}

6. Thymeleaf or JSP

Key idea: there are many view engines (tools that produce HTML from a template plus data). With Spring Boot, choose Thymeleaf: it runs inside a jar and is preconfigured. JSP only works with war packaging and needs extra libraries and a webapp folder.

Thymeleaf JSP + JSTL
Location src/main/resources/templates/ src/main/webapp/WEB-INF/view/
Packaging jar or war war only (or running from the IDE)
Libraries spring-boot-starter-thymeleaf tomcat-embed-jasper, JSTL API + implementation
Open the file in a browser valid HTML (natural templates) no, full of <c:...> tags
Rendering straight into the response a forward to the JSP servlet

The last row is the root of the trap in section 8: a JSP is rendered through an internal forward, which passes through the filter chain again.

Setting up JSP properly on Spring Boot 3, and JSTL with the Jakarta namespace

Dependencies (no versions, Boot manages all three):

<packaging>war</packaging>
...
<dependency>
  <groupId>org.apache.tomcat.embed</groupId>
  <artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<dependency>
  <groupId>jakarta.servlet.jsp.jstl</groupId>
  <artifactId>jakarta.servlet.jsp.jstl-api</artifactId>
</dependency>
<dependency>
  <groupId>org.glassfish.web</groupId>
  <artifactId>jakarta.servlet.jsp.jstl</artifactId>
</dependency>

At the top of a JSP, use the new JSTL 3 URIs (the jakarta.tags.* namespace). The old URI http://java.sun.com/jsp/jstl/core in the material is still accepted for compatibility, but new code should use the new names:

<%@ page contentType="text/html" pageEncoding="UTF-8" %>
<%@ taglib prefix="c"    uri="jakarta.tags.core" %>
<%@ taglib prefix="fmt"  uri="jakarta.tags.fmt" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

<c:forEach var="p" items="${page.content}">
  <p>${p.name}: <fmt:formatNumber value="${p.price}" type="number" maxFractionDigits="0"/> đ</p>
</c:forEach>

${p.name} in a JSP does not escape HTML: a product name containing <script> will run (XSS). Use <c:out value="${p.name}"/>. Thymeleaf’s th:text escapes by default. XSS is covered in web attacks.

Currency formatting: type="currency" depends on the locale and the JDK. In the experiment with <fmt:setLocale value="vi_VN"/> the output was ₫25,000,000, not the expected 25.000.000 ₫. Formatting the number explicitly as above and appending “đ” yourself is more predictable; Thymeleaf has #numbers.formatDecimal(p.price, 0, 'POINT', 0, 'COMMA').

7. Static files and WebMvcConfigurer

Key idea: Boot already serves every file in classpath:/static/ (and public/, resources/, META-INF/resources/) at the URL root. For an extra location, such as user uploads stored outside the jar, add a resource handler in a WebMvcConfigurer.

  • src/main/resources/static/css/app.css → GET /css/app.css. No controller, no configuration.
  • The course material keeps CSS in src/main/webapp/resources/, so it has to declare a /css/** handler; put the files in static/ and you don’t.
  • Bootstrap, jQuery: a CDN with integrity, or WebJars so Maven manages the version.

The lab adds exactly one handler for uploaded files and keeps the auto-configuration:

@Configuration
@EnableConfigurationProperties(StorageProperties.class)
public class WebConfig implements WebMvcConfigurer {       // no @EnableWebMvc
    private final StorageProperties props;
    public WebConfig(StorageProperties props) { this.props = props; }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/files/**")
                .addResourceLocations(props.dir().toAbsolutePath().toUri().toString());
    }
}

Long caching for static files: spring.web.resources.cache.cachecontrol.max-age=365d with spring.web.resources.chain.strategy.content.enabled=true (URLs carry a content hash). Storing uploads safely is in part 6.

8. The “//” trap with Spring Security 6

Key idea: with JSP, the view name "/auth/login" plus the prefix /WEB-INF/view/ becomes /WEB-INF/view//auth/login.jsp. The forward to the JSP passes through Spring Security, StrictHttpFirewall sees // and rejects it. Fix: drop the leading / from view names, and permit the FORWARD and ERROR dispatcher types.

The course material says the error comes from “an extra slash” and didn’t happen before Security was added. Right symptom, but two halves of the mechanism are missing:

  1. The firewall: Spring Security’s StrictHttpFirewall blocks URLs containing suspicious sequences such as //, .., ;, because they are used to sneak past authorization rules.
  2. Spring Security 6 also checks forwards: since version 6, authorizeHttpRequests applies to every dispatcher type, FORWARD and ERROR included. Version 5 only checked the original request.

Experiment: a small JSP application (Spring Boot 3.5.9, Security 6.5.7, war packaging, started with java -jar). /a returns "/auth/login", /b returns "auth/login", both are permitAll():

Configuration /a (leading /) /b (no leading /)
FORWARD not permitted 302 to /login 302 to /login
dispatcherTypeMatchers(FORWARD, ERROR).permitAll() 400, log: RequestRejectedException: ... potentially malicious String "//" 200, page renders

The first row shows that dropping the / alone is not enough: the forward to /WEB-INF/view/auth/login.jsp matches no permitAll rule and falls into anyRequest().authenticated(). The correct configuration needs both:

http.authorizeHttpRequests(a -> a
    .dispatcherTypeMatchers(DispatcherType.FORWARD, DispatcherType.ERROR).permitAll()
    .requestMatchers("/", "/login", "/register", "/css/**").permitAll()
    .anyRequest().authenticated());

Permitting FORWARD is safe because only server code can create a forward; the original request was already checked on the first pass.

Exercises

Exercise 1: A user admin area that follows the MVC path

Task (paraphrased from the course lab): build /admin/users with a paginated list, an edit page (full name, phone, role, avatar) and a delete button. Requirements: resource-style URLs, redirect with a message after a successful POST, show the form again on errors, no deletion via GET, regular users are blocked. Write tests that prove it.

Solution to exercise 1: controller, view and tests

The controller (from the lab, trimmed; binding and validation are explained in part 3):

@Controller
@RequestMapping("/admin/users")
public class AdminUserController {
    private final UserRepository users; private final FileStorageService storage;
    public AdminUserController(UserRepository users, FileStorageService storage) { this.users = users; this.storage = storage; }

    @GetMapping
    String list(@PageableDefault(size = 10, sort = "id") Pageable pageable, Model model) {
        model.addAttribute("page", users.findAll(pageable));
        return "admin/users/list";
    }

    @GetMapping("/{id}/edit")
    String edit(@PathVariable Long id, Model model) {
        AppUser u = find(id);
        UserForm f = new UserForm();
        f.setFullName(u.getFullName()); f.setPhone(u.getPhone()); f.setRole(u.getRole());
        model.addAttribute("form", f); model.addAttribute("user", u);
        return "admin/users/edit";
    }

    @PostMapping("/{id}")
    String update(@PathVariable Long id, @Valid @ModelAttribute("form") UserForm form, BindingResult result,
                  @RequestParam(name = "avatar", required = false) MultipartFile avatar,
                  Model model, RedirectAttributes ra) {
        AppUser u = find(id);
        if (result.hasErrors()) { model.addAttribute("user", u); return "admin/users/edit"; }
        u.setFullName(form.getFullName()); u.setPhone(form.getPhone()); u.setRole(form.getRole());
        if (avatar != null && !avatar.isEmpty()) u.setAvatar(storage.store(avatar, "avatar"));
        users.save(u);
        ra.addFlashAttribute("message", "Saved");
        return "redirect:/admin/users";
    }

    @PostMapping("/{id}/delete")
    String delete(@PathVariable Long id, RedirectAttributes ra) {
        users.deleteById(id);
        ra.addFlashAttribute("message", "Deleted");
        return "redirect:/admin/users";
    }

    private AppUser find(Long id) { return users.findById(id).orElseThrow(() -> new NotFoundException("user " + id)); }
}

The list view: the delete button is a POST form, Thymeleaf adds the _csrf input itself:

<p th:text="${message}"></p>
<tr th:each="u : ${page.content}">
  <td th:text="${u.email}"></td>
  <td><form th:action="@{/admin/users/{id}/delete(id=${u.id})}" method="post"><button>Delete</button></form></td>
</tr>

Authorization for /admin/** lives in the SecurityFilterChain (part 4). NotFoundException is turned into a 404 page by the @ControllerAdvice.

MockMvc tests (run, part of the lab’s 23 tests, all passing):

@Test void deleteUserNeedsPostAndAdmin() throws Exception {
    mvc.perform(get("/admin/users/" + alice.getId() + "/delete").with(user(me(admin))))
       .andExpect(status().isMethodNotAllowed());                         // 405
    mvc.perform(post("/admin/users/" + alice.getId() + "/delete").with(user(me(admin))))
       .andExpect(status().isForbidden());                                // no CSRF token
    mvc.perform(post("/admin/users/" + alice.getId() + "/delete").with(user(me(admin))).with(csrf()))
       .andExpect(redirectedUrl("/admin/users"));
}

@Test void userCannotOpenAdmin() throws Exception {
    mvc.perform(get("/admin").with(user(me(alice)))).andExpect(status().isForbidden())
       .andExpect(forwardedUrl("/access-denied"));
}

What a senior would improve:

  • Soft delete (a deleted_at column) or refuse to delete users with orders, instead of a deleteById that hits a foreign-key error.
  • An admin can’t demote or delete themselves; keep an audit log of who changed whose role.
  • Call a @Transactional UserAdminService instead of the repository directly once the logic grows.
  • Assert view().name(...) for every GET to catch wrong view names early.

Exercise 2: Diagnose

A Boot + JSP application works in the IDE. After (a) adding @EnableWebMvc the CSS disappears; (b) packaging a jar and deploying, every page returns 404; (c) enabling Spring Security, the login page redirects in a loop. Explain each failure and the fix.

Solution to exercise 2

(a) @EnableWebMvc disables WebMvcAutoConfiguration, losing the default resource handler for static/. Remove the annotation, keep implements WebMvcConfigurer.

(b) JSPs don’t work in an executable jar: switch to <packaging>war</packaging>, or move to Thymeleaf.

(c) Security 6 also checks the forward to the JSP. The forward to /WEB-INF/view/... isn’t permitAll, so it demands a login, and the login page itself needs a forward: a redirect loop. Add dispatcherTypeMatchers(FORWARD, ERROR).permitAll(), and drop the leading / from view names to avoid the // the firewall rejects.

Remember

  • Can you redraw the path filter → DispatcherServlet → HandlerMapping → HandlerAdapter → controller → ViewResolver → View?
  • Can you explain when to return a view name versus JSON, and how redirect: differs from forward:?
  • Do you know why a POST must end in a redirect, and how long a flash attribute lives?
  • Do you know why a Boot app shouldn’t carry @EnableWebMvc, and why JSP needs a war?
  • Can you explain the // error with Spring Security 6 through the firewall and FORWARD checks?

Interview questions

Junior

How do @Controller and @RestController differ?

@RestController is @Controller plus @ResponseBody: the return value is written straight into the body (usually JSON) instead of being treated as a view name.

@Controller is for server-rendered pages: the method returns "products/list" and a ViewResolver finds the template. The same DispatcherServlet handles both; they differ in the return value handler.

How do redirect: and forward: differ?

forward: moves the request inside the server, the browser doesn’t know and the URL stays; redirect: returns 302 and the browser sends a new GET to another URL.

A forward keeps the same request (attributes included); a redirect loses the model, so you use flash attributes. After a POST that changes data, redirect so F5 doesn’t resubmit the form.

What is Post/Redirect/Get and what problem does it solve?

After a successful POST the server redirects to a GET page instead of rendering directly, so reloading the page doesn’t resubmit the form.

If validation fails, don’t redirect: render the form again with the errors. A “saved” message crosses the redirect as a flash attribute. PRG doesn’t replace server-side duplicate protection.

Mid

Describe the path of a request in Spring MVC.

Filters (Spring Security included) → DispatcherServlet → HandlerMapping finds the handler → HandlerAdapter invokes the method, argument resolvers build its parameters → return value handler → ViewResolver and View render, or an HttpMessageConverter writes JSON.

Exceptions along the way go through HandlerExceptionResolver, where @ControllerAdvice catches them. The mapping table is built at startup, so duplicate mappings stop the app from starting.

Why shouldn’t you add @EnableWebMvc to a Spring Boot application?

It tells Boot you’re configuring MVC yourself, so WebMvcAutoConfiguration backs off: you lose static file serving, the spring.mvc.* properties and the default converters.

To add interceptors, resource handlers or formatters, implement WebMvcConfigurer in a plain @Configuration. In the experiment, the annotation turned /css/app.css into a 404 while pages kept working.

What are the limitations of JSP with Spring Boot?

JSPs don’t work in an executable jar, so you need war packaging; you need Jasper and JSTL; rendering is a forward, so it passes through the filters again; ${} expressions don’t escape HTML.

Thymeleaf is supported out of the box, runs from a jar, escapes by default, and its templates open in a browser. New projects should pick Thymeleaf or a separate frontend.

Senior

After upgrading to Spring Boot 3, the JSP login page fails with “malicious String //” or loops on redirects. How do you explain and fix it?

Spring Security 6 also authorizes FORWARD dispatches; JSPs render through a forward, and a view name with a leading / produces a // path that StrictHttpFirewall rejects.

Fix both: permit dispatcherTypeMatchers(FORWARD, ERROR) and drop the leading / from view names. Don’t loosen the firewall (setAllowUrlEncodedDoubleSlash or a custom firewall), because // is a known trick for bypassing authorization rules. Add tests on view names to catch it before it reaches a real environment.

One application has SSR pages and a REST API for mobile. How do you organise it?

Split by path (/api/**) with two SecurityFilterChains: form login + session + CSRF for pages, stateless bearer tokens for the API; page controllers and API controllers are separate classes sharing the same services.

Split error handling too: a @ControllerAdvice for pages that renders error views, another for /api that returns ProblemDetail. Give the API filter chain a higher @Order. Never return entities as JSON or to views; use DTOs on each side.

Useful phrases for interviews

  • “DispatcherServlet is a front controller: it delegates to a handler mapping, a handler adapter and a view resolver.”
  • “The handler mapping table is built once at startup, so an ambiguous mapping fails fast.”
  • “A controller returns a logical view name; the view resolver adds the prefix and suffix.”
  • “After a successful POST I redirect and pass the message as a flash attribute.”
  • “Deleting through a GET link is unsafe; I use a POST form with the CSRF token.”
  • “In a Boot app I implement WebMvcConfigurer but never add @EnableWebMvc.”
  • “JSPs need war packaging, so for new projects I go with Thymeleaf.”
  • “Spring Security 6 authorizes forward dispatches, so I permit FORWARD and ERROR explicitly.”
  • “A leading slash in a view name can work in the IDE and break inside the fat jar.”

Notes based on Hỏi Dân IT course material, rewritten and extended in my own words.