Spring Web MVC framework providing comprehensive web application development capabilities for Java applications built on the Servlet API
npx @tessl/cli install tessl/maven-org-springframework--spring-webmvc@6.2.00
# Spring Web MVC
1
2
Spring Web MVC is the original web framework built on the Servlet API, providing comprehensive web application development capabilities for Java applications. It serves as the foundation for building robust, scalable web applications through its central DispatcherServlet that handles HTTP request processing, routing, and response generation.
3
4
## Package Information
5
6
- **Package Name**: org.springframework:spring-webmvc
7
- **Package Type**: Maven
8
- **Language**: Java
9
- **Installation**: Add to your Maven `pom.xml`:
10
```xml
11
<dependency>
12
<groupId>org.springframework</groupId>
13
<artifactId>spring-webmvc</artifactId>
14
<version>6.2.8</version>
15
</dependency>
16
```
17
18
Or to your Gradle `build.gradle`:
19
```gradle
20
implementation 'org.springframework:spring-webmvc:6.2.8'
21
```
22
23
## Core Imports
24
25
```java
26
import org.springframework.web.servlet.DispatcherServlet;
27
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
28
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
29
import org.springframework.stereotype.Controller;
30
import org.springframework.web.bind.annotation.RequestMapping;
31
import org.springframework.web.servlet.ModelAndView;
32
```
33
34
For functional web programming:
35
```java
36
import org.springframework.web.servlet.function.RouterFunction;
37
import org.springframework.web.servlet.function.ServerRequest;
38
import org.springframework.web.servlet.function.ServerResponse;
39
import static org.springframework.web.servlet.function.RouterFunctions.*;
40
import static org.springframework.web.servlet.function.RequestPredicates.*;
41
```
42
43
## Basic Usage
44
45
### Traditional MVC with Annotations
46
47
```java
48
@Controller
49
public class HelloController {
50
51
@RequestMapping("/hello")
52
public ModelAndView hello() {
53
ModelAndView mv = new ModelAndView("hello");
54
mv.addObject("message", "Hello, World!");
55
return mv;
56
}
57
}
58
59
@Configuration
60
@EnableWebMvc
61
public class WebConfig implements WebMvcConfigurer {
62
63
@Bean
64
public ViewResolver viewResolver() {
65
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
66
resolver.setPrefix("/WEB-INF/views/");
67
resolver.setSuffix(".jsp");
68
return resolver;
69
}
70
}
71
```
72
73
### Functional Web Programming
74
75
```java
76
@Configuration
77
public class RouterConfig {
78
79
@Bean
80
public RouterFunction<ServerResponse> routes() {
81
return route(GET("/hello"), this::hello)
82
.andRoute(POST("/users"), this::createUser);
83
}
84
85
private ServerResponse hello(ServerRequest request) {
86
return ServerResponse.ok().body("Hello, World!");
87
}
88
89
private ServerResponse createUser(ServerRequest request) throws Exception {
90
User user = request.body(User.class);
91
// Process user creation
92
return ServerResponse.created(URI.create("/users/" + user.getId())).build();
93
}
94
}
95
```
96
97
## Architecture
98
99
Spring Web MVC is built around several key architectural patterns:
100
101
- **Central Dispatcher Pattern**: `DispatcherServlet` acts as the front controller, receiving all HTTP requests and coordinating their processing through various handler mappings, adapters, and resolvers.
102
103
- **Strategy Pattern Implementation**: Core interfaces like `HandlerMapping`, `HandlerAdapter`, `ViewResolver`, and `HandlerExceptionResolver` define pluggable strategies for different aspects of request processing.
104
105
- **Handler Chain Pattern**: `HandlerExecutionChain` coordinates the execution of handlers with interceptors for cross-cutting concerns like authentication and logging.
106
107
- **Model-View-Controller Pattern**: Clear separation between business logic (Model), presentation (View), and request handling (Controller) components.
108
109
- **Functional Programming Support**: Modern functional API alongside traditional annotation-driven approach for different development styles.
110
111
## Capabilities
112
113
### Core Servlet Framework
114
115
Central request processing infrastructure including the DispatcherServlet front controller, handler mapping strategies, adapter patterns, and view resolution. This forms the foundation of Spring MVC's request-response lifecycle.
116
117
```java { .api }
118
public class DispatcherServlet extends FrameworkServlet {
119
public DispatcherServlet();
120
public DispatcherServlet(WebApplicationContext webApplicationContext);
121
public void setDetectAllHandlerMappings(boolean detectAllHandlerMappings);
122
public void setDetectAllHandlerAdapters(boolean detectAllHandlerAdapters);
123
public final MultipartResolver getMultipartResolver();
124
public final List<HandlerMapping> getHandlerMappings();
125
}
126
127
public interface HandlerMapping {
128
HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception;
129
default boolean usesPathPatterns();
130
}
131
132
public interface ViewResolver {
133
View resolveViewName(String viewName, Locale locale) throws Exception;
134
}
135
```
136
137
[Core Servlet Framework](./servlet-framework.md)
138
139
### Configuration Framework
140
141
Java-based configuration system using @EnableWebMvc annotation and WebMvcConfigurer interface for customizing Spring MVC behavior. Provides programmatic configuration of handler mappings, view resolvers, message converters, and more.
142
143
```java { .api }
144
@EnableWebMvc
145
public @interface EnableWebMvc {}
146
147
public interface WebMvcConfigurer {
148
default void configurePathMatch(PathMatchConfigurer configurer);
149
default void configureContentNegotiation(ContentNegotiationConfigurer configurer);
150
default void addInterceptors(InterceptorRegistry registry);
151
default void addResourceHandlers(ResourceHandlerRegistry registry);
152
default void addCorsMappings(CorsRegistry registry);
153
default void configureViewResolvers(ViewResolverRegistry registry);
154
default void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers);
155
default void configureMessageConverters(List<HttpMessageConverter<?>> converters);
156
}
157
158
public class ResourceHandlerRegistry {
159
public ResourceHandlerRegistration addResourceHandler(String... pathPatterns);
160
}
161
```
162
163
[Configuration Framework](./configuration.md)
164
165
### Functional Web Framework
166
167
Modern functional programming model for Spring MVC using RouterFunction and HandlerFunction interfaces. Provides an alternative to annotation-based controllers with composable, type-safe request routing and handling.
168
169
```java { .api }
170
@FunctionalInterface
171
public interface RouterFunction<T extends ServerResponse> {
172
Optional<HandlerFunction<T>> route(ServerRequest request);
173
default RouterFunction<T> and(RouterFunction<T> other);
174
default RouterFunction<T> andRoute(RequestPredicate predicate, HandlerFunction<T> handlerFunction);
175
default <S extends ServerResponse> RouterFunction<S> filter(HandlerFilterFunction<T, S> filterFunction);
176
}
177
178
@FunctionalInterface
179
public interface HandlerFunction<T extends ServerResponse> {
180
T handle(ServerRequest request) throws Exception;
181
}
182
183
public interface ServerRequest {
184
HttpMethod method();
185
URI uri();
186
String path();
187
MultiValueMap<String, String> queryParams();
188
<T> T body(Class<T> bodyType) throws IOException, ServletException;
189
}
190
```
191
192
[Functional Web Framework](./functional-web.md)
193
194
### Controller Annotations
195
196
Annotation-driven MVC programming model using @Controller, @RequestMapping, and related annotations for declarative request handling. Includes support for method parameters, return values, exception handling, and asynchronous processing.
197
198
```java { .api }
199
public class RequestMappingHandlerMapping extends AbstractHandlerMethodMapping<RequestMappingInfo> {
200
public void setUseSuffixPatternMatch(boolean useSuffixPatternMatch);
201
public void setUseTrailingSlashMatch(boolean useTrailingSlashMatch);
202
}
203
204
public class RequestMappingHandlerAdapter extends AbstractHandlerMethodAdapter {
205
public void setCustomArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers);
206
public void setCustomReturnValueHandlers(List<HandlerMethodReturnValueHandler> returnValueHandlers);
207
public void setMessageConverters(List<HttpMessageConverter<?>> messageConverters);
208
}
209
210
public class ResponseBodyEmitter {
211
public ResponseBodyEmitter();
212
public ResponseBodyEmitter(Long timeout);
213
public void send(Object object) throws IOException;
214
public void complete();
215
public void onTimeout(Runnable callback);
216
}
217
```
218
219
[Controller Annotations](./controller-annotations.md)
220
221
### View Resolution & Templating
222
223
View resolution system for rendering responses using various template engines and view technologies. Supports JSP, Thymeleaf, FreeMarker, and custom view implementations with flexible content negotiation.
224
225
```java { .api }
226
public abstract class AbstractView implements View {
227
public void setContentType(String contentType);
228
public String getContentType();
229
public void setAttributesMap(Map<String, ?> attributes);
230
protected abstract void renderMergedOutputModel(
231
Map<String, Object> model,
232
HttpServletRequest request,
233
HttpServletResponse response
234
) throws Exception;
235
}
236
237
public class InternalResourceViewResolver extends UrlBasedViewResolver {
238
public void setPrefix(String prefix);
239
public void setSuffix(String suffix);
240
public void setViewClass(Class<?> viewClass);
241
}
242
243
public class ContentNegotiatingViewResolver implements ViewResolver {
244
public void setContentNegotiationManager(ContentNegotiationManager contentNegotiationManager);
245
public void setViewResolvers(List<ViewResolver> viewResolvers);
246
public void setDefaultViews(List<View> defaultViews);
247
}
248
```
249
250
[View Resolution & Templating](./view-resolution.md)
251
252
### Resource Handling
253
254
Static resource serving capabilities with support for resource transformation, compression, versioning, and caching. Handles CSS, JavaScript, images, and other static assets with customizable resolution strategies.
255
256
```java { .api }
257
public class ResourceHttpRequestHandler implements HttpRequestHandler {
258
public void setLocations(List<Resource> locations);
259
public List<Resource> getLocations();
260
public void setResourceResolvers(List<ResourceResolver> resourceResolvers);
261
public void setResourceTransformers(List<ResourceTransformer> resourceTransformers);
262
}
263
264
public interface ResourceResolver {
265
Resource resolveResource(
266
HttpServletRequest request,
267
String requestPath,
268
List<? extends Resource> locations,
269
ResourceResolverChain chain
270
);
271
String resolveUrlPath(
272
String resourcePath,
273
List<? extends Resource> locations,
274
ResourceResolverChain chain
275
);
276
}
277
```
278
279
[Resource Handling](./resource-handling.md)
280
281
### Support Utilities
282
283
Support classes and utilities for servlet initialization, request context access, URI building, internationalization, and other cross-cutting concerns. Includes initializers for programmatic servlet configuration and context utilities.
284
285
```java { .api }
286
public abstract class AbstractDispatcherServletInitializer implements WebApplicationInitializer {
287
protected abstract WebApplicationContext createServletApplicationContext();
288
protected abstract String[] getServletMappings();
289
protected String getServletName();
290
protected Filter[] getServletFilters();
291
}
292
293
public class RequestContextUtils {
294
public static WebApplicationContext findWebApplicationContext(HttpServletRequest request);
295
public static LocaleResolver getLocaleResolver(HttpServletRequest request);
296
public static Locale getLocale(HttpServletRequest request);
297
public static FlashMap getInputFlashMap(HttpServletRequest request);
298
}
299
300
public class ServletUriComponentsBuilder extends UriComponentsBuilder {
301
public static ServletUriComponentsBuilder fromContextPath(HttpServletRequest request);
302
public static ServletUriComponentsBuilder fromCurrentRequest();
303
public static ServletUriComponentsBuilder fromCurrentContextPath();
304
}
305
```
306
307
[Support Utilities](./support-utilities.md)
308
309
## Types
310
311
### Core Data Types
312
313
```java { .api }
314
public class ModelAndView {
315
public ModelAndView();
316
public ModelAndView(String viewName);
317
public ModelAndView(View view);
318
public ModelAndView(String viewName, Map<String, ?> model);
319
public void setViewName(String viewName);
320
public String getViewName();
321
public void setView(View view);
322
public View getView();
323
public ModelAndView addObject(String attributeName, Object attributeValue);
324
public Map<String, Object> getModel();
325
public void setStatus(HttpStatusCode status);
326
public boolean hasView();
327
}
328
329
public class HandlerExecutionChain {
330
public HandlerExecutionChain(Object handler);
331
public HandlerExecutionChain(Object handler, HandlerInterceptor... interceptors);
332
public Object getHandler();
333
public HandlerInterceptor[] getInterceptors();
334
public boolean applyPreHandle(HttpServletRequest request, HttpServletResponse response) throws Exception;
335
public void applyPostHandle(HttpServletRequest request, HttpServletResponse response, ModelAndView mv) throws Exception;
336
}
337
```
338
339
### Exception Types
340
341
```java { .api }
342
public class NoHandlerFoundException extends ServletException {
343
public NoHandlerFoundException(String httpMethod, String requestURL, HttpHeaders headers);
344
public String getHttpMethod();
345
public String getRequestURL();
346
public HttpHeaders getHeaders();
347
}
348
349
public class ModelAndViewDefiningException extends Exception {
350
public ModelAndViewDefiningException(ModelAndView modelAndView);
351
public ModelAndView getModelAndView();
352
}
353
```
354
355
### Flash Map Support
356
357
```java { .api }
358
public class FlashMap extends HashMap<String, Object> {
359
public FlashMap addAttribute(String attributeName, Object attributeValue);
360
public FlashMap addAllAttributes(Map<String, ?> attributes);
361
public void setTargetRequestPath(String path);
362
public String getTargetRequestPath();
363
public void setTargetRequestParams(MultiValueMap<String, String> params);
364
public MultiValueMap<String, String> getTargetRequestParams();
365
}
366
367
public interface FlashMapManager {
368
FlashMap retrieveAndUpdate(HttpServletRequest request, HttpServletResponse response);
369
void saveOutputFlashMap(FlashMap flashMap, HttpServletRequest request, HttpServletResponse response);
370
}
371
```