[[web.servlet]]
= Servlet Web Applications

If you want to build servlet-based web applications, you can take advantage of Spring Boot's auto-configuration for Spring MVC or Jersey.



[[web.servlet.spring-mvc]]
== The "`Spring Web MVC Framework`"

The {url-spring-framework-docs}/web/webmvc.html[Spring Web MVC framework] (often referred to as "`Spring MVC`") is a rich "`model view controller`" web framework.
Spring MVC lets you create special javadoc:org.springframework.stereotype.Controller[format=annotation] or javadoc:org.springframework.web.bind.annotation.RestController[format=annotation] beans to handle incoming HTTP requests.
Methods in your controller are mapped to HTTP by using javadoc:org.springframework.web.bind.annotation.RequestMapping[format=annotation] annotations.

The following code shows a typical javadoc:org.springframework.web.bind.annotation.RestController[format=annotation] that serves JSON data:

include-code::MyRestController[]

"`WebMvc.fn`", the functional variant, separates the routing configuration from the actual handling of the requests, as shown in the following example:

include-code::MyRoutingConfiguration[]

include-code::MyUserHandler[]

Spring MVC is part of the core Spring Framework, and detailed information is available in the {url-spring-framework-docs}/web/webmvc.html[reference documentation].
There are also several guides that cover Spring MVC available at https://spring.io/guides.

TIP: You can define as many javadoc:org.springframework.web.servlet.function.RouterFunction[] beans as you like to modularize the definition of the router.
Beans can be ordered if you need to apply a precedence.



[[web.servlet.spring-mvc.auto-configuration]]
=== Spring MVC Auto-configuration

Spring Boot provides auto-configuration for Spring MVC that works well with most applications.
It replaces the need for javadoc:org.springframework.web.servlet.config.annotation.EnableWebMvc[format=annotation] and the two cannot be used together.
In addition to Spring MVC's defaults, the auto-configuration provides the following features:

* Inclusion of javadoc:org.springframework.web.servlet.view.ContentNegotiatingViewResolver[] and javadoc:org.springframework.web.servlet.view.BeanNameViewResolver[] beans.
* Support for serving static resources, including support for WebJars (covered xref:web/servlet.adoc#web.servlet.spring-mvc.static-content[later in this document]).
* Automatic registration of javadoc:org.springframework.core.convert.converter.Converter[], javadoc:org.springframework.core.convert.converter.GenericConverter[], and javadoc:org.springframework.format.Formatter[] beans.
* Support for javadoc:org.springframework.boot.http.converter.autoconfigure.HttpMessageConverters[] (covered xref:web/servlet.adoc#web.servlet.spring-mvc.message-converters[later in this document]).
* Automatic registration of javadoc:org.springframework.validation.MessageCodesResolver[] (covered xref:web/servlet.adoc#web.servlet.spring-mvc.message-codes[later in this document]).
* Static `index.html` support.
* Automatic use of a javadoc:org.springframework.web.bind.support.ConfigurableWebBindingInitializer[] bean (covered xref:web/servlet.adoc#web.servlet.spring-mvc.binding-initializer[later in this document]).

If you want to keep those Spring Boot MVC customizations and make more {url-spring-framework-docs}/web/webmvc.html[MVC customizations] (interceptors, formatters, view controllers, and other features), you can add your own javadoc:org.springframework.context.annotation.Configuration[format=annotation] class of type javadoc:org.springframework.web.servlet.config.annotation.WebMvcConfigurer[] but *without* javadoc:org.springframework.web.servlet.config.annotation.EnableWebMvc[format=annotation].

If you want to provide custom instances of javadoc:org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping[], javadoc:org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter[], or javadoc:org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver[], and still keep the Spring Boot MVC customizations, you can declare a bean of type javadoc:org.springframework.boot.webmvc.autoconfigure.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 javadoc:org.springframework.web.servlet.config.annotation.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 javadoc:org.springframework.context.annotation.Configuration[format=annotation] annotated with javadoc:org.springframework.web.servlet.config.annotation.EnableWebMvc[format=annotation].
Alternatively, add your own javadoc:org.springframework.context.annotation.Configuration[format=annotation]-annotated javadoc:org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration[] as described in the javadoc:org.springframework.web.servlet.config.annotation.EnableWebMvc[format=annotation] API documentation.



[[web.servlet.spring-mvc.conversion-service]]
=== Spring MVC Conversion Service

Spring MVC uses a different javadoc:org.springframework.core.convert.ConversionService[] to the one used to convert values from your `application.properties` or `application.yaml` file.
It means that javadoc:java.time.Period[], javadoc:java.time.Duration[] and javadoc:org.springframework.util.unit.DataSize[] converters are not available and that javadoc:org.springframework.boot.convert.DurationUnit[format=annotation] and javadoc:org.springframework.boot.convert.DataSizeUnit[format=annotation] annotations will be ignored.

If you want to customize the javadoc:org.springframework.core.convert.ConversionService[] used by Spring MVC, you can provide a javadoc:org.springframework.web.servlet.config.annotation.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 javadoc:org.springframework.boot.convert.ApplicationConversionService[].

Conversion can also be customized using the `spring.mvc.format.*` configuration properties.
When not configured, the following defaults are used:

|===
|Property |`DateTimeFormatter` |Formats

|configprop:spring.mvc.format.date[]
|`ofLocalizedDate(FormatStyle.SHORT)`
|`java.util.Date` and javadoc:java.time.LocalDate[]

|configprop:spring.mvc.format.time[]
|`ofLocalizedTime(FormatStyle.SHORT)`
|java.time's javadoc:java.time.LocalTime[] and javadoc:java.time.OffsetTime[]

|configprop:spring.mvc.format.date-time[]
|`ofLocalizedDateTime(FormatStyle.SHORT)`
|java.time's javadoc:java.time.LocalDateTime[], javadoc:java.time.OffsetDateTime[], and javadoc:java.time.ZonedDateTime[]
|===



[[web.servlet.spring-mvc.message-converters]]
=== HttpMessageConverters

Spring MVC uses the javadoc:org.springframework.http.converter.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 javadoc:org.springframework.http.converter.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 javadoc:org.springframework.boot.http.converter.autoconfigure.ClientHttpMessageConvertersCustomizer[] or
javadoc:org.springframework.boot.http.converter.autoconfigure.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:

include-code::MyHttpMessageConvertersConfiguration[]



[[web.servlet.spring-mvc.message-codes]]
=== MessageCodesResolver

Spring MVC has a strategy for generating error codes for rendering error messages from binding errors: javadoc:org.springframework.validation.MessageCodesResolver[].
If you set the configprop:spring.mvc.message-codes-resolver-format[] property `PREFIX_ERROR_CODE` or `POSTFIX_ERROR_CODE`, Spring Boot creates one for you (see the enumeration in javadoc:org.springframework.validation.DefaultMessageCodesResolver$Format[]).



[[web.servlet.spring-mvc.static-content]]
=== 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 javadoc:jakarta.servlet.ServletContext[].
It uses the javadoc:org.springframework.web.servlet.resource.ResourceHttpRequestHandler[] from Spring MVC so that you can modify that behavior by adding your own javadoc:org.springframework.web.servlet.config.annotation.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 configprop:server.servlet.register-default-servlet[] property.

The default servlet acts as a fallback, serving content from the root of the javadoc:jakarta.servlet.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 javadoc:org.springframework.web.servlet.DispatcherServlet[].

By default, resources are mapped on `+/**+`, but you can tune that with the configprop:spring.mvc.static-path-pattern[] property.
For instance, relocating all resources to `/resources/**` can be achieved as follows:

[configprops,yaml]
----
spring:
  mvc:
    static-path-pattern: "/resources/**"
----

You can also customize the static resource locations by using the configprop: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 https://www.webjars.org/[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 configprop:spring.mvc.webjars-path-pattern[] property.

TIP: 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:

[configprops,yaml]
----
spring:
  web:
    resources:
      chain:
        strategy:
          content:
            enabled: true
            paths: "/**"
----

NOTE: Links to resources are rewritten in templates at runtime, thanks to a javadoc:org.springframework.web.servlet.resource.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 javadoc:org.springframework.web.servlet.resource.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:

[configprops,yaml]
----
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 javadoc:org.springframework.boot.autoconfigure.web.WebProperties$Resources[] for more supported options.

[TIP]
====
This feature has been thoroughly described in a dedicated https://spring.io/blog/2014/07/24/spring-framework-4-1-handling-static-web-resources[blog post] and in Spring Framework's {url-spring-framework-docs}/web/webmvc/mvc-config/static-resources.html[reference documentation].
====



[[web.servlet.spring-mvc.welcome-page]]
=== 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 javadoc:org.springframework.web.servlet.HandlerMapping[] beans which is by default the following:

[cols="1,1"]
|===
|`RouterFunctionMapping`
|Endpoints declared with javadoc:org.springframework.web.servlet.function.RouterFunction[] beans

|`RequestMappingHandlerMapping`
|Endpoints declared in javadoc:org.springframework.stereotype.Controller[format=annotation] beans

|`WelcomePageHandlerMapping`
|The welcome page support
|===



[[web.servlet.spring-mvc.favicon]]
=== 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.



[[web.servlet.spring-mvc.content-negotiation]]
=== 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, javadoc:org.springframework.web.bind.annotation.GetMapping[format=annotation] 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 {url-spring-framework-docs}/web/webmvc/mvc-controller/ann-requestmapping.html#mvc-ann-requestmapping-suffix-pattern-match[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")`:

[configprops,yaml]
----
spring:
  mvc:
    contentnegotiation:
      favor-parameter: true
----

Or if you prefer to use a different parameter name:

[configprops,yaml]
----
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:

[configprops,yaml]
----
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 javadoc:org.springframework.web.util.pattern.PathPatternParser[] strategy.
javadoc:org.springframework.web.util.pattern.PathPatternParser[] is an https://spring.io/blog/2020/06/30/url-matching-with-pathpattern-in-spring-mvc[optimized implementation] but comes with some restrictions compared to the javadoc:org.springframework.util.AntPathMatcher[] strategy.
javadoc:org.springframework.web.util.pattern.PathPatternParser[] restricts usage of {url-spring-framework-docs}/web/webmvc/mvc-controller/ann-requestmapping.html#mvc-ann-requestmapping-uri-templates[some path pattern variants].
It is also incompatible with configuring the javadoc:org.springframework.web.servlet.DispatcherServlet[] with a path prefix (configprop:spring.mvc.servlet.path[]).

The strategy can be configured using the configprop:spring.mvc.pathmatch.matching-strategy[] configuration property, as shown in the following example:

[configprops,yaml]
----
spring:
  mvc:
    pathmatch:
      matching-strategy: "ant-path-matcher"
----

Spring MVC will throw a javadoc:org.springframework.web.servlet.NoHandlerFoundException[] if a handler is not found for a request.
Note that, by default, the xref:web/servlet.adoc#web.servlet.spring-mvc.static-content[serving of static content] is mapped to `+/**+` and will, therefore, provide a handler for all requests.
If no static content is available, javadoc:org.springframework.web.servlet.resource.ResourceHttpRequestHandler[] will throw a javadoc:org.springframework.web.servlet.resource.NoResourceFoundException[].
For a javadoc:org.springframework.web.servlet.NoHandlerFoundException[] to be thrown, set configprop:spring.mvc.static-path-pattern[] to a more specific value such as `/resources/**` or set configprop:spring.web.resources.add-mappings[] to `false` to disable serving of static content entirely.



[[web.servlet.spring-mvc.binding-initializer]]
=== ConfigurableWebBindingInitializer

Spring MVC uses a javadoc:org.springframework.web.bind.support.WebBindingInitializer[] to initialize a javadoc:org.springframework.web.bind.WebDataBinder[] for a particular request.
If you create your own javadoc:org.springframework.web.bind.support.ConfigurableWebBindingInitializer[] javadoc:org.springframework.context.annotation.Bean[format=annotation], Spring Boot automatically configures Spring MVC to use it.



[[web.servlet.spring-mvc.template-engines]]
=== 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:

* https://freemarker.apache.org/docs/[FreeMarker]
* https://docs.groovy-lang.org/docs/next/html/documentation/template-engines.html#_the_markuptemplateengine[Groovy]
* https://www.thymeleaf.org[Thymeleaf]
* https://mustache.github.io/[Mustache]

TIP: If possible, JSPs should be avoided.
There are several xref:web/servlet.adoc#web.servlet.embedded-container.jsp-limitations[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`.

TIP: 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.



[[web.servlet.spring-mvc.error-handling]]
=== 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 javadoc:org.springframework.web.servlet.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 xref:appendix:application-properties/index.adoc#appendix.application-properties.web[Web Properties] section of the Appendix.

To replace the default behavior completely, you can implement javadoc:org.springframework.boot.webmvc.error.ErrorController[] and register a bean definition of that type or add a bean of type javadoc:org.springframework.boot.webmvc.error.ErrorAttributes[] to use the existing mechanism but replace the contents.

TIP: The javadoc:org.springframework.boot.webmvc.autoconfigure.error.BasicErrorController[] can be used as a base class for a custom javadoc:org.springframework.boot.webmvc.error.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 javadoc:org.springframework.boot.webmvc.autoconfigure.error.BasicErrorController[], add a public method with a javadoc:org.springframework.web.bind.annotation.RequestMapping[format=annotation] that has a `produces` attribute, and create a bean of your new type.

As of Spring Framework 6.0, {url-spring-framework-docs}/web/webmvc/mvc-ann-rest-exceptions.html[RFC 9457 Problem Details] is supported.
Spring MVC can produce custom error messages with the `application/problem+json` media type, like:

[source,json]
----
{
	"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 configprop:spring.mvc.problemdetails.enabled[] to `true`.

You can also define a class annotated with javadoc:org.springframework.web.bind.annotation.ControllerAdvice[format=annotation] to customize the JSON document to return for a particular controller and/or exception type, as shown in the following example:

include-code::MyControllerAdvice[]

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 javadoc:org.springframework.boot.webmvc.error.ErrorAttributes[] representation.

In some cases, errors handled at the controller level are not recorded by web observations or the xref:actuator/metrics.adoc#actuator.metrics.supported.spring-mvc[metrics infrastructure].
Applications can ensure that such exceptions are recorded with the observations by {url-spring-framework-docs}/integration/observability.html#observability.http-server.servlet[setting the handled exception on the observation context].



[[web.servlet.spring-mvc.error-handling.error-pages]]
==== 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:

[source]
----
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:

[source]
----
src/
 +- main/
     +- java/
     |   + <source code>
     +- resources/
         +- templates/
             +- error/
             |   +- 5xx.ftlh
             +- <other templates>
----

For more complex mappings, you can also add beans that implement the javadoc:org.springframework.boot.webmvc.autoconfigure.error.ErrorViewResolver[] interface, as shown in the following example:

include-code::MyErrorViewResolver[]

You can also use regular Spring MVC features such as {url-spring-framework-docs}/web/webmvc/mvc-servlet/exceptionhandlers.html[`@ExceptionHandler` methods] and {url-spring-framework-docs}/web/webmvc/mvc-controller/ann-advice.html[`@ControllerAdvice`].
The javadoc:org.springframework.boot.webmvc.error.ErrorController[] then picks up any unhandled exceptions.



[[web.servlet.spring-mvc.error-handling.error-pages-without-spring-mvc]]
==== Mapping Error Pages Outside of Spring MVC

For applications that do not use Spring MVC, you can use the javadoc:org.springframework.boot.web.error.ErrorPageRegistrar[] interface to directly register javadoc:org.springframework.boot.web.error.ErrorPage[] instances.
This abstraction works directly with the underlying embedded servlet container and works even if you do not have a Spring MVC javadoc:org.springframework.web.servlet.DispatcherServlet[].

include-code::MyErrorPagesConfiguration[]

NOTE: If you register an javadoc:org.springframework.boot.web.error.ErrorPage[] with a path that ends up being handled by a javadoc:jakarta.servlet.Filter[] (as is common with some non-Spring web frameworks, like Jersey and Wicket), then the javadoc:jakarta.servlet.Filter[] has to be explicitly registered as an `ERROR` dispatcher, as shown in the following example:

include-code::MyFilterConfiguration[]

Note that the default javadoc:org.springframework.boot.web.servlet.FilterRegistrationBean[] does not include the `ERROR` dispatcher type.



[[web.servlet.spring-mvc.error-handling.in-a-war-deployment]]
==== Error Handling in a WAR Deployment

When deployed to a servlet container, Spring Boot uses its error page filter to forward a request with an error status to the appropriate error page.
This is necessary as the servlet specification does not provide an API for registering error pages.
Depending on the container that you are deploying your war file to and the technologies that your application uses, some additional configuration may be required.

The error page filter can only forward the request to the correct error page if the response has not already been committed.
By default, WebSphere Application Server 8.0 and later commits the response upon successful completion of a servlet's service method.
You should disable this behavior by setting `com.ibm.ws.webcontainer.invokeFlushAfterService` to `false`.



[[web.servlet.spring-mvc.cors]]
=== CORS Support

https://en.wikipedia.org/wiki/Cross-origin_resource_sharing[Cross-origin resource sharing] (CORS) is a https://www.w3.org/TR/cors/[W3C specification] implemented by https://caniuse.com/#feat=cors[most browsers] that lets you specify in a flexible way what kind of cross-domain requests are authorized, instead of using some less secure and less powerful approaches such as IFRAME or JSONP.

As of version 4.2, Spring MVC {url-spring-framework-docs}/web/webmvc-cors.html[supports CORS].
Using {url-spring-framework-docs}/web/webmvc-cors.html#mvc-cors-controller[controller method CORS configuration] with javadoc:{url-spring-framework-javadoc}/org.springframework.web.bind.annotation.CrossOrigin[format=annotation] annotations in your Spring Boot application does not require any specific configuration.
{url-spring-framework-docs}/web/webmvc-cors.html#mvc-cors-global[Global CORS configuration] can be defined by registering a javadoc:org.springframework.web.servlet.config.annotation.WebMvcConfigurer[] bean with a customized `addCorsMappings(CorsRegistry)` method, as shown in the following example:

include-code::MyCorsConfiguration[]



[[web.servlet.spring-mvc.api-versioning]]
=== API Versioning

Spring MVC supports API versioning which can be used to evolve an HTTP API over time.
The same `@Controller` path can be mapped multiple times to support different versions of the API.

For more details see {url-spring-framework-docs}/web/webmvc/mvc-controller/ann-requestmapping.html#mvc-ann-requestmapping-version[Spring Framework's reference documentation].

Once mappings have been added, you additionally need to configure Spring MVC so that it is able to use any version information sent with a request.
Typically, versions are sent as HTTP headers, query parameters, media type parameters, or as part of the path.

To configure Spring MVC, you can either use a javadoc:org.springframework.web.servlet.config.annotation.WebMvcConfigurer[] bean and override the `configureApiVersioning(...)` method, or you can use properties.

For example, the following will use an `X-Version` HTTP header to obtain version information and default to `1.0.0` when no header is sent.

[configprops,yaml]
----
spring:
  mvc:
    apiversion:
      default: 1.0.0
      use:
        header: X-Version
----

NOTE: If your setup requires multiple strategies, such as header and query parameter, consider declaring the order programmatically by overriding the `configureApiVersioning` method.

For more complete control, you can also define javadoc:org.springframework.web.accept.ApiVersionResolver[], javadoc:org.springframework.web.accept.ApiVersionParser[] and javadoc:org.springframework.web.accept.ApiVersionDeprecationHandler[] beans which will be injected into the auto-configured Spring MVC configuration.

TIP: API versioning is also supported with both `WebClient` and `RestClient`.
See xref:io/rest-client.adoc#io.rest-client.apiversioning[] for details.



[[web.servlet.jersey]]
== JAX-RS and Jersey

If you prefer the JAX-RS programming model for REST endpoints, you can use one of the available implementations instead of Spring MVC.
https://jersey.github.io/[Jersey] and https://cxf.apache.org/[Apache CXF] work quite well out of the box.
CXF requires you to register its javadoc:jakarta.servlet.Servlet[] or javadoc:jakarta.servlet.Filter[] as a javadoc:org.springframework.context.annotation.Bean[format=annotation] in your application context.
Jersey has some native Spring support, so we also provide auto-configuration support for it in Spring Boot, together with a starter.

To get started with Jersey, include the `spring-boot-starter-jersey` as a dependency and then you need one javadoc:org.springframework.context.annotation.Bean[format=annotation] of type javadoc:org.glassfish.jersey.server.ResourceConfig[] in which you register all the endpoints, as shown in the following example:

include-code::MyJerseyConfig[]

WARNING: Jersey's support for scanning executable archives is rather limited.
For example, it cannot scan for endpoints in a package found in a xref:how-to:deployment/installing.adoc[fully executable jar file] or in `WEB-INF/classes` when running an executable war file.
To avoid this limitation, the `packages` method should not be used, and endpoints should be registered individually by using the `register` method, as shown in the preceding example.

For more advanced customizations, you can also register an arbitrary number of beans that implement javadoc:org.springframework.boot.jersey.autoconfigure.ResourceConfigCustomizer[].

All the registered endpoints should be a javadoc:org.springframework.stereotype.Component[format=annotation] with HTTP resource annotations (`@GET` and others), as shown in the following example:

include-code::MyEndpoint[]

Since the javadoc:org.springframework.boot.actuate.endpoint.annotation.Endpoint[format=annotation] is a Spring javadoc:org.springframework.stereotype.Component[format=annotation], its lifecycle is managed by Spring and you can use the javadoc:org.springframework.beans.factory.annotation.Autowired[format=annotation] annotation to inject dependencies and use the javadoc:org.springframework.beans.factory.annotation.Value[format=annotation] annotation to inject external configuration.
By default, the Jersey servlet is registered and mapped to `/*`.
You can change the mapping by adding javadoc:jakarta.ws.rs.ApplicationPath[format=annotation] to your javadoc:org.glassfish.jersey.server.ResourceConfig[].

By default, Jersey is set up as a servlet in a javadoc:org.springframework.context.annotation.Bean[format=annotation] of type javadoc:org.springframework.boot.web.servlet.ServletRegistrationBean[] named `jerseyServletRegistration`.
By default, the servlet is initialized lazily, but you can customize that behavior by setting `spring.jersey.servlet.load-on-startup`.
You can disable or override that bean by creating one of your own with the same name.
You can also use a filter instead of a servlet by setting `spring.jersey.type=filter` (in which case, the javadoc:org.springframework.context.annotation.Bean[format=annotation] to replace or override is `jerseyFilterRegistration`).
The filter has an javadoc:org.springframework.core.annotation.Order[format=annotation], which you can set with `spring.jersey.filter.order`.
When using Jersey as a filter, a servlet that will handle any requests that are not intercepted by Jersey must be present.
If your application does not contain such a servlet, you may want to enable the default servlet by setting configprop:server.servlet.register-default-servlet[] to `true`.
Both the servlet and the filter registrations can be given init parameters by using `spring.jersey.init.*` to specify a map of properties.



[[web.servlet.embedded-container]]
== Embedded Servlet Container Support

For servlet application, Spring Boot includes support for embedded https://tomcat.apache.org/[Tomcat] and https://www.eclipse.org/jetty/[Jetty] servers.
Most developers use the appropriate starter to obtain a fully configured instance.
By default, the embedded server listens for HTTP requests on port `8080`.



[[web.servlet.embedded-container.servlets-filters-listeners]]
=== Servlets, Filters, and Listeners

When using an embedded servlet container, you can register servlets, filters, and all the listeners (such as javadoc:jakarta.servlet.http.HttpSessionListener[]) from the servlet spec, either by using Spring beans or by scanning for servlet components.



[[web.servlet.embedded-container.servlets-filters-listeners.beans]]
==== Registering Servlets, Filters, and Listeners as Spring Beans

Any javadoc:jakarta.servlet.Servlet[], javadoc:jakarta.servlet.Filter[], or servlet `*Listener` instance that is a Spring bean is registered with the embedded container.
This can be particularly convenient if you want to refer to a value from your `application.properties` during configuration.

By default, if the context contains only a single Servlet, it is mapped to `/`.
In the case of multiple servlet beans, the bean name is used as a path prefix.
Filters map to `+/*+`.

If convention-based mapping is not flexible enough, you can use the javadoc:org.springframework.boot.web.servlet.ServletRegistrationBean[], javadoc:org.springframework.boot.web.servlet.FilterRegistrationBean[], and javadoc:org.springframework.boot.web.servlet.ServletListenerRegistrationBean[] classes for complete control.
If you prefer annotations over javadoc:org.springframework.boot.web.servlet.ServletRegistrationBean[] and javadoc:org.springframework.boot.web.servlet.FilterRegistrationBean[], you can also use javadoc:org.springframework.boot.web.servlet.ServletRegistration[format=annotation] and
javadoc:org.springframework.boot.web.servlet.FilterRegistration[format=annotation] as an alternative.

It is usually safe to leave filter beans unordered.
If a specific order is required, you should annotate the javadoc:jakarta.servlet.Filter[] with javadoc:org.springframework.core.annotation.Order[format=annotation] or make it implement javadoc:org.springframework.core.Ordered[].
You cannot configure the order of a javadoc:jakarta.servlet.Filter[] by annotating its bean method with javadoc:org.springframework.core.annotation.Order[format=annotation].
If you cannot change the javadoc:jakarta.servlet.Filter[] class to add javadoc:org.springframework.core.annotation.Order[format=annotation] or implement javadoc:org.springframework.core.Ordered[], you must define a javadoc:org.springframework.boot.web.servlet.FilterRegistrationBean[] for the javadoc:jakarta.servlet.Filter[] and set the registration bean's order using the `setOrder(int)` method.
Or, if you prefer annotations, you can also use javadoc:org.springframework.boot.web.servlet.FilterRegistration[format=annotation] and set the `order` attribute.
Avoid configuring a filter that reads the request body at `Ordered.HIGHEST_PRECEDENCE`, since it might go against the character encoding configuration of your application.
If a servlet filter wraps the request, it should be configured with an order that is less than or equal to `OrderedFilter.REQUEST_WRAPPER_FILTER_MAX_ORDER`.

TIP: To see the order of every javadoc:jakarta.servlet.Filter[] in your application, enable debug level logging for the `web` xref:features/logging.adoc#features.logging.log-groups[logging group] (`logging.level.web=debug`).
Details of the registered filters, including their order and URL patterns, will then be logged at startup.

WARNING: Take care when registering javadoc:jakarta.servlet.Filter[] beans since they are initialized very early in the application lifecycle.
If you need to register a javadoc:jakarta.servlet.Filter[] that interacts with other beans, consider using a javadoc:org.springframework.boot.web.servlet.DelegatingFilterProxyRegistrationBean[] instead.



[[web.servlet.embedded-container.context-initializer]]
=== Servlet Context Initialization

Embedded servlet containers do not directly execute the javadoc:jakarta.servlet.ServletContainerInitializer[] interface or Spring's javadoc:org.springframework.web.WebApplicationInitializer[] interface.
This is an intentional design decision intended to reduce the risk that third party libraries designed to run inside a war may break Spring Boot applications.

If you need to perform servlet context initialization in a Spring Boot application, you should register a bean that implements the javadoc:org.springframework.boot.web.servlet.ServletContextInitializer[] interface.
The single `onStartup` method provides access to the javadoc:jakarta.servlet.ServletContext[] and, if necessary, can easily be used as an adapter to an existing javadoc:org.springframework.web.WebApplicationInitializer[].



[[web.servlet.embedded-container.context-initializer.init-parameters]]
==== Init Parameters

Init parameters can be configured on the javadoc:jakarta.servlet.ServletContext[] using `server.servlet.context-parameters.*` properties.
For example, the property `server.servlet.context-parameters.com.example.parameter=example` will configure a `ServletContext` init parameter named `com.example.parameter` with the value `example`.



[[web.servlet.embedded-container.context-initializer.scanning]]
==== Scanning for Servlets, Filters, and listeners

When using an embedded container, automatic registration of classes annotated with javadoc:jakarta.servlet.annotation.WebServlet[format=annotation], javadoc:jakarta.servlet.annotation.WebFilter[format=annotation], and javadoc:jakarta.servlet.annotation.WebListener[format=annotation] can be enabled by using javadoc:org.springframework.boot.web.server.servlet.context.ServletComponentScan[format=annotation].

TIP: javadoc:org.springframework.boot.web.server.servlet.context.ServletComponentScan[format=annotation] has no effect in a standalone container, where the container's built-in discovery mechanisms are used instead.



[[web.servlet.embedded-container.application-context]]
=== The ServletWebServerApplicationContext

Under the hood, Spring Boot uses a different type of javadoc:org.springframework.context.ApplicationContext[] for embedded servlet container support.
The javadoc:org.springframework.boot.web.server.servlet.context.ServletWebServerApplicationContext[] is a special type of javadoc:org.springframework.web.context.WebApplicationContext[] that bootstraps itself by searching for a single javadoc:org.springframework.boot.web.server.servlet.ServletWebServerFactory[] bean.
Usually a javadoc:org.springframework.boot.tomcat.servlet.TomcatServletWebServerFactory[], or javadoc:org.springframework.boot.jetty.servlet.JettyServletWebServerFactory[] has been auto-configured.

NOTE: You usually do not need to be aware of these implementation classes.
Most applications are auto-configured, and the appropriate javadoc:org.springframework.context.ApplicationContext[] and javadoc:org.springframework.boot.web.server.servlet.ServletWebServerFactory[] are created on your behalf.

In an embedded container setup, the javadoc:jakarta.servlet.ServletContext[] is set as part of server startup which happens during application context initialization.
Because of this beans in the javadoc:org.springframework.context.ApplicationContext[] cannot be reliably initialized with a javadoc:jakarta.servlet.ServletContext[].
One way to get around this is to inject javadoc:org.springframework.context.ApplicationContext[] as a dependency of the bean and access the javadoc:jakarta.servlet.ServletContext[] only when it is needed.
Another way is to use a callback once the server has started.
This can be done using an javadoc:org.springframework.context.ApplicationListener[] which listens for the javadoc:org.springframework.boot.context.event.ApplicationStartedEvent[] as follows:

include-code::MyDemoBean[]



[[web.servlet.embedded-container.customizing]]
=== Customizing Embedded Servlet Containers

Common servlet container settings can be configured by using Spring javadoc:org.springframework.core.env.Environment[] properties.
Usually, you would define the properties in your `application.properties` or `application.yaml` file.

Common server settings include:

* Network settings: Listen port for incoming HTTP requests (`server.port`), interface address to bind to (`server.address`), and so on.
* Session settings: Whether the session is persistent (`server.servlet.session.persistent`), session timeout (`server.servlet.session.timeout`), location of session data (`server.servlet.session.store-dir`), and session-cookie configuration (`server.servlet.session.cookie.*`).
* Error management: Location of the error page (configprop:spring.web.error.path[]) and so on.
* xref:how-to:webserver.adoc#howto.webserver.configure-ssl[SSL]
* xref:how-to:webserver.adoc#howto.webserver.enable-response-compression[HTTP compression]

Spring Boot tries as much as possible to expose common settings, but this is not always possible.
For those cases, dedicated namespaces offer server-specific customizations (see `server.tomcat`).
For instance, xref:how-to:webserver.adoc#howto.webserver.configure-access-logs[access logs] can be configured with specific features of the embedded servlet container.

TIP: See the javadoc:org.springframework.boot.web.server.autoconfigure.ServerProperties[] class for a complete list.



[[web.servlet.embedded-container.customizing.samesite]]
==== SameSite Cookies

The `SameSite` cookie attribute can be used by web browsers to control if and how cookies are submitted in cross-site requests.
The attribute is particularly relevant for modern web browsers which have started to change the default value that is used when the attribute is missing.

If you want to change the `SameSite` attribute of your session cookie, you can use the configprop:server.servlet.session.cookie.same-site[] property.
This property is supported by auto-configured Tomcat and Jetty servers.
It is also used to configure Spring Session servlet based javadoc:org.springframework.session.SessionRepository[] beans.

For example, if you want your session cookie to have a `SameSite` attribute of `None`, you can add the following to your `application.properties` or `application.yaml` file:

[configprops,yaml]
----
server:
  servlet:
    session:
      cookie:
        same-site: "none"
----

If you want to change the `SameSite` attribute on other cookies added to your javadoc:jakarta.servlet.http.HttpServletResponse[], you can use a javadoc:org.springframework.boot.web.server.servlet.CookieSameSiteSupplier[].
The javadoc:org.springframework.boot.web.server.servlet.CookieSameSiteSupplier[] is passed a javadoc:jakarta.servlet.http.Cookie[] and may return a `SameSite` value, or `null`.

There are a number of convenience factory and filter methods that you can use to quickly match specific cookies.
For example, adding the following bean will automatically apply a `SameSite` of `Lax` for all cookies with a name that matches the regular expression `myapp.*`.

include-code::MySameSiteConfiguration[]



[[web.servlet.embedded-container.customizing.encoding]]
==== Character Encoding

The character encoding behavior of the embedded servlet container for request and response handling can be configured using the `server.servlet.encoding.*` configuration properties.

When a request's `Accept-Language` header indicates a locale for the request it will be automatically mapped to a charset by the servlet container.
Each container provides default locale to charset mappings and you should verify that they meet your application's needs.
When they do not, use the configprop:server.servlet.encoding.mapping[] configuration property to customize the mappings, as shown in the following example:

[configprops,yaml]
----
server:
  servlet:
    encoding:
      mapping:
        ko: "UTF-8"
----

In the preceding example, the `ko` (Korean) locale has been mapped to `UTF-8`.
This is equivalent to a `<locale-encoding-mapping-list>` entry in a `web.xml` file of a traditional war deployment.



[[web.servlet.embedded-container.customizing.programmatic]]
==== Programmatic Customization

If you need to programmatically configure your embedded servlet container, you can register a Spring bean that implements the javadoc:org.springframework.boot.web.server.WebServerFactoryCustomizer[] interface.
javadoc:org.springframework.boot.web.server.WebServerFactoryCustomizer[] provides access to the javadoc:org.springframework.boot.web.server.servlet.ConfigurableServletWebServerFactory[], which includes numerous customization setter methods.
The following example shows programmatically setting the port:

include-code::MyWebServerFactoryCustomizer[]

javadoc:org.springframework.boot.tomcat.servlet.TomcatServletWebServerFactory[], and javadoc:org.springframework.boot.jetty.servlet.JettyServletWebServerFactory[] are dedicated variants of javadoc:org.springframework.boot.web.server.servlet.ConfigurableServletWebServerFactory[] that have additional customization setter methods for Tomcat, and Jetty respectively.
The following example shows how to customize javadoc:org.springframework.boot.tomcat.servlet.TomcatServletWebServerFactory[] that provides access to Tomcat-specific configuration options:

include-code::MyTomcatWebServerFactoryCustomizer[]



[[web.servlet.embedded-container.customizing.direct]]
==== Customizing ConfigurableServletWebServerFactory Directly

For more advanced use cases that require you to extend from javadoc:org.springframework.boot.web.server.servlet.ServletWebServerFactory[], you can expose a bean of such type yourself.

Setters are provided for many configuration options.
Several protected method "`hooks`" are also provided should you need to do something more exotic.
See the javadoc:org.springframework.boot.web.server.servlet.ConfigurableServletWebServerFactory[] API documentation for details.

NOTE: Auto-configured customizers are still applied on your custom factory, so use that option carefully.



[[web.servlet.embedded-container.jsp-limitations]]
=== JSP Limitations

When running a Spring Boot application that uses an embedded servlet container (and is packaged as an executable archive), there are some limitations in the JSP support.

* With Jetty and Tomcat, it should work if you use war packaging.
An executable war will work when launched with `java -jar`, and will also be deployable to any standard container.
JSPs are not supported when using an executable jar.

* Creating a custom `error.jsp` page does not override the default view for xref:web/servlet.adoc#web.servlet.spring-mvc.error-handling[error handling].
  xref:web/servlet.adoc#web.servlet.spring-mvc.error-handling.error-pages[Custom error pages] should be used instead.

* If you run your application using `mvn spring-boot:run` or `gradle bootRun` and you deviate from the standard `src/main/webapp` directory structure you may need to set a `WAR_SOURCE_DIRECTORY` environment variable so that Spring Boot can find your JSPs.
