Servlet Web Applications
- Servlet Web Applications
| This version is still in development and is not considered stable yet. For the latest stable version, please use Spring Boot 4.1.1! |
If you want to build servlet-based web applications, you can take advantage of Spring Boot’s auto-configuration for Spring MVC or Jersey.
The “Spring Web MVC Framework”
The Spring Web MVC framework (often referred to as “Spring MVC”) is a rich “model view controller” web framework.
Spring MVC lets you create special @Controller or @RestController beans to handle incoming HTTP requests.
Methods in your controller are mapped to HTTP by using @RequestMapping annotations.
The following code shows a typical @RestController that serves JSON data:
- Java
- Kotlin
import java.util.List;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/users")
public class MyRestController {
private final UserRepository userRepository;
private final CustomerRepository customerRepository;
public MyRestController(UserRepository userRepository, CustomerRepository customerRepository) {
this.userRepository = userRepository;
this.customerRepository = customerRepository;
}
@GetMapping("/{userId}")
public User getUser(@PathVariable Long userId) {
return this.userRepository.findById(userId).get();
}
@GetMapping("/{userId}/customers")
public List<Customer> getUserCustomers(@PathVariable Long userId) {
return this.userRepository.findById(userId).map(this.customerRepository::findByUser).get();
}
@DeleteMapping("/{userId}")
public void deleteUser(@PathVariable Long userId) {
this.userRepository.deleteById(userId);
}
}
import org.springframework.web.bind.annotation.DeleteMapping
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
@RestController
@RequestMapping("/users")
class MyRestController(private val userRepository: UserRepository, private val customerRepository: CustomerRepository) {
@GetMapping("/{userId}")
fun getUser(@PathVariable userId: Long): User {
return userRepository.findById(userId).get()
}
@GetMapping("/{userId}/customers")
fun getUserCustomers(@PathVariable userId: Long): List<Customer> {
return userRepository.findById(userId).map(customerRepository::findByUser).get()
}
@DeleteMapping("/{userId}")
fun deleteUser(@PathVariable userId: Long) {
userRepository.deleteById(userId)
}
}
“WebMvc.fn”, the functional variant, separates the routing configuration from the actual handling of the requests, as shown in the following example:
- Java
- Kotlin
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.function.RequestPredicate;
import org.springframework.web.servlet.function.RouterFunction;
import org.springframework.web.servlet.function.ServerResponse;
import static org.springframework.web.servlet.function.RequestPredicates.accept;
import static org.springframework.web.servlet.function.RouterFunctions.route;
@Configuration(proxyBeanMethods = false)
public class MyRoutingConfiguration {
private static final RequestPredicate ACCEPT_JSON = accept(MediaType.APPLICATION_JSON);
@Bean
public RouterFunction<ServerResponse> routerFunction(MyUserHandler userHandler) {
return route()
.GET("/{user}", ACCEPT_JSON, userHandler::getUser)
.GET("/{user}/customers", ACCEPT_JSON, userHandler::getUserCustomers)
.DELETE("/{user}", ACCEPT_JSON, userHandler::deleteUser)
.build();
}
}
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.http.MediaType
import org.springframework.web.servlet.function.RequestPredicates.accept
import org.springframework.web.servlet.function.RouterFunction
import org.springframework.web.servlet.function.RouterFunctions
import org.springframework.web.servlet.function.ServerResponse
@Configuration(proxyBeanMethods = false)
class MyRoutingConfiguration {
@Bean
fun routerFunction(userHandler: MyUserHandler): RouterFunction<ServerResponse> {
return RouterFunctions.route()
.GET("/{user}", ACCEPT_JSON, userHandler::getUser)
.GET("/{user}/customers", ACCEPT_JSON, userHandler::getUserCustomers)
.DELETE("/{user}", ACCEPT_JSON, userHandler::deleteUser)
.build()
}
companion object {
private val ACCEPT_JSON = accept(MediaType.APPLICATION_JSON)
}
}
- Java
- Kotlin
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.function.ServerRequest;
import org.springframework.web.servlet.function.ServerResponse;
@Component
public class MyUserHandler {
public ServerResponse getUser(ServerRequest request) {
...
}
public ServerResponse getUserCustomers(ServerRequest request) {
...
}
public ServerResponse deleteUser(ServerRequest request) {
...
}
}
import org.springframework.stereotype.Component
import org.springframework.web.servlet.function.ServerRequest
import org.springframework.web.servlet.function.ServerResponse
@Component
class MyUserHandler {
fun getUser(request: ServerRequest?): ServerResponse {
...
}
fun getUserCustomers(request: ServerRequest?): ServerResponse {
...
}
fun deleteUser(request: ServerRequest?): ServerResponse {
...
}
}
Spring MVC is part of the core Spring Framework, and detailed information is available in the reference documentation. There are also several guides that cover Spring MVC available at spring.io/guides.
You can define as many RouterFunction beans as you like to modularize the definition of the router. Beans can be ordered if you need to apply a precedence. |
Spring MVC Auto-configuration
Spring Boot provides auto-configuration for Spring MVC that works well with most applications.
It replaces the need for @EnableWebMvc and the two cannot be used together.
In addition to Spring MVC’s defaults, the auto-configuration provides the following features:
- Inclusion of
ContentNegotiatingViewResolverandBeanNameViewResolverbeans. - Support for serving static resources, including support for WebJars (covered later in this document).
- Automatic registration of
Converter,GenericConverter, andFormatterbeans. - Support for
HttpMessageConverters(covered later in this document). - Automatic registration of
MessageCodesResolver(covered later in this document). - Static
index.htmlsupport. - Automatic use of a
ConfigurableWebBindingInitializerbean (covered later in this document).
If you want to keep those Spring Boot MVC customizations and make more MVC customizations (interceptors, formatters, view controllers, and other features), you can add your own @Configuration class of type WebMvcConfigurer but without @EnableWebMvc.
If you want to provide custom instances of RequestMappingHandlerMapping, RequestMappingHandlerAdapter, or ExceptionHandlerExceptionResolver, and still keep the Spring Boot MVC customizations, you can declare a bean of type WebMvcRegistrations and use it to provide custom instances of those components.
The custom instances will be subject to further initialization and configuration by Spring MVC.
To participate in, and if desired, override that subsequent processing, a WebMvcConfigurer should be used.
If you do not want to use the auto-configuration and want to take complete control of Spring MVC, add your own @Configuration annotated with @EnableWebMvc.
Alternatively, add your own @Configuration-annotated DelegatingWebMvcConfiguration as described in the @EnableWebMvc API documentation.
Spring MVC Conversion Service
Spring MVC uses a different ConversionService to the one used to convert values from your application.properties or application.yaml file.
It means that Period, Duration and DataSize converters are not available and that @DurationUnit and @DataSizeUnit annotations will be ignored.
If you want to customize the ConversionService used by Spring MVC, you can provide a WebMvcConfigurer bean with an addFormatters method.
From this method you can register any converter that you like, or you can delegate to the static methods available on ApplicationConversionService.
Conversion can also be customized using the spring.mvc.format.* configuration properties.
When not configured, the following defaults are used:
| Property | DateTimeFormatter |
Formats |
|---|---|---|
spring.mvc.format.date |
ofLocalizedDate(FormatStyle.SHORT) |
java.util.Date and LocalDate |
spring.mvc.format.time |
ofLocalizedTime(FormatStyle.SHORT) |
java.time’s LocalTime and OffsetTime |
spring.mvc.format.date-time |
ofLocalizedDateTime(FormatStyle.SHORT) |
java.time’s LocalDateTime, OffsetDateTime, and ZonedDateTime |
HttpMessageConverters
Spring MVC uses the HttpMessageConverter interface to convert HTTP requests and responses.
Sensible defaults are included out of the box.
For example, objects can be automatically converted to JSON (by using the Jackson library) or XML (by using the Jackson XML extension, if available, or by using JAXB if the Jackson XML extension is not available).
By default, strings are encoded in UTF-8.
Any HttpMessageConverter bean that is present in the context is added to the list of converters.
You can also override default converters in the same way.
If you need to add or customize converters, you can declare one or more ClientHttpMessageConvertersCustomizer or
ServerHttpMessageConvertersCustomizer as beans. There, you can choose whether converter instances should be added
before default ones (addCustomConverter) or if they should override a specific default converter (like withJsonConverter).
See the following listing for an example:
- Java
- Kotlin
import java.text.SimpleDateFormat;
import tools.jackson.databind.json.JsonMapper;
import org.springframework.boot.http.converter.autoconfigure.ClientHttpMessageConvertersCustomizer;
import org.springframework.boot.http.converter.autoconfigure.ServerHttpMessageConvertersCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverters.ClientBuilder;
import org.springframework.http.converter.HttpMessageConverters.ServerBuilder;
import org.springframework.http.converter.json.JacksonJsonHttpMessageConverter;
@Configuration(proxyBeanMethods = false)
public class MyHttpMessageConvertersConfiguration {
@Bean
public ClientHttpMessageConvertersCustomizer myClientConvertersCustomizer() {
return (clientBuilder) -> clientBuilder.addCustomConverter(new AdditionalHttpMessageConverter())
.addCustomConverter(new AnotherHttpMessageConverter());
}
@Bean
public JacksonConverterCustomizer jacksonConverterCustomizer() {
JsonMapper jsonMapper = JsonMapper.builder().defaultDateFormat(new SimpleDateFormat("yyyy-MM")).build();
return new JacksonConverterCustomizer(jsonMapper);
}
// contribute a custom JSON converter to both client and server
static class JacksonConverterCustomizer
implements ClientHttpMessageConvertersCustomizer, ServerHttpMessageConvertersCustomizer {
private final JsonMapper jsonMapper;
JacksonConverterCustomizer(JsonMapper jsonMapper) {
this.jsonMapper = jsonMapper;
}
@Override
public void customize(ClientBuilder builder) {
builder.withJsonConverter(new JacksonJsonHttpMessageConverter(this.jsonMapper));
}
@Override
public void customize(ServerBuilder builder) {
builder.withJsonConverter(new JacksonJsonHttpMessageConverter(this.jsonMapper));
}
}
}
import org.springframework.boot.http.converter.autoconfigure.ClientHttpMessageConvertersCustomizer
import org.springframework.boot.http.converter.autoconfigure.ServerHttpMessageConvertersCustomizer
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.http.converter.HttpMessageConverters
import org.springframework.http.converter.json.JacksonJsonHttpMessageConverter
import tools.jackson.databind.json.JsonMapper
import java.text.SimpleDateFormat
@Configuration(proxyBeanMethods = false)
class MyHttpMessageConvertersConfiguration {
@Bean
fun myClientConvertersCustomizer(): ClientHttpMessageConvertersCustomizer {
return ClientHttpMessageConvertersCustomizer { clientBuilder: HttpMessageConverters.ClientBuilder ->
clientBuilder
.addCustomConverter(AdditionalHttpMessageConverter())
.addCustomConverter(AnotherHttpMessageConverter())
}
}
@Bean
fun jacksonConverterCustomizer(): JacksonConverterCustomizer {
val jsonMapper = JsonMapper.builder()
.defaultDateFormat(SimpleDateFormat("yyyy-MM"))
.build()
return JacksonConverterCustomizer(jsonMapper)
}
// contribute a custom JSON converter to both client and server
class JacksonConverterCustomizer(private val jsonMapper: JsonMapper) :
ClientHttpMessageConvertersCustomizer, ServerHttpMessageConvertersCustomizer {
override fun customize(builder: HttpMessageConverters.ClientBuilder) {
builder.withJsonConverter(JacksonJsonHttpMessageConverter(this.jsonMapper))
}
override fun customize(builder: HttpMessageConverters.ServerBuilder) {
builder.withJsonConverter(JacksonJsonHttpMessageConverter(this.jsonMapper))
}
}
}
MessageCodesResolver
Spring MVC has a strategy for generating error codes for rendering error messages from binding errors: MessageCodesResolver.
If you set the spring.mvc.message-codes-resolver-format property PREFIX_ERROR_CODE or POSTFIX_ERROR_CODE, Spring Boot creates one for you (see the enumeration in DefaultMessageCodesResolver.Format).
Static Content
By default, Spring Boot serves static content from a directory called /static (or /public or /resources or /META-INF/resources) in the classpath or from the root of the ServletContext.
It uses the ResourceHttpRequestHandler from Spring MVC so that you can modify that behavior by adding your own WebMvcConfigurer and overriding the addResourceHandlers method.
In a stand-alone web application, the default servlet from the container is not enabled.
It can be enabled using the server.servlet.register-default-servlet property.
The default servlet acts as a fallback, serving content from the root of the ServletContext if Spring decides not to handle it.
Most of the time, this does not happen (unless you modify the default MVC configuration), because Spring can always handle requests through the DispatcherServlet.
By default, resources are mapped on /**, but you can tune that with the spring.mvc.static-path-pattern property.
For instance, relocating all resources to /resources/** can be achieved as follows:
- Properties
- YAML
spring.mvc.static-path-pattern=/resources/**
spring:
mvc:
static-path-pattern: "/resources/**"
You can also customize the static resource locations by using the spring.web.resources.static-locations property (replacing the default values with a list of directory locations).
The root servlet context path, “/”, is automatically added as a location as well.
In addition to the “standard” static resource locations mentioned earlier, a special case is made for Webjars content.
By default, any resources with a path in /webjars/** are served from jar files if they are packaged in the Webjars format.
The path can be customized with the spring.mvc.webjars-path-pattern property.
Do not use the src/main/webapp directory if your application is packaged as a jar. Although this directory is a common standard, it works only with war packaging, and it is silently ignored by most build tools if you generate a jar. |
Spring Boot also supports the advanced resource handling features provided by Spring MVC, allowing use cases such as cache-busting static resources or using version agnostic URLs for Webjars.
To use version agnostic URLs for Webjars, add the org.webjars:webjars-locator-lite dependency.
Then declare your Webjar.
Using jQuery as an example, adding “/webjars/jquery/jquery.min.js” results in “/webjars/jquery/x.y.z/jquery.min.js” where x.y.z is the Webjar version.
To use cache busting, the following configuration configures a cache busting solution for all static resources, effectively adding a content hash, such as <link href=“/css/spring-2a2d595e6ed9a0b24f027f2b63b134d6.css”/>, in URLs:
- Properties
- YAML
spring.web.resources.chain.strategy.content.enabled=true
spring.web.resources.chain.strategy.content.paths=/**
spring:
web:
resources:
chain:
strategy:
content:
enabled: true
paths: "/**"
Links to resources are rewritten in templates at runtime, thanks to a ResourceUrlEncodingFilter that is auto-configured for Thymeleaf and FreeMarker. You should manually declare this filter when using JSPs. Other template engines are currently not automatically supported but can be with custom template macros/helpers and the use of the ResourceUrlProvider. |
When loading resources dynamically with, for example, a JavaScript module loader, renaming files is not an option. That is why other strategies are also supported and can be combined. A “fixed” strategy adds a static version string in the URL without changing the file name, as shown in the following example:
- Properties
- YAML
spring.web.resources.chain.strategy.content.enabled=true
spring.web.resources.chain.strategy.content.paths=/**
spring.web.resources.chain.strategy.fixed.enabled=true
spring.web.resources.chain.strategy.fixed.paths=/js/lib/
spring.web.resources.chain.strategy.fixed.version=v12
spring:
web:
resources:
chain:
strategy:
content:
enabled: true
paths: "/**"
fixed:
enabled: true
paths: "/js/lib/"
version: "v12"
With this configuration, JavaScript modules located under “/js/lib/” use a fixed versioning strategy (“/v12/js/lib/mymodule.js”), while other resources still use the content one (<link href=“/css/spring-2a2d595e6ed9a0b24f027f2b63b134d6.css”/>).
See WebProperties.Resources for more supported options.
| This feature has been thoroughly described in a dedicated blog post and in Spring Framework’s reference documentation. |
Welcome Page
Spring Boot supports both static and templated welcome pages.
It first looks for an index.html file in the configured static content locations.
If one is not found, it then looks for an index template.
If either is found, it is automatically used as the welcome page of the application.
This only acts as a fallback for actual index routes defined by the application.
The ordering is defined by the order of HandlerMapping beans which is by default the following:
RouterFunctionMapping |
Endpoints declared with RouterFunction beans |
RequestMappingHandlerMapping |
Endpoints declared in @Controller beans |
WelcomePageHandlerMapping |
The welcome page support |
Custom Favicon
As with other static resources, Spring Boot checks for a favicon.ico in the configured static content locations.
If such a file is present, it is automatically used as the favicon of the application.
Path Matching and Content Negotiation
Spring MVC can map incoming HTTP requests to handlers by looking at the request path and matching it to the mappings defined in your application (for example, @GetMapping annotations on Controller methods).
Spring Boot chooses to disable suffix pattern matching by default, which means that requests like “GET /projects/spring-boot.json” will not be matched to @GetMapping(“/projects/spring-boot”) mappings.
This is considered as a best practice for Spring MVC applications.
This feature was mainly useful in the past for HTTP clients which did not send proper “Accept” request headers; we needed to make sure to send the correct Content Type to the client.
Nowadays, Content Negotiation is much more reliable.
There are other ways to deal with HTTP clients that do not consistently send proper “Accept” request headers.
Instead of using suffix matching, we can use a query parameter to ensure that requests like “GET /projects/spring-boot?format=json” will be mapped to @GetMapping(“/projects/spring-boot”):
- Properties
- YAML
spring.mvc.contentnegotiation.favor-parameter=true
spring:
mvc:
contentnegotiation:
favor-parameter: true
Or if you prefer to use a different parameter name:
- Properties
- YAML
spring.mvc.contentnegotiation.favor-parameter=true
spring.mvc.contentnegotiation.parameter-name=myparam
spring:
mvc:
contentnegotiation:
favor-parameter: true
parameter-name: "myparam"
Most standard media types are supported out-of-the-box, but you can also define new ones:
- Properties
- YAML
spring.mvc.contentnegotiation.media-types.markdown=text/markdown
spring:
mvc:
contentnegotiation:
media-types:
markdown: "text/markdown"
As of Spring Framework 5.3, Spring MVC supports two strategies for matching request paths to controllers.
By default, Spring Boot uses the PathPatternParser strategy.
PathPatternParser is an optimized implementation but comes with some restrictions compared to the AntPathMatcher strategy.
PathPatternParser restricts usage of some path pattern variants.
It is also incompatible with configuring the DispatcherServlet with a path prefix (spring.mvc.servlet.path).
The strategy can be configured using the spring.mvc.pathmatch.matching-strategy configuration property, as shown in the following example:
- Properties
- YAML
spring.mvc.pathmatch.matching-strategy=ant-path-matcher
spring:
mvc:
pathmatch:
matching-strategy: "ant-path-matcher"
Spring MVC will throw a NoHandlerFoundException if a handler is not found for a request.
Note that, by default, the serving of static content is mapped to /** and will, therefore, provide a handler for all requests.
If no static content is available, ResourceHttpRequestHandler will throw a NoResourceFoundException.
For a NoHandlerFoundException to be thrown, set spring.mvc.static-path-pattern to a more specific value such as /resources/** or set spring.web.resources.add-mappings to false to disable serving of static content entirely.
ConfigurableWebBindingInitializer
Spring MVC uses a WebBindingInitializer to initialize a WebDataBinder for a particular request.
If you create your own ConfigurableWebBindingInitializer @Bean, Spring Boot automatically configures Spring MVC to use it.
Template Engines
As well as REST web services, you can also use Spring MVC to serve dynamic HTML content. Spring MVC supports a variety of templating technologies, including Thymeleaf, FreeMarker, and JSPs. Also, many other templating engines include their own Spring MVC integrations.
Spring Boot includes auto-configuration support for the following templating engines:
| If possible, JSPs should be avoided. There are several known limitations when using them with embedded servlet containers. |
When you use one of these templating engines with the default configuration, your templates are picked up automatically from src/main/resources/templates.
| Depending on how you run your application, your IDE may order the classpath differently. Running your application in the IDE from its main method results in a different ordering than when you run your application by using Maven or Gradle or from its packaged jar. This can cause Spring Boot to fail to find the expected template. If you have this problem, you can reorder the classpath in the IDE to place the module’s classes and resources first. |
Error Handling
By default, Spring Boot provides an /error mapping that handles all errors in a sensible way, and it is registered as a “global” error page in the servlet container.
For machine clients, it produces a JSON response with details of the error, the HTTP status, and the exception message.
For browser clients, there is a “whitelabel” error view that renders the same data in HTML format (to customize it, add a View that resolves to error).
There are a number of spring.web.error properties that can be set if you want to customize the default error handling behavior.
See the Web Properties section of the Appendix.
To replace the default behavior completely, you can implement ErrorController and register a bean definition of that type or add a bean of type ErrorAttributes to use the existing mechanism but replace the contents.
The BasicErrorController can be used as a base class for a custom ErrorController. This is particularly useful if you want to add a handler for a new content type (the default is to handle text/html specifically and provide a fallback for everything else). To do so, extend BasicErrorController, add a public method with a @RequestMapping that has a produces attribute, and create a bean of your new type. |
As of Spring Framework 6.0, RFC 9457 Problem Details is supported.
Spring MVC can produce custom error messages with the application/problem+json media type, like:
{
"type": "https://example.org/problems/unknown-project",
"title": "Unknown project",
"status": 404,
"detail": "No project found for id 'spring-unknown'",
"instance": "/projects/spring-unknown"
}
This support can be enabled by setting spring.mvc.problemdetails.enabled to true.
You can also define a class annotated with @ControllerAdvice to customize the JSON document to return for a particular controller and/or exception type, as shown in the following example:
- Java
- Kotlin
import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
@ControllerAdvice(basePackageClasses = SomeController.class)
public class MyControllerAdvice extends ResponseEntityExceptionHandler {
@ResponseBody
@ExceptionHandler(MyException.class)
public ResponseEntity<?> handleControllerException(HttpServletRequest request, Throwable ex) {
HttpStatus status = getStatus(request);
return new ResponseEntity<>(new MyErrorBody(status.value(), ex.getMessage()), status);
}
private HttpStatus getStatus(HttpServletRequest request) {
Integer code = (Integer) request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
HttpStatus status = HttpStatus.resolve(code);
return (status != null) ? status : HttpStatus.INTERNAL_SERVER_ERROR;
}
}
import jakarta.servlet.RequestDispatcher
import jakarta.servlet.http.HttpServletRequest
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.ControllerAdvice
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.ResponseBody
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler
@ControllerAdvice(basePackageClasses = [SomeController::class])
class MyControllerAdvice : ResponseEntityExceptionHandler() {
@ResponseBody
@ExceptionHandler(MyException::class)
fun handleControllerException(request: HttpServletRequest, ex: Throwable): ResponseEntity<*> {
val status = getStatus(request)
return ResponseEntity(MyErrorBody(status.value(), ex.message), status)
}
private fun getStatus(request: HttpServletRequest): HttpStatus {
val code = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE) as Int
val status = HttpStatus.resolve(code)
return status ?: HttpStatus.INTERNAL_SERVER_ERROR
}
}
In the preceding example, if MyException is thrown by a controller defined in the same package as SomeController, a JSON representation of the MyErrorBody POJO is used instead of the ErrorAttributes representation.
In some cases, errors handled at the controller level are not recorded by web observations or the metrics infrastructure. Applications can ensure that such exceptions are recorded with the observations by setting the handled exception on the observation context.
Custom Error Pages
If you want to display a custom HTML error page for a given status code, you can add a file to an /error directory.
Error pages can either be static HTML (that is, added under any of the static resource directories) or be built by using templates.
The name of the file should be the exact status code or a series mask.
For example, to map 404 to a static HTML file, your directory structure would be as follows:
src/
+- main/
+- java/
| + <source code>
+- resources/
+- public/
+- error/
| +- 404.html
+- <other public assets>
To map all 5xx errors by using a FreeMarker template, your directory structure would be as follows:
src/
+- main/
+- java/
| + <source code>
+- resources/
+- templates/
+- error/
| +- 5xx.ftlh
+- <other templates>
For more complex mappings, you can also add beans that implement the ErrorViewResolver interface, as shown in the following example:
- Java
- Kotlin
import java.util.Map;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.boot.webmvc.autoconfigure.error.ErrorViewResolver;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.ModelAndView;
public class MyErrorViewResolver implements ErrorViewResolver {
@Override
public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status, Map<String, Object> model) {
// Use the request or status to optionally return a ModelAndView
if (status == HttpStatus.INSUFFICIENT_STORAGE) {
// We could add custom model values here
return new ModelAndView("myview");
}
return null;
}
}
import jakarta.servlet.http.HttpServletRequest
import org.springframework.boot.webmvc.autoconfigure.error.ErrorViewResolver
import org.springframework.http.HttpStatus
import org.springframework.web.servlet.ModelAndView
class MyErrorViewResolver : ErrorViewResolver {
override fun resolveErrorView(request: HttpServletRequest, status: HttpStatus,
model: Map<String, Any>): ModelAndView? {
// Use the request or status to optionally return a ModelAndView
if (status == HttpStatus.INSUFFICIENT_STORAGE) {
// We could add custom model values here
return ModelAndView("myview")
}
return null
}
}
You can also use regular Spring MVC features such as @ExceptionHandler methods and @ControllerAdvice.
The ErrorController then picks up any unhandled exceptions.
Mapping Error Pages Outside of Spring MVC
For applications that do not use Spring MVC, you can use the ErrorPageRegistrar interface to directly register ErrorPage instances.
This abstraction works directly with the underlying embedded servlet container and works even if you d
(本文超出站点单文档体积上限,已截断)
