Home

SpringMVC

Li

Li Wei

April 26, 202610 min read

Title: SpringMVC

Overview

SpringMVC is a lightweight web framework that implements the MVC model in Java.

Advantages of SpringMVC:

  • Easy to use
  • Outstanding performance (compared with existing framework technologies)
  • Highly flexible

Three‑Tier Architecture in Software Development

  • Presentation layer: responsible for displaying data
  • Business layer: responsible for business logic
  • Data layer: responsible for data access

MVC (Model‑View‑Controller)

A design pattern for creating the presentation layer of web applications.

  • Model: data model that encapsulates data
  • View: page view that presents data (e.g., JSP, HTML)
  • Controller: dispatcher that handles user interactions and executes business logic (e.g., Servlet, SpringMVC)

Basic Configuration

Getting Started Project

Process flow:

  • Server startup:

    • Loads DispatcherServlet defined in web.xml
    • Reads the configuration in spring-mvc.xml, loading all classes annotated as beans in the controller packages
    • Reads the content marked with @RequestMapping above each bean method
  • Request handling:

    • DispatcherServlet intercepts all requests (/)
    • Matches the request path against all loaded @RequestMapping entries
    • Executes the corresponding method
    • Finds and renders the page in the webapp directory based on the method’s return value

Code demonstration:

  • Add dependencies in pom.xml
  • Define a concrete controller, e.g., java/controller/UserController
  • In webapp/WEB-INF/web.xml, configure the SpringMVC core controller to forward requests to the appropriate business‑logic controller (equivalent to a servlet configuration)
  • resources/spring-mvc.xml

Controller Loading Control

Controller loading control:

SpringMVC handlers (beans) must follow the prescribed format. To avoid loading invalid beans, a bean‑loading filter can be used to include or exclude beans. Presentation‑layer beans are typically marked with @Controller.

  • Configuration in resources/spring-mvc.xml
    • Static resource loading (resources under the webapp directory); enable the MVC namespace
    • Chinese character encoding handling: SpringMVC provides a dedicated filter for Chinese character garbling, configured in web.xml

Annotation‑Driven

WebApplicationContext creates the Spring core container (root/parent container).

  • Parent container: created after the Spring environment loads; contains all beans defined in the Spring context
  • Child container: created after the MVC environment loads; does not contain the parent’s beans
  • The child can access resources in the parent, but the parent cannot access the child’s resources

@EnableWebMvc Annotation purposes:

  • Supports ConversionService configuration for easy custom type converters
  • Supports @NumberFormat annotation for number formatting
  • Supports @DateTimeFormat annotation for date formatting (Date, Calendar)
  • Supports @Valid parameter validation (requires JSR‑303)
  • Works with third‑party JARs and SpringMVC annotations to read/write XML and JSON

Pure annotation development:

  • Convert the SpringMVC core XML configuration to a Java config class, e.g., java/config/SpringMVCConfiguration.java
  • Based on the Servlet 3.0 specification, create a custom servlet container initializer that loads the SpringMVC core config class

Request Mapping

Name: @RequestMapping
Type: method annotation, class annotation
Location: above a handler method or above the handler class

  • Method annotation

    • Purpose: binds a request URL to a specific handling method (no class‑level prefix). Example access format: http://localhost/requestURL2
  • Class annotation

    • Purpose: sets a common URL prefix for all methods in the handler
    • When a class‑level mapping is present, the prefix is added before the actual method mapping, e.g., **/user/requestURL1**
    • If the returned view does not specify an absolute path, Spring will look for the page under the class‑level directory, e.g., webapp/user/page.jsp
  • Common attributes: (omitted for brevity)


Basic Operations

Request Handling

Simple Types

SpringMVC binds incoming parameters to method arguments for quick access.

  • Example URL: http://localhost/requestParam1?name=seazean&age=14

@RequestParam Usage:

  • Type: parameter annotation
  • Location: placed before a method parameter in a handler
  • Purpose: binds a request parameter to the corresponding method argument
  • Example URL: http://localhost/requestParam2?userName=Jock
POJO Types
  • Simple properties: When a POJO contains simple‑type fields, the request parameter names must match the POJO’s field names.
    Example URL: http://localhost/requestParam3?name=seazean&age=14

  • Name conflicts: If a POJO field name collides with another method parameter, both will be set. It is recommended to use the @RequestParam annotation to disambiguate.
    Example URL: http://localhost/requestParam4?name=seazean&age=14

  • Nested objects: When a POJO contains an object property, the request parameter name follows the object hierarchy.
    Example URL: http://localhost/requestParam5?address.province=beijing

  • Collection properties:

    • For simple‑type collections, repeat the same parameter name in the URL.
      Example URL: http://localhost/requestParam6?nick=Jock1&nick=Jockme&nick=zahc
    • For a List of objects, use array‑style notation to indicate the index.
      Example URL: http://localhost/requestParam7?addresses[0].province=bj&addresses[1].province=tj
    • For a Map of objects, use map‑style notation.
      Example URL: http://localhost/requestParam8?addressMap['home'].province=bj&addressMap['job'].province=tj
Array & Collection Parameters
  • Array: Parameter name must match the method argument name, and there must be more than one value.
    Example URL: http://localhost/requestParam9?nick=Jockme&nick=zahc

  • Collection: Same rule as arrays; used for simple‑type data.
    Example URL: http://localhost/requestParam10?nick=Jockme&nick=zahc

Note: By default SpringMVC treats a List as a collection of objects. It first creates an object, then tries to set nick as a property of that object, which fails because List is an interface and cannot be instantiated. Switching to a concrete ArrayList solves the instantiation issue, but ArrayList still has no nick property, so the data remains empty.

Solution: Declare that nick represents multiple values, not a single property. Use the @RequestParam annotation to bundle multiple names parameters into an array; SpringMVC will then recognize the format and treat the argument as an array or collection.

Converters
  • Enable conversion: <mvc:annotation-driven />
  • Purpose: provides controller request forwarding, automatic JSON conversion, etc.

If you call http://localhost/requestParam1?name=seazean&age=seazean, a type‑conversion error occurs.

SpringMVC performs automatic type conversion via the Converter interface:

  • Scalar converters
  • Collection/array converters
  • Default converters

Date conversion: Accessing http://localhost/requestParam11?date=1999-09-09 (http://localhost/requestParam11?date=1999-09-09) triggers an error without a date converter.

Implementation:

  • Declare a custom conversion format and override the default in resources/spring-mvc.xml

  • @DateTimeFormat

    • Type: parameter annotation or field annotation
    • Location: before a method parameter or above a member variable
    • Purpose: specifies a conversion rule for the annotated element

    Requires annotation‑driven support; enable in XML.

  • Custom converters: implement the Converter interface or register a bean in the container.

    • Option 1: (details omitted)
    • Option 2: Register the custom converter in resources/spring-mvc.xml; it will be added to SpringMVC’s ConverterService.
  • Using a converter: (example omitted)


Response Handling

Page Navigation

Forward vs. redirect:

  • Forward: server‑side internal transfer
  • Redirect: client‑side new request

InternalResourceViewResolver (quick page lookup):

  • Common page locations often share a similar structure; you can configure a generic prefix/suffix in spring-mvc.xml to simplify view resolution.
  • If a controller method returns void, the resolved view path is used as the default prefix/suffix.
Data Navigation

ModelAndView is a SpringMVC object that can be returned from a controller method (similar to Model) to carry data to the view.

  • Set data: store attributes in the request scope
  • Set view: logical view name

Code examples:

  • Use HttpServletRequest as a method argument to pass data
  • Use Model as a method argument to pass data
  • Use ModelAndView as a method argument and return it to the caller
  • ModelAndView extensions

In the Java Spring framework, ModelAndView and Model both serve to transfer data between a controller and a view, but they differ:

  • Return type: ModelAndView is a concrete class that bundles model data and view information; Model is an interface used only for storing model attributes.
  • Usage: ModelAndView is typically returned from a handler method and includes the view name; Model is used within a handler to add attributes for the view.
  • View information: ModelAndView can specify the view name or logical path; Model contains no view information.
JSON

Annotation: @ResponseBody

Purpose: When placed on a controller method, the returned object is converted (via an appropriate message converter) to the specified format and written to the response body. If the return type is a String, the string is sent directly; if it’s an object, it is converted to JSON and returned.

Note: If the method lacks @ResponseBody, the return value is wrapped in a ModelAndView by default.

Code examples:

  • Use HttpServletResponse to write data directly
  • Use **@ResponseBody** to treat the returned result as response content (rendered on the page) rather than as a view name
  • Add Jackson dependencies for JSON conversion
  • Use SpringMVC’s built‑in message converters for automatic object‑to‑JSON conversion
  • Manually add a message converter
  • Enable SpringMVC annotation‑driven support
  • Convert collection types to JSON

RESTful Style

Overview

REST (Representational State Transfer) defines how resources are transferred over the network in a particular representation.

  • Resource: any real‑world entity; can be a collection or a single item. Each resource has a unique URI. For example, retrieving a specific class /class/12; a class may have sub‑resources such as all teachers of that class /classes/classId/teachers.
  • Representation: the external form of a resource (e.g., JSON, XML, image, txt).
  • State transfer: describes how server‑side resource state changes (CRUD operations via HTTP verbs). HTTP is a stateless protocol; all resource state is stored on the server.

Access Patterns

RESTful access follows the REST style.

  • Traditional URL style: http://localhost/user/get?id=1
  • RESTful URL style: http://localhost/user/1

Advantages: hides the operation behind the URI, making the request more concise and readable.

Simplified RESTful path configuration: @RestController = @Controller + @ResponseBody

Related annotations: @GetMapping is a derivative of @RequestMapping, so they behave the same; it is recommended to use @GetMapping.

POST and other verbs work similarly.

Filter: HiddenHttpMethodFilter enables RESTful method support in SpringMVC.

Implementation:

  • restful.jsp:

    • Forms use a hidden field to submit the HTTP method; the parameter name is _method and must be used together with method=post.
    • GET requests can be sent via the address bar or a form with method="get".
    • POST requests must be submitted via a form with method="post".
  • java/controller/UserController

  • Interceptor configuration in web.xml

Parameter Annotations

Common RESTful parameter annotations:

  • Use @PathVariable to bind a named variable from the URL path (useful when multiple parameters exist).

Other annotations:

  • @RequestHeader – retrieve request headers
  • @RequestParam – retrieve query parameters (the part after ? in the URL)
  • @CookieValue – retrieve cookie values
  • @RequestAttribute – retrieve request‑scope attributes
  • @RequestBody – retrieve the request body (for POST)
  • @MatrixVariable – matrix variables
  • @ModelAttribute – custom‑type variables

Code examples for different request methods are provided.

Recognition Mechanism

When a form submits using REST, it includes _method=PUT; the request is intercepted by HiddenHttpMethodFilter, which performs the necessary filtering.

org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(): REST clients such as Postman can send PUT, DELETE, etc., directly without being filtered; this changes the default handling defined by _method .


Accessing the Underlying Servlet

SpringMVC allows direct access to the original Servlet API by declaring the appropriate parameters in handler methods.


Originally written by Li Wei (李唯_) and published in Chinese on 后端技术栈全书 (Full-Stack Backend Engineering). Translated and adapted for DriftSeas with permission.

Keep reading

More related articles from DriftSeas.