0
# Web Configuration
1
2
Spring Boot's web configuration provides comprehensive auto-configuration for both servlet-based (Spring MVC) and reactive (Spring WebFlux) web applications, including embedded server support, error handling, and HTTP processing.
3
4
## Capabilities
5
6
### Servlet Web Configuration
7
8
Auto-configurations for traditional servlet-based web applications using Spring MVC.
9
10
```java { .api }
11
/**
12
* Auto-configuration for Spring MVC DispatcherServlet
13
* Provides the core servlet for handling HTTP requests in Spring MVC applications
14
*/
15
@AutoConfiguration
16
@ConditionalOnWebApplication(type = Type.SERVLET)
17
@ConditionalOnClass(DispatcherServlet.class)
18
@AutoConfigureAfter(ServletWebServerFactoryAutoConfiguration.class)
19
public class DispatcherServletAutoConfiguration {
20
21
/**
22
* Default DispatcherServlet registration path
23
*/
24
public static final String DEFAULT_DISPATCHER_SERVLET_REGISTRATION_PATH = "/*";
25
26
/**
27
* Default DispatcherServlet bean name
28
*/
29
public static final String DEFAULT_DISPATCHER_SERVLET_BEAN_NAME = "dispatcherServlet";
30
}
31
32
/**
33
* Auto-configuration for Spring MVC framework
34
* Configures view resolvers, message converters, and other MVC components
35
*/
36
@AutoConfiguration
37
@ConditionalOnWebApplication(type = Type.SERVLET)
38
@ConditionalOnClass({Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class})
39
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
40
@AutoConfigureAfter({DispatcherServletAutoConfiguration.class, TaskExecutionAutoConfiguration.class, ValidationAutoConfiguration.class})
41
public class WebMvcAutoConfiguration {
42
43
/**
44
* Default date format for HTTP date headers
45
*/
46
public static final String DEFAULT_PREFIX = "";
47
48
/**
49
* Default suffix for view names
50
*/
51
public static final String DEFAULT_SUFFIX = "";
52
}
53
54
/**
55
* Auto-configuration for servlet web server factories
56
* Configures embedded servers like Tomcat, Jetty, and Undertow
57
*/
58
@AutoConfiguration
59
@ConditionalOnWebApplication(type = Type.SERVLET)
60
@ConditionalOnClass(ServletRequest.class)
61
@ConditionalOnMissingBean(value = ServletWebServerFactory.class, search = SearchStrategy.CURRENT)
62
public class ServletWebServerFactoryAutoConfiguration {
63
64
/**
65
* Configuration for Tomcat embedded server
66
*/
67
@Configuration(proxyBeanMethods = false)
68
@ConditionalOnClass({Servlet.class, Tomcat.class, UpgradeProtocol.class})
69
@ConditionalOnMissingBean(value = ServletWebServerFactory.class, search = SearchStrategy.CURRENT)
70
static class EmbeddedTomcat {
71
72
@Bean
73
public TomcatServletWebServerFactory tomcatServletWebServerFactory(
74
ObjectProvider<TomcatConnectorCustomizer> connectorCustomizers,
75
ObjectProvider<TomcatContextCustomizer> contextCustomizers,
76
ObjectProvider<TomcatProtocolHandlerCustomizer<?>> protocolHandlerCustomizers) {
77
// Tomcat server factory configuration
78
}
79
}
80
81
/**
82
* Configuration for Jetty embedded server
83
*/
84
@Configuration(proxyBeanMethods = false)
85
@ConditionalOnClass({Servlet.class, Server.class, Loader.class, WebAppContext.class})
86
@ConditionalOnMissingBean(value = ServletWebServerFactory.class, search = SearchStrategy.CURRENT)
87
static class EmbeddedJetty {
88
89
@Bean
90
public JettyServletWebServerFactory jettyServletWebServerFactory(
91
ObjectProvider<JettyServerCustomizer> serverCustomizers) {
92
// Jetty server factory configuration
93
}
94
}
95
}
96
```
97
98
**Usage Examples:**
99
100
```java
101
// Custom servlet configuration
102
@Configuration
103
public class WebConfig implements WebMvcConfigurer {
104
105
@Override
106
public void addViewControllers(ViewControllerRegistry registry) {
107
registry.addViewController("/").setViewName("index");
108
}
109
110
@Override
111
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
112
converters.add(new MappingJackson2HttpMessageConverter());
113
}
114
}
115
116
// Custom embedded server configuration
117
@Component
118
public class TomcatCustomizer implements WebServerFactoryCustomizer<TomcatServletWebServerFactory> {
119
120
@Override
121
public void customize(TomcatServletWebServerFactory factory) {
122
factory.setPort(8081);
123
factory.addConnectorCustomizers(connector -> {
124
connector.setMaxThreads(200);
125
});
126
}
127
}
128
```
129
130
### Reactive Web Configuration
131
132
Auto-configurations for reactive web applications using Spring WebFlux.
133
134
```java { .api }
135
/**
136
* Auto-configuration for Spring WebFlux framework
137
* Configures reactive web components and handlers
138
*/
139
@AutoConfiguration
140
@ConditionalOnWebApplication(type = Type.REACTIVE)
141
@ConditionalOnClass(WebFluxConfigurer.class)
142
@ConditionalOnMissingBean({WebFluxConfigurationSupport.class, WebFluxConfigurer.class})
143
@AutoConfigureAfter({ReactiveWebServerFactoryAutoConfiguration.class, CodecsAutoConfiguration.class, ValidationAutoConfiguration.class})
144
public class WebFluxAutoConfiguration {
145
146
/**
147
* Default path pattern parser
148
*/
149
public static final String DEFAULT_PATH_PATTERN_PARSER = "pathPatternParser";
150
151
/**
152
* Creates WebFlux configuration
153
*/
154
@Bean
155
@Order(0)
156
public WebFluxConfigurer webFluxConfigurer(
157
ObjectProvider<WebFluxCustomizer> webFluxCustomizers) {
158
// WebFlux configuration setup
159
}
160
}
161
162
/**
163
* Auto-configuration for reactive web server factories
164
* Configures embedded reactive servers like Netty and Undertow
165
*/
166
@AutoConfiguration
167
@ConditionalOnWebApplication(type = Type.REACTIVE)
168
@ConditionalOnMissingBean(value = ReactiveWebServerFactory.class, search = SearchStrategy.CURRENT)
169
public class ReactiveWebServerFactoryAutoConfiguration {
170
171
/**
172
* Configuration for Netty reactive server
173
*/
174
@Configuration(proxyBeanMethods = false)
175
@ConditionalOnClass({HttpServer.class})
176
@ConditionalOnMissingBean(value = ReactiveWebServerFactory.class, search = SearchStrategy.CURRENT)
177
static class EmbeddedNetty {
178
179
@Bean
180
public NettyReactiveWebServerFactory nettyReactiveWebServerFactory(
181
ObjectProvider<NettyReactiveWebServerFactoryCustomizer> customizers) {
182
// Netty server factory configuration
183
}
184
}
185
}
186
```
187
188
**Usage Examples:**
189
190
```java
191
// Reactive web configuration
192
@Configuration
193
public class ReactiveWebConfig implements WebFluxConfigurer {
194
195
@Override
196
public void addCorsMappings(CorsRegistry registry) {
197
registry.addMapping("/**")
198
.allowedOrigins("*")
199
.allowedMethods("*");
200
}
201
202
@Override
203
public void configureHttpMessageCodecs(ServerCodecConfigurer configurer) {
204
configurer.defaultCodecs().maxInMemorySize(1024 * 1024);
205
}
206
}
207
208
// Custom reactive server configuration
209
@Component
210
public class NettyCustomizer implements WebServerFactoryCustomizer<NettyReactiveWebServerFactory> {
211
212
@Override
213
public void customize(NettyReactiveWebServerFactory factory) {
214
factory.setPort(8080);
215
factory.addServerCustomizers(httpServer ->
216
httpServer.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)
217
);
218
}
219
}
220
```
221
222
### HTTP Encoding Configuration
223
224
Auto-configuration for HTTP character encoding and content negotiation.
225
226
```java { .api }
227
/**
228
* Auto-configuration for HTTP character encoding
229
* Configures character encoding filters and content negotiation
230
*/
231
@AutoConfiguration
232
@ConditionalOnWebApplication(type = Type.SERVLET)
233
@ConditionalOnClass(CharacterEncodingFilter.class)
234
@ConditionalOnProperty(prefix = "server.servlet.encoding", value = "enabled", matchIfMissing = true)
235
public class HttpEncodingAutoConfiguration {
236
237
/**
238
* Default character encoding
239
*/
240
public static final String DEFAULT_CHARSET = "UTF-8";
241
242
/**
243
* Creates character encoding filter
244
*/
245
@Bean
246
@ConditionalOnMissingBean
247
public CharacterEncodingFilter characterEncodingFilter() {
248
CharacterEncodingFilter filter = new OrderedCharacterEncodingFilter();
249
filter.setEncoding(this.properties.getCharset().name());
250
filter.setForceRequestEncoding(this.properties.shouldForce(Encoding.Type.REQUEST));
251
filter.setForceResponseEncoding(this.properties.shouldForce(Encoding.Type.RESPONSE));
252
return filter;
253
}
254
}
255
256
/**
257
* Configuration properties for HTTP encoding
258
*/
259
@ConfigurationProperties(prefix = "server.servlet.encoding")
260
public class Encoding {
261
262
/**
263
* Charset for HTTP requests and responses
264
*/
265
private Charset charset = StandardCharsets.UTF_8;
266
267
/**
268
* Whether to force encoding for requests
269
*/
270
private Boolean force;
271
272
/**
273
* Whether to force encoding for requests
274
*/
275
private Boolean forceRequest;
276
277
/**
278
* Whether to force encoding for responses
279
*/
280
private Boolean forceResponse;
281
282
/**
283
* Locale resolver to charset mapping
284
*/
285
private Map<Locale, Charset> mapping = new HashMap<>();
286
287
// Getters and setters
288
public Charset getCharset() { return this.charset; }
289
public void setCharset(Charset charset) { this.charset = charset; }
290
public boolean shouldForce(Type type) { /* force logic */ }
291
292
public enum Type {
293
REQUEST, RESPONSE
294
}
295
}
296
```
297
298
### Error Handling Configuration
299
300
Auto-configuration for web error handling and custom error pages.
301
302
```java { .api }
303
/**
304
* Auto-configuration for web error handling
305
* Provides default error pages and error handling mechanisms
306
*/
307
@AutoConfiguration
308
@ConditionalOnWebApplication(type = Type.SERVLET)
309
@ConditionalOnClass({Servlet.class, DispatcherServlet.class})
310
@AutoConfigureAfter({DispatcherServletAutoConfiguration.class})
311
public class ErrorMvcAutoConfiguration {
312
313
/**
314
* Default error path
315
*/
316
private static final String ERROR_PATH = "/error";
317
318
/**
319
* Creates basic error controller
320
*/
321
@Bean
322
@ConditionalOnMissingBean(value = ErrorController.class, search = SearchStrategy.CURRENT)
323
public BasicErrorController basicErrorController(ErrorAttributes errorAttributes,
324
ObjectProvider<ErrorViewResolver> errorViewResolvers) {
325
return new BasicErrorController(errorAttributes, this.serverProperties.getError(),
326
errorViewResolvers.orderedStream().collect(Collectors.toList()));
327
}
328
329
/**
330
* Creates default error attributes
331
*/
332
@Bean
333
@ConditionalOnMissingBean(value = ErrorAttributes.class, search = SearchStrategy.CURRENT)
334
public DefaultErrorAttributes errorAttributes() {
335
return new DefaultErrorAttributes();
336
}
337
}
338
339
/**
340
* Error properties configuration
341
*/
342
@ConfigurationProperties(prefix = "server.error")
343
public class ErrorProperties {
344
345
/**
346
* Path of the error controller
347
*/
348
private String path = "/error";
349
350
/**
351
* Whether to include exception details in error responses
352
*/
353
private IncludeAttribute includeException = IncludeAttribute.NEVER;
354
355
/**
356
* Whether to include stack trace in error responses
357
*/
358
private IncludeAttribute includeStacktrace = IncludeAttribute.NEVER;
359
360
/**
361
* Whether to include error message in responses
362
*/
363
private IncludeAttribute includeMessage = IncludeAttribute.NEVER;
364
365
/**
366
* Whether to include binding errors in responses
367
*/
368
private IncludeAttribute includeBindingErrors = IncludeAttribute.NEVER;
369
370
// Getters and setters
371
public String getPath() { return this.path; }
372
public void setPath(String path) { this.path = path; }
373
374
public enum IncludeAttribute {
375
NEVER, ALWAYS, ON_PARAM
376
}
377
}
378
```
379
380
### Resource Handling Configuration
381
382
Auto-configuration for static resource handling, caching, and compression.
383
384
```java { .api }
385
/**
386
* Auto-configuration for static resource handling
387
* Configures static resource locations, caching, and optimization
388
*/
389
@AutoConfiguration
390
@ConditionalOnWebApplication(type = Type.SERVLET)
391
@ConditionalOnClass({Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class})
392
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
393
@AutoConfigureAfter({DispatcherServletAutoConfiguration.class})
394
public class WebMvcAutoConfiguration {
395
396
/**
397
* Default static resource locations
398
*/
399
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
400
"classpath:/META-INF/resources/",
401
"classpath:/resources/",
402
"classpath:/static/",
403
"classpath:/public/"
404
};
405
406
/**
407
* Configuration for resource handling
408
*/
409
@Configuration(proxyBeanMethods = false)
410
@ConditionalOnEnabledResourceChain
411
static class ResourceChainCustomizerConfiguration {
412
413
@Bean
414
public ResourceChainResourceHandlerRegistrationCustomizer resourceHandlerRegistrationCustomizer(
415
WebProperties webProperties) {
416
return new ResourceChainResourceHandlerRegistrationCustomizer(webProperties.getResources());
417
}
418
}
419
}
420
421
/**
422
* Web properties for resource configuration
423
*/
424
@ConfigurationProperties(prefix = "spring.web")
425
public class WebProperties {
426
427
/**
428
* Resource handling properties
429
*/
430
private final Resources resources = new Resources();
431
432
public Resources getResources() {
433
return this.resources;
434
}
435
436
/**
437
* Static resource configuration
438
*/
439
public static class Resources {
440
441
/**
442
* Static resource locations
443
*/
444
private String[] staticLocations = CLASSPATH_RESOURCE_LOCATIONS;
445
446
/**
447
* Whether to add mappings for resource locations
448
*/
449
private boolean addMappings = true;
450
451
/**
452
* Cache configuration
453
*/
454
private final Cache cache = new Cache();
455
456
/**
457
* Resource chain configuration
458
*/
459
private final Chain chain = new Chain();
460
461
// Getters and setters
462
public String[] getStaticLocations() { return this.staticLocations; }
463
public void setStaticLocations(String[] staticLocations) { this.staticLocations = staticLocations; }
464
465
/**
466
* Cache settings for static resources
467
*/
468
public static class Cache {
469
/**
470
* Cache period for resources
471
*/
472
private Duration period;
473
474
/**
475
* Cache control settings
476
*/
477
private final Cachecontrol cachecontrol = new Cachecontrol();
478
479
/**
480
* Whether to use last modified header
481
*/
482
private Boolean useLastModified = true;
483
484
public static class Cachecontrol {
485
private Duration maxAge;
486
private Boolean noCache;
487
private Boolean noStore;
488
private Boolean mustRevalidate;
489
private Boolean noTransform;
490
private Boolean cachePublic;
491
private Boolean cachePrivate;
492
private Boolean proxyRevalidate;
493
private Duration staleWhileRevalidate;
494
private Duration staleIfError;
495
private Duration sMaxAge;
496
}
497
}
498
499
/**
500
* Resource chain configuration for optimization
501
*/
502
public static class Chain {
503
/**
504
* Whether to enable resource chain
505
*/
506
private Boolean enabled;
507
508
/**
509
* Whether to cache resources
510
*/
511
private boolean cache = true;
512
513
/**
514
* Whether to enable HTML compression
515
*/
516
private boolean compressed = false;
517
518
/**
519
* Strategy for resource resolution
520
*/
521
private final Strategy strategy = new Strategy();
522
523
public static class Strategy {
524
private final Fixed fixed = new Fixed();
525
private final Content content = new Content();
526
527
public static class Fixed {
528
private boolean enabled = false;
529
private String[] paths = new String[0];
530
private String version;
531
}
532
533
public static class Content {
534
private boolean enabled = false;
535
private String[] paths = new String[] { "/**" };
536
}
537
}
538
}
539
}
540
}
541
```
542
543
**Usage Examples:**
544
545
```java
546
// Custom resource configuration
547
@Configuration
548
public class ResourceConfig implements WebMvcConfigurer {
549
550
@Override
551
public void addResourceHandlers(ResourceHandlerRegistry registry) {
552
registry.addResourceHandler("/custom/**")
553
.addResourceLocations("classpath:/custom-static/")
554
.setCachePeriod(31556926)
555
.resourceChain(true)
556
.addResolver(new VersionResourceResolver().addContentVersionStrategy("/**"));
557
}
558
}
559
560
// Custom error handling
561
@ControllerAdvice
562
public class GlobalExceptionHandler {
563
564
@ExceptionHandler(ResourceNotFoundException.class)
565
public ResponseEntity<ErrorResponse> handleResourceNotFound(ResourceNotFoundException ex) {
566
ErrorResponse error = new ErrorResponse("RESOURCE_NOT_FOUND", ex.getMessage());
567
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(error);
568
}
569
}
570
571
// Properties configuration
572
# application properties
573
spring.web.resources.static-locations=classpath:/static/,classpath:/public/
574
spring.web.resources.cache.period=31536000
575
spring.web.resources.chain.enabled=true
576
spring.web.resources.chain.compressed=true
577
server.error.include-message=always
578
server.error.include-binding-errors=always
579
```
580
581
## Types
582
583
### Web Configuration Types
584
585
```java { .api }
586
/**
587
* Enumeration of web application types
588
*/
589
public enum WebApplicationType {
590
/**
591
* Not a web application
592
*/
593
NONE,
594
595
/**
596
* Servlet-based web application
597
*/
598
SERVLET,
599
600
/**
601
* Reactive web application
602
*/
603
REACTIVE
604
}
605
606
/**
607
* Interface for customizing web server factories
608
*/
609
public interface WebServerFactoryCustomizer<T extends WebServerFactory> {
610
/**
611
* Customize the specified web server factory
612
* @param factory the web server factory to customize
613
*/
614
void customize(T factory);
615
}
616
617
/**
618
* Interface for customizing servlet web server factories
619
*/
620
public interface ServletWebServerFactory extends WebServerFactory {
621
/**
622
* Get a new fully configured but paused WebServer instance
623
* @param servletContextInitializer ServletContext initializers
624
* @return WebServer instance
625
*/
626
WebServer getWebServer(ServletContextInitializer... servletContextInitializer);
627
}
628
629
/**
630
* Interface for customizing reactive web server factories
631
*/
632
public interface ReactiveWebServerFactory extends WebServerFactory {
633
/**
634
* Get a new fully configured but paused WebServer instance
635
* @param httpHandler HTTP handler for requests
636
* @return WebServer instance
637
*/
638
WebServer getWebServer(HttpHandler httpHandler);
639
}
640
```
641
642
### HTTP Message Converter Types
643
644
```java { .api }
645
/**
646
* Registry for HTTP message converters
647
*/
648
public interface HttpMessageConvertersAutoConfiguration {
649
650
/**
651
* String HTTP message converter
652
*/
653
@Bean
654
@ConditionalOnMissingBean
655
public StringHttpMessageConverter stringHttpMessageConverter();
656
657
/**
658
* JSON HTTP message converter using Jackson
659
*/
660
@Bean
661
@ConditionalOnClass(ObjectMapper.class)
662
@ConditionalOnBean(ObjectMapper.class)
663
@ConditionalOnProperty(name = "spring.http.converters.preferred-json-mapper", havingValue = "jackson", matchIfMissing = true)
664
public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter(ObjectMapper objectMapper);
665
}
666
667
/**
668
* Customizer for HTTP message converters
669
*/
670
public interface HttpMessageConverterCustomizer {
671
/**
672
* Customize the HTTP message converter
673
* @param converter the converter to customize
674
*/
675
void customize(HttpMessageConverter<?> converter);
676
}
677
```