Часто при работе с микросервисами, построенными с помощью технологии Spring Boot, можно видеть стандартный вывод ошибок подобный этому:
{
"timestamp": 1510417124782,
"status": 500,
"error": "Internal Server Error",
"exception": "com.netflix.hystrix.exception.HystrixRuntimeException",
"message": "ApplicationRepository#save(Application) failed and no fallback available.",
"path": "/application"
}
Такой вывод может быть излишним и ненужным клиентам вашего сервиса. Если вы хотите упростить жизнь сторонним сервисам в случае ошибки, то как раз об этом и пойдет речь в данном посте.
Начнем мы с построения небольшого сервиса с одним контроллером. Наш сервис будет принимать запрос на получение пользователя и в случае успеха отдавать данные по пользователю. В случае провала к нам возвращается ошибка. Начнем с простого и далее в статье будем усовершенствовать проект.
Итак, первое, что нам понадобится, это пользователь:
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private int id;
private String firstName;
private String lastName;
}
Здесь я использовал библиотеку lombok. Аннотация Data подставляет геттеры и сеттеры в класс. Остальные аннотации добавляют пустой конструктор и конструктор с параметрами. Если вы хотите повторить данный пример у себя в IntelliJ Idea, то вам необходимо поставить галочку в пункте enable annotation processing, либо написать все руками.
Далее нам понадобится сервис (для краткости репозиторий создавать не будем):
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
@Service
public class UserService {
private static final Map<Integer, User> userStorage
= new HashMap<>();
static {
userStorage.put(1, new User(1, "Petr", "Petrov"));
userStorage.put(2, new User(2, "Ivan", "Ivanov"));
userStorage.put(3, new User(3, "Sergei", "Sidorov"));
}
public User get(int id) {
return userStorage.get(id);
}
}
Ну и, конечно, сам контроллер:
import org.springframework.beans.factory.annotation.Autowired;
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("user")
public class UserController {
private UserService userService;
@Autowired
public UserController(UserService userService) {
this.userService = userService;
}
@GetMapping("{id}")
public User get(@PathVariable(name = "id") int id) {
return userService.get(id);
}
}
Итак, у нас есть почти полноценный сервис с пользователями. Запускаем его и смотрим.
При запросе на URL localhost:8080/user/1 нам возвращается json в таком формате:
{
"id": 1,
"firstName": "Petr",
"lastName": "Petrov"
}
Все отлично. Но что будет, если сделать запрос на URL localhost:8080/user/4 (у нас всего 3 пользователя)? Правильный ответ: мы получим статус 200 и ничего в ответе. Ситуация не особо приятная. Ошибки нет, но и запрашиваемого объекта тоже нет.
Давайте улучшим наш сервис и добавим в него выбрасывание ошибки в случае неудачи. Для начала создадим исключение:
public class ThereIsNoSuchUserException extends RuntimeException { }
Теперь добавим пробрасывание ошибки в сервис:
public User get(int id) {
User user = userStorage.get(id);
if (user == null) {
throw new ThereIsNoSuchUserException();
}
return user;
}
Сделаем перезапуск сервиса и снова посмотрим, что будет при запросе несуществующего пользователя:
{
"timestamp": 1510479979781,
"status": 500,
"error": "Internal Server Error",
"exception": "org.faoxis.habrexception.ThereIsNoSuchUserException",
"message": "No message available",
"path": "/user/4"
}
Это уже лучше. Гораздо более информативно и код статуса не 200. Такую ситуацию клиент на своей стороне уже сможет успешно и легко обработать. Но, как говорится, есть один нюанс. Ошибки могут быть совершенно разными, и клиенту нашего сервиса придется ставить кучу условных операторов и исследовать, что у нас пошло не так и как это можно поправить. Получается немного грубо с нашей стороны.
Как раз для таких случаев и была придумана аннотация ResponseStatus. Подставим ее на место нашего исключения и на практике посмотрим, как это работает:
@ResponseStatus(code = HttpStatus.NOT_FOUND, reason = "There is no such user")
public class ThereIsNoSuchUserException extends RuntimeException {
}
Повторим запрос и посмотрим результат:
{
"timestamp": 1510480307384,
"status": 404,
"error": "Not Found",
"exception": "org.faoxis.habrexception.ThereIsNoSuchUserException",
"message": "There is no such user",
"path": "/user/4"
}
Отлично! Код статуса и сообщение поменялись. Теперь клиент сможет определись по коду ответа причину ошибки и даже уточнить ее по полю message. Но все же есть проблема. Большинство полей клиенту могут быть просто не нужны. Например, код ответа как отдельное поле может быть излишним, поскольку мы его и так получаем с кодом ответа. С этим нужно что-то делать.
К счастью, со spring boot сделать последний шаг к нашему успешному оповещению об ошибке не так сложно.
Все, что для этого требуется, разобрать пару аннотаций и один класс:
- Аннотация ExceptionHandler. Используется для обработки собственных и каких-то специфичных исключений. Далее в примере будет понятно, что это значит. На всякий случай ссылка на документацию.
- Аннотация ControllerAdvice. Данная аннотация дает «совет» группе констроллеров по определенным событиям. В нашем случае — это обработка ошибок. По умолчанию применяется ко всем контроллерам, но в параметрах можно указать отпределенную группу. Подбронее тут.
- Класс ResponseEntityExceptionHandler. Данный класс занимается обработкой ошибок. У него куча методов, название которых построенно по принципу handle + название исключения. Если мы хотим обработать какое-то базовое исключение, то наследуемся от этого класса и переопределяем нужный метод.
Давайте теперь посмотрим, как все это обЪединить и построить наше уникальное и неповторимое сообщение об ошибке:
import lombok.AllArgsConstructor;
import lombok.Data;
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.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
@ControllerAdvice
public class AwesomeExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(ThereIsNoSuchUserException.class)
protected ResponseEntity<AwesomeException> handleThereIsNoSuchUserException() {
return new ResponseEntity<>(new AwesomeException("There is no such user"), HttpStatus.NOT_FOUND);
}
@Data
@AllArgsConstructor
private static class AwesomeException {
private String message;
}
}
Сделаем все тот же запрос и увидим статус ответа 404 и наше сообщение с единственным полем:
{
"message": "There is no such user"
}
Аннотацию ResponseStatus над нашим исключением можно смело убирать.
В итоге у нас получилось приложение, в котором обработка ошибок настраивается максимально гибко и просто. Полный проект можно найти в репозитории github. Надеюсь, что все было просто и понятно. Спасибо за внимание и пишите комментарии! Буду рад вашим замечаниям и уточнениям!
Currently the error response from spring boot contains the standard content like below:
{
"timestamp" : 1426615606,
"exception" : "org.springframework.web.bind.MissingServletRequestParameterException",
"status" : 400,
"error" : "Bad Request",
"path" : "/welcome",
"message" : "Required String parameter 'name' is not present"
}
I am looking for a way to get rid of the «exception» property in the response. Is there a way to achieve this?
asked Mar 17, 2015 at 18:08
As described in the documentation on error handling, you can provide your own bean that implements ErrorAttributes
to take control of the content.
An easy way to do that is to subclass DefaultErrorAttributes
. For example:
@Bean
public ErrorAttributes errorAttributes() {
return new DefaultErrorAttributes() {
@Override
public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace) {
Map<String, Object> errorAttributes = super.getErrorAttributes(requestAttributes, includeStackTrace);
// Customize the default entries in errorAttributes to suit your needs
return errorAttributes;
}
};
}
answered Mar 17, 2015 at 21:10
Andy WilkinsonAndy Wilkinson
104k24 gold badges247 silver badges237 bronze badges
4
If there is empty message text in json when you encounter exception, you can be hit by changed behavior in spring boot 2.3.0. If this is the case, just change your server.error.include-message
property to always
.
answered May 5, 2020 at 10:36
LuboLubo
1,48012 silver badges31 bronze badges
1
Following answer is totally derived from Andy Wilkinson’s answer (which uses web.reactive
classes)
— It includes web.servlet
based classes.
— Spring boot 2.2.4.RELEASE
ExceptionHandlerConfig.java
package com.example.sample.core.exception;
import java.util.LinkedHashMap;
import java.util.Map;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.WebRequest;
@Configuration
public class ExceptionHandlerConfig {
//private static final String DEFAULT_KEY_TIMESTAMP = "timestamp";
private static final String DEFAULT_KEY_STATUS = "status";
private static final String DEFAULT_KEY_ERROR = "error";
private static final String DEFAULT_KEY_ERRORS = "errors";
private static final String DEFAULT_KEY_MESSAGE = "message";
//private static final String DEFAULT_KEY_PATH = "path";
public static final String KEY_STATUS = "status";
public static final String KEY_ERROR = "error";
public static final String KEY_MESSAGE = "message";
public static final String KEY_TIMESTAMP = "timestamp";
public static final String KEY_ERRORS = "errors";
//
@Bean
public ErrorAttributes errorAttributes() {
return new DefaultErrorAttributes() {
@Override
public Map<String ,Object> getErrorAttributes(
WebRequest webRequest
,boolean includeStackTrace
) {
Map<String ,Object> defaultMap
= super.getErrorAttributes( webRequest ,includeStackTrace );
Map<String ,Object> errorAttributes = new LinkedHashMap<>();
// Customize.
// For eg: Only add the keys you want.
errorAttributes.put( KEY_STATUS, defaultMap.get( DEFAULT_KEY_STATUS ) );
errorAttributes.put( KEY_MESSAGE ,defaultMap.get( DEFAULT_KEY_MESSAGE ) );
return errorAttributes;
}
};
}
}
answered Mar 10, 2020 at 11:53
Vinay VisshVinay Vissh
4572 gold badges10 silver badges12 bronze badges
Editor’s note: This article was updated on September 5, 2022, by our editorial team. It has been modified to include recent sources and to align with our current editorial standards.
The ability to handle errors correctly in APIs while providing meaningful error messages is a desirable feature, as it can help the API client respond to issues. The default behavior returns stack traces that are hard to understand and ultimately useless for the API client. Partitioning the error information into fields enables the API client to parse it and provide better error messages to the user. In this article, we cover how to implement proper Spring Boot exception handling when building a REST API .
Building REST APIs with Spring became the standard approach for Java developers. Using Spring Boot helps substantially, as it removes a lot of boilerplate code and enables auto-configuration of various components. We assume that you’re familiar with the basics of API development with those technologies. If you are unsure about how to develop a basic REST API, you should start with this article about Spring MVC or this article about building a Spring REST Service.
Making Error Responses Clearer
We’ll use the source code hosted on GitHub as an example application that implements a REST API for retrieving objects that represent birds. It has the features described in this article and a few more examples of error handling scenarios. Here’s a summary of endpoints implemented in that application:
GET /birds/{birdId} |
Gets information about a bird and throws an exception if not found. |
GET /birds/noexception/{birdId} |
This call also gets information about a bird, except it doesn’t throw an exception when a bird doesn’t exist with that ID. |
POST /birds |
Creates a bird. |
The Spring framework MVC module has excellent features for error handling. But it is left to the developer to use those features to treat the exceptions and return meaningful responses to the API client.
Let’s look at an example of the default Spring Boot answer when we issue an HTTP POST to the /birds
endpoint with the following JSON object that has the string “aaa” on the field “mass,” which should be expecting an integer:
{
"scientificName": "Common blackbird",
"specie": "Turdus merula",
"mass": "aaa",
"length": 4
}
The Spring Boot default answer, without proper error handling, looks like this:
{
"timestamp": 1658551020,
"status": 400,
"error": "Bad Request",
"exception": "org.springframework.http.converter.HttpMessageNotReadableException",
"message": "JSON parse error: Unrecognized token 'three': was expecting ('true', 'false' or 'null'); nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'aaa': was expecting ('true', 'false' or 'null')n at [Source: java.io.PushbackInputStream@cba7ebc; line: 4, column: 17]",
"path": "/birds"
}
The Spring Boot DefaultErrorAttributes
-generated response has some good fields, but it is too focused on the exception. The timestamp
field is an integer that doesn’t carry information about its measurement unit. The exception
field is only valuable to Java developers, and the message leaves the API consumer lost in implementation details that are irrelevant to them. What if there were more details we could extract from the exception? Let’s learn how to handle exceptions in Spring Boot properly and wrap them into a better JSON representation to make life easier for our API clients.
As we’ll be using Java date and time classes, we first need to add a Maven dependency for the Jackson JSR310 converters. They convert Java date and time classes to JSON representation using the @JsonFormat
annotation:
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
Next, let’s define a class for representing API errors. We’ll create a class called ApiError
with enough fields to hold relevant information about errors during REST calls:
class ApiError {
private HttpStatus status;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy hh:mm:ss")
private LocalDateTime timestamp;
private String message;
private String debugMessage;
private List<ApiSubError> subErrors;
private ApiError() {
timestamp = LocalDateTime.now();
}
ApiError(HttpStatus status) {
this();
this.status = status;
}
ApiError(HttpStatus status, Throwable ex) {
this();
this.status = status;
this.message = "Unexpected error";
this.debugMessage = ex.getLocalizedMessage();
}
ApiError(HttpStatus status, String message, Throwable ex) {
this();
this.status = status;
this.message = message;
this.debugMessage = ex.getLocalizedMessage();
}
}
-
The
status
property holds the operation call status, which will be anything from 4xx to signal client errors or 5xx to signal server errors. A typical scenario is an HTTP code 400: BAD_REQUEST when the client, for example, sends an improperly formatted field, like an invalid email address. -
The
timestamp
property holds the date-time instance when the error happened. -
The
message
property holds a user-friendly message about the error. -
The
debugMessage
property holds a system message describing the error in detail. -
The
subErrors
property holds an array of suberrors when there are multiple errors in a single call. An example would be numerous validation errors in which multiple fields have failed. TheApiSubError
class encapsulates this information:
abstract class ApiSubError {
}
@Data
@EqualsAndHashCode(callSuper = false)
@AllArgsConstructor
class ApiValidationError extends ApiSubError {
private String object;
private String field;
private Object rejectedValue;
private String message;
ApiValidationError(String object, String message) {
this.object = object;
this.message = message;
}
}
The ApiValidationError
is a class that extends ApiSubError
and expresses validation problems encountered during the REST call.
Below, you’ll see examples of JSON responses generated after implementing these improvements.
Here is a JSON example returned for a missing entity while calling endpoint GET /birds/2
:
{
"apierror": {
"status": "NOT_FOUND",
"timestamp": "22-07-2022 06:20:19",
"message": "Bird was not found for parameters {id=2}"
}
}
Here is another example of JSON returned when issuing a POST /birds
call with an invalid value for the bird’s mass:
{
"apierror": {
"status": "BAD_REQUEST",
"timestamp": "22-07-2022 06:49:25",
"message": "Validation errors",
"subErrors": [
{
"object": "bird",
"field": "mass",
"rejectedValue": 999999,
"message": "must be less or equal to 104000"
}
]
}
}
Spring Boot Error Handler
Let’s explore some Spring annotations used to handle exceptions.
RestController
is the base annotation for classes that handle REST operations.
ExceptionHandler
is a Spring annotation that provides a mechanism to treat exceptions thrown during execution of handlers (controller operations). This annotation, if used on methods of controller classes, will serve as the entry point for handling exceptions thrown within this controller only.
Altogether, the most common implementation is to use @ExceptionHandler
on methods of @ControllerAdvice
classes so that the Spring Boot exception handling will be applied globally or to a subset of controllers.
ControllerAdvice
is an annotation in Spring and, as the name suggests, is “advice” for multiple controllers. It enables the application of a single ExceptionHandler
to multiple controllers. With this annotation, we can define how to treat such an exception in a single place, and the system will call this handler for thrown exceptions on classes covered by this ControllerAdvice
.
The subset of controllers affected can be defined by using the following selectors on @ControllerAdvice
: annotations()
, basePackageClasses()
, and basePackages()
. ControllerAdvice
is applied globally to all controllers if no selectors are provided
By using @ExceptionHandler
and @ControllerAdvice
, we’ll be able to define a central point for treating exceptions and wrapping them in an ApiError
object with better organization than is possible with the default Spring Boot error-handling mechanism.
Handling Exceptions
Next, we’ll create the class that will handle the exceptions. For simplicity, we call it RestExceptionHandler
, which must extend from Spring Boot’s ResponseEntityExceptionHandler
. We’ll be extending ResponseEntityExceptionHandler
, as it already provides some basic handling of Spring MVC exceptions. We’ll add handlers for new exceptions while improving the existing ones.
Overriding Exceptions Handled in ResponseEntityExceptionHandler
If you take a look at the source code of ResponseEntityExceptionHandler
, you’ll see a lot of methods called handle******()
, like handleHttpMessageNotReadable()
or handleHttpMessageNotWritable()
. Let’s see how can we extend handleHttpMessageNotReadable()
to handle HttpMessageNotReadableException
exceptions. We just have to override the method handleHttpMessageNotReadable()
in our RestExceptionHandler
class:
@Order(Ordered.HIGHEST_PRECEDENCE)
@ControllerAdvice
public class RestExceptionHandler extends ResponseEntityExceptionHandler {
@Override
protected ResponseEntity<Object> handleHttpMessageNotReadable(HttpMessageNotReadableException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
String error = "Malformed JSON request";
return buildResponseEntity(new ApiError(HttpStatus.BAD_REQUEST, error, ex));
}
private ResponseEntity<Object> buildResponseEntity(ApiError apiError) {
return new ResponseEntity<>(apiError, apiError.getStatus());
}
//other exception handlers below
}
We have declared that in case of a thrownHttpMessageNotReadableException
, the error message will be “Malformed JSON request” and the error will be encapsulated in the ApiError
object. Below, we can see the answer of a REST call with this new method overridden:
{
"apierror": {
"status": "BAD_REQUEST",
"timestamp": "22-07-2022 03:53:39",
"message": "Malformed JSON request",
"debugMessage": "JSON parse error: Unrecognized token 'aaa': was expecting ('true', 'false' or 'null'); nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'aaa': was expecting ('true', 'false' or 'null')n at [Source: java.io.PushbackInputStream@7b5e8d8a; line: 4, column: 17]"
}
}
Implementing Custom Exceptions
Next, we’ll create a method that handles an exception not yet declared inside Spring Boot’s ResponseEntityExceptionHandler
.
A common scenario for a Spring application that handles database calls is to provide a method that returns a record by its ID using a repository class. But if we look into the CrudRepository.findOne()
method, we’ll see that it returns null
for an unknown object. If our service calls this method and returns directly to the controller, we’ll get an HTTP code 200 (OK) even if the resource isn’t found. In fact, the proper approach is to return a HTTP code 404 (NOT FOUND) as specified in the HTTP/1.1 spec.
We’ll create a custom exception called EntityNotFoundException
to handle this case. This one is different from javax.persistence.EntityNotFoundException
, as it provides some constructors that ease the object creation, and one may choose to handle the javax.persistence
exception differently.
That said, let’s create an ExceptionHandler
for this newly created EntityNotFoundException
in our RestExceptionHandler
class. Create a method called handleEntityNotFound()
and annotate it with @ExceptionHandler
, passing the class object EntityNotFoundException.class
to it. This declaration signalizes Spring that every time EntityNotFoundException
is thrown, Spring should call this method to handle it.
When annotating a method with @ExceptionHandler
, a wide range of auto-injected parameters like WebRequest
, Locale
, and others may be specified as described here. We’ll provide the exception EntityNotFoundException
as a parameter for this handleEntityNotFound
method:
@Order(Ordered.HIGHEST_PRECEDENCE)
@ControllerAdvice
public class RestExceptionHandler extends ResponseEntityExceptionHandler {
//other exception handlers
@ExceptionHandler(EntityNotFoundException.class)
protected ResponseEntity<Object> handleEntityNotFound(
EntityNotFoundException ex) {
ApiError apiError = new ApiError(NOT_FOUND);
apiError.setMessage(ex.getMessage());
return buildResponseEntity(apiError);
}
}
Great! In the handleEntityNotFound()
method, we set the HTTP status code to NOT_FOUND
and usethe new exception message. Here is what the response for the GET /birds/2
endpoint looks like now:
{
"apierror": {
"status": "NOT_FOUND",
"timestamp": "22-07-2022 04:02:22",
"message": "Bird was not found for parameters {id=2}"
}
}
The Importance of Spring Boot Exception Handling
It is important to control exception handling so we can properly map exceptions to the ApiError
object and inform API clients appropriately. Additionally, we would need to create more handler methods (the ones with @ExceptionHandler) for thrown exceptions within the application code. The GitHub code provides more more examples for other common exceptions like MethodArgumentTypeMismatchException
, ConstraintViolationException
.
Here are some additional resources that helped in the composition of this article:
-
Error Handling for REST With Spring
-
Exception Handling in Spring MVC
Further Reading on the Toptal Engineering Blog:
- Top 10 Most Common Spring Framework Mistakes
- Spring Security with JWT for REST API
- Using Spring Boot for OAuth2 and JWT REST Protection
- Building an MVC Application With Spring Framework: A Beginner’s Tutorial
- Spring Batch Tutorial: Batch Processing Made Easy with Spring
Understanding the basics
-
Why should the API have a uniform error format?
A uniform error format allows an API client to parse error objects. A more complex error could implement the ApiSubError class and provide more details about the problem so the client can know which actions to take.
-
How does Spring know which ExceptionHandler to use?
The Spring MVC class, ExceptionHandlerExceptionResolver, performs most of the work in its doResolveHandlerMethodException() method.
-
What information is important to provide to API consumers?
Usually, it is helpful to include the error origination, the input parameters, and some guidance on how to fix the failing call.
Spring Web MVC is the original web framework built on the Servlet API and has been included
in the Spring Framework from the very beginning. The formal name, «Spring Web MVC,»
comes from the name of its source module
(spring-webmvc
),
but it is more commonly known as «Spring MVC».
Parallel to Spring Web MVC, Spring Framework 5.0 introduced a reactive-stack web framework
whose name, «Spring WebFlux,» is also based on its source module
(spring-webflux
).
This chapter covers Spring Web MVC. The next chapter
covers Spring WebFlux.
For baseline information and compatibility with Servlet container and Jakarta EE version
ranges, see the Spring Framework
Wiki.
1.1. DispatcherServlet
Spring MVC, as many other web frameworks, is designed around the front controller
pattern where a central Servlet
, the DispatcherServlet
, provides a shared algorithm
for request processing, while actual work is performed by configurable delegate components.
This model is flexible and supports diverse workflows.
The DispatcherServlet
, as any Servlet
, needs to be declared and mapped according
to the Servlet specification by using Java configuration or in web.xml
.
In turn, the DispatcherServlet
uses Spring configuration to discover
the delegate components it needs for request mapping, view resolution, exception
handling, and more.
The following example of the Java configuration registers and initializes
the DispatcherServlet
, which is auto-detected by the Servlet container
(see Servlet Config):
Java
public class MyWebApplicationInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) {
// Load Spring web application configuration
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.register(AppConfig.class);
// Create and register the DispatcherServlet
DispatcherServlet servlet = new DispatcherServlet(context);
ServletRegistration.Dynamic registration = servletContext.addServlet("app", servlet);
registration.setLoadOnStartup(1);
registration.addMapping("/app/*");
}
}
Kotlin
class MyWebApplicationInitializer : WebApplicationInitializer {
override fun onStartup(servletContext: ServletContext) {
// Load Spring web application configuration
val context = AnnotationConfigWebApplicationContext()
context.register(AppConfig::class.java)
// Create and register the DispatcherServlet
val servlet = DispatcherServlet(context)
val registration = servletContext.addServlet("app", servlet)
registration.setLoadOnStartup(1)
registration.addMapping("/app/*")
}
}
In addition to using the ServletContext API directly, you can also extendAbstractAnnotationConfigDispatcherServletInitializer and override specific methods(see the example under Context Hierarchy). |
For programmatic use cases, a GenericWebApplicationContext can be used as analternative to AnnotationConfigWebApplicationContext . See theGenericWebApplicationContext javadoc for details. |
The following example of web.xml
configuration registers and initializes the DispatcherServlet
:
<web-app>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/app-context.xml</param-value>
</context-param>
<servlet>
<servlet-name>app</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value></param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>app</servlet-name>
<url-pattern>/app/*</url-pattern>
</servlet-mapping>
</web-app>
Spring Boot follows a different initialization sequence. Rather than hooking into the lifecycle of the Servlet container, Spring Boot uses Spring configuration to bootstrap itself and the embedded Servlet container. Filter and Servlet declarationsare detected in Spring configuration and registered with the Servlet container. For more details, see the Spring Boot documentation. |
1.1.1. Context Hierarchy
DispatcherServlet
expects a WebApplicationContext
(an extension of a plain
ApplicationContext
) for its own configuration. WebApplicationContext
has a link to the
ServletContext
and the Servlet
with which it is associated. It is also bound to the ServletContext
such that applications can use static methods on RequestContextUtils
to look up the
WebApplicationContext
if they need access to it.
For many applications, having a single WebApplicationContext
is simple and suffices.
It is also possible to have a context hierarchy where one root WebApplicationContext
is shared across multiple DispatcherServlet
(or other Servlet
) instances, each with
its own child WebApplicationContext
configuration.
See Additional Capabilities of the ApplicationContext
for more on the context hierarchy feature.
The root WebApplicationContext
typically contains infrastructure beans, such as data repositories and
business services that need to be shared across multiple Servlet
instances. Those beans
are effectively inherited and can be overridden (that is, re-declared) in the Servlet-specific
child WebApplicationContext
, which typically contains beans local to the given Servlet
.
The following image shows this relationship:
The following example configures a WebApplicationContext
hierarchy:
Java
public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[] { RootConfig.class };
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] { App1Config.class };
}
@Override
protected String[] getServletMappings() {
return new String[] { "/app1/*" };
}
}
Kotlin
class MyWebAppInitializer : AbstractAnnotationConfigDispatcherServletInitializer() {
override fun getRootConfigClasses(): Array<Class<*>> {
return arrayOf(RootConfig::class.java)
}
override fun getServletConfigClasses(): Array<Class<*>> {
return arrayOf(App1Config::class.java)
}
override fun getServletMappings(): Array<String> {
return arrayOf("/app1/*")
}
}
If an application context hierarchy is not required, applications can return all configuration through getRootConfigClasses() and null from getServletConfigClasses() .
|
The following example shows the web.xml
equivalent:
<web-app>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/root-context.xml</param-value>
</context-param>
<servlet>
<servlet-name>app1</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/app1-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>app1</servlet-name>
<url-pattern>/app1/*</url-pattern>
</servlet-mapping>
</web-app>
If an application context hierarchy is not required, applications may configure a “root” context only and leave the contextConfigLocation Servlet parameter empty.
|
1.1.2. Special Bean Types
The DispatcherServlet
delegates to special beans to process requests and render the
appropriate responses. By “special beans” we mean Spring-managed Object
instances that
implement framework contracts. Those usually come with built-in contracts, but
you can customize their properties and extend or replace them.
The following table lists the special beans detected by the DispatcherServlet
:
Bean type | Explanation |
---|---|
|
Map a request to a handler along with a list of The two main |
|
Help the |
|
Strategy to resolve exceptions, possibly mapping them to handlers, to HTML error |
|
Resolve logical |
|
Resolve the |
|
Resolve themes your web application can use — for example, to offer personalized layouts. |
|
Abstraction for parsing a multi-part request (for example, browser form file upload) with |
|
Store and retrieve the “input” and the “output” |
1.1.3. Web MVC Config
Applications can declare the infrastructure beans listed in Special Bean Types
that are required to process requests. The DispatcherServlet
checks the
WebApplicationContext
for each special bean. If there are no matching bean types,
it falls back on the default types listed in
DispatcherServlet.properties
.
In most cases, the MVC Config is the best starting point. It declares the required
beans in either Java or XML and provides a higher-level configuration callback API to
customize it.
Spring Boot relies on the MVC Java configuration to configure Spring MVC and provides many extra convenient options. |
1.1.4. Servlet Config
In a Servlet environment, you have the option of configuring the Servlet container
programmatically as an alternative or in combination with a web.xml
file.
The following example registers a DispatcherServlet
:
Java
import org.springframework.web.WebApplicationInitializer;
public class MyWebApplicationInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext container) {
XmlWebApplicationContext appContext = new XmlWebApplicationContext();
appContext.setConfigLocation("/WEB-INF/spring/dispatcher-config.xml");
ServletRegistration.Dynamic registration = container.addServlet("dispatcher", new DispatcherServlet(appContext));
registration.setLoadOnStartup(1);
registration.addMapping("/");
}
}
Kotlin
import org.springframework.web.WebApplicationInitializer
class MyWebApplicationInitializer : WebApplicationInitializer {
override fun onStartup(container: ServletContext) {
val appContext = XmlWebApplicationContext()
appContext.setConfigLocation("/WEB-INF/spring/dispatcher-config.xml")
val registration = container.addServlet("dispatcher", DispatcherServlet(appContext))
registration.setLoadOnStartup(1)
registration.addMapping("/")
}
}
WebApplicationInitializer
is an interface provided by Spring MVC that ensures your
implementation is detected and automatically used to initialize any Servlet 3 container.
An abstract base class implementation of WebApplicationInitializer
named
AbstractDispatcherServletInitializer
makes it even easier to register the
DispatcherServlet
by overriding methods to specify the servlet mapping and the
location of the DispatcherServlet
configuration.
This is recommended for applications that use Java-based Spring configuration, as the
following example shows:
Java
public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return null;
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] { MyWebConfig.class };
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
Kotlin
class MyWebAppInitializer : AbstractAnnotationConfigDispatcherServletInitializer() {
override fun getRootConfigClasses(): Array<Class<*>>? {
return null
}
override fun getServletConfigClasses(): Array<Class<*>>? {
return arrayOf(MyWebConfig::class.java)
}
override fun getServletMappings(): Array<String> {
return arrayOf("/")
}
}
If you use XML-based Spring configuration, you should extend directly from
AbstractDispatcherServletInitializer
, as the following example shows:
Java
public class MyWebAppInitializer extends AbstractDispatcherServletInitializer {
@Override
protected WebApplicationContext createRootApplicationContext() {
return null;
}
@Override
protected WebApplicationContext createServletApplicationContext() {
XmlWebApplicationContext cxt = new XmlWebApplicationContext();
cxt.setConfigLocation("/WEB-INF/spring/dispatcher-config.xml");
return cxt;
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
Kotlin
class MyWebAppInitializer : AbstractDispatcherServletInitializer() {
override fun createRootApplicationContext(): WebApplicationContext? {
return null
}
override fun createServletApplicationContext(): WebApplicationContext {
return XmlWebApplicationContext().apply {
setConfigLocation("/WEB-INF/spring/dispatcher-config.xml")
}
}
override fun getServletMappings(): Array<String> {
return arrayOf("/")
}
}
AbstractDispatcherServletInitializer
also provides a convenient way to add Filter
instances and have them be automatically mapped to the DispatcherServlet
, as the
following example shows:
Java
public class MyWebAppInitializer extends AbstractDispatcherServletInitializer {
// ...
@Override
protected Filter[] getServletFilters() {
return new Filter[] {
new HiddenHttpMethodFilter(), new CharacterEncodingFilter() };
}
}
Kotlin
class MyWebAppInitializer : AbstractDispatcherServletInitializer() {
// ...
override fun getServletFilters(): Array<Filter> {
return arrayOf(HiddenHttpMethodFilter(), CharacterEncodingFilter())
}
}
Each filter is added with a default name based on its concrete type and automatically
mapped to the DispatcherServlet
.
The isAsyncSupported
protected method of AbstractDispatcherServletInitializer
provides a single place to enable async support on the DispatcherServlet
and all
filters mapped to it. By default, this flag is set to true
.
Finally, if you need to further customize the DispatcherServlet
itself, you can
override the createDispatcherServlet
method.
1.1.5. Processing
The DispatcherServlet
processes requests as follows:
-
The
WebApplicationContext
is searched for and bound in the request as an attribute
that the controller and other elements in the process can use. It is bound by default
under theDispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE
key. -
The locale resolver is bound to the request to let elements in the process
resolve the locale to use when processing the request (rendering the view, preparing
data, and so on). If you do not need locale resolving, you do not need the locale resolver. -
The theme resolver is bound to the request to let elements such as views determine
which theme to use. If you do not use themes, you can ignore it. -
If you specify a multipart file resolver, the request is inspected for multiparts. If
multiparts are found, the request is wrapped in aMultipartHttpServletRequest
for
further processing by other elements in the process. See Multipart Resolver for further
information about multipart handling. -
An appropriate handler is searched for. If a handler is found, the execution chain
associated with the handler (preprocessors, postprocessors, and controllers) is
run to prepare a model for rendering. Alternatively, for annotated
controllers, the response can be rendered (within theHandlerAdapter
) instead of
returning a view. -
If a model is returned, the view is rendered. If no model is returned (maybe due to
a preprocessor or postprocessor intercepting the request, perhaps for security
reasons), no view is rendered, because the request could already have been fulfilled.
The HandlerExceptionResolver
beans declared in the WebApplicationContext
are used to
resolve exceptions thrown during request processing. Those exception resolvers allow
customizing the logic to address exceptions. See Exceptions for more details.
For HTTP caching support, handlers can use the checkNotModified
methods of WebRequest
,
along with further options for annotated controllers as described in
HTTP Caching for Controllers.
You can customize individual DispatcherServlet
instances by adding Servlet
initialization parameters (init-param
elements) to the Servlet declaration in the
web.xml
file. The following table lists the supported parameters:
Parameter | Explanation |
---|---|
|
Class that implements |
|
String that is passed to the context instance (specified by |
|
Namespace of the |
|
Whether to throw a By default, this is set to Note that, if default servlet handling is |
1.1.6. Path Matching
The Servlet API exposes the full request path as requestURI
and further sub-divides it
into contextPath
, servletPath
, and pathInfo
whose values vary depending on how a
Servlet is mapped. From these inputs, Spring MVC needs to determine the lookup path to
use for mapping handlers, which should exclude the contextPath
and any servletMapping
prefix, if applicable.
The servletPath
and pathInfo
are decoded and that makes them impossible to compare
directly to the full requestURI
in order to derive the lookupPath and that makes it
necessary to decode the requestURI
. However this introduces its own issues because the
path may contain encoded reserved characters such as "/"
or ";"
that can in turn
alter the structure of the path after they are decoded which can also lead to security
issues. In addition, Servlet containers may normalize the servletPath
to varying
degrees which makes it further impossible to perform startsWith
comparisons against
the requestURI
.
This is why it is best to avoid reliance on the servletPath
which comes with the
prefix-based servletPath
mapping type. If the DispatcherServlet
is mapped as the
default Servlet with "/"
or otherwise without a prefix with "/*"
and the Servlet
container is 4.0+ then Spring MVC is able to detect the Servlet mapping type and avoid
use of the servletPath
and pathInfo
altogether. On a 3.1 Servlet container,
assuming the same Servlet mapping types, the equivalent can be achieved by providing
a UrlPathHelper
with alwaysUseFullPath=true
via Path Matching in
the MVC config.
Fortunately the default Servlet mapping "/"
is a good choice. However, there is still
an issue in that the requestURI
needs to be decoded to make it possible to compare to
controller mappings. This is again undesirable because of the potential to decode
reserved characters that alter the path structure. If such characters are not expected,
then you can reject them (like the Spring Security HTTP firewall), or you can configure
UrlPathHelper
with urlDecode=false
but controller mappings will need to match to the
encoded path which may not always work well. Furthermore, sometimes the
DispatcherServlet
needs to share the URL space with another Servlet and may need to
be mapped by prefix.
The above issues are addressed when using PathPatternParser
and parsed patterns, as
an alternative to String path matching with AntPathMatcher
. The PathPatternParser
has
been available for use in Spring MVC from version 5.3, and is enabled by default from
version 6.0. Unlike AntPathMatcher
which needs either the lookup path decoded or the
controller mapping encoded, a parsed PathPattern
matches to a parsed representation
of the path called RequestPath
, one path segment at a time. This allows decoding and
sanitizing path segment values individually without the risk of altering the structure
of the path. Parsed PathPattern
also supports the use of servletPath
prefix mapping
as long as a Servlet path mapping is used and the prefix is kept simple, i.e. it has no
encoded characters. For pattern syntax details and comparison, see
Pattern Comparison.
1.1.7. Interception
All HandlerMapping
implementations support handler interceptors that are useful when
you want to apply specific functionality to certain requests — for example, checking for
a principal. Interceptors must implement HandlerInterceptor
from the
org.springframework.web.servlet
package with three methods that should provide enough
flexibility to do all kinds of pre-processing and post-processing:
-
preHandle(..)
: Before the actual handler is run -
postHandle(..)
: After the handler is run -
afterCompletion(..)
: After the complete request has finished
The preHandle(..)
method returns a boolean value. You can use this method to break or
continue the processing of the execution chain. When this method returns true
, the
handler execution chain continues. When it returns false, the DispatcherServlet
assumes the interceptor itself has taken care of requests (and, for example, rendered an
appropriate view) and does not continue executing the other interceptors and the actual
handler in the execution chain.
See Interceptors in the section on MVC configuration for examples of how to
configure interceptors. You can also register them directly by using setters on individual
HandlerMapping
implementations.
postHandle
method is less useful with @ResponseBody
and ResponseEntity
methods for
which the response is written and committed within the HandlerAdapter
and before
postHandle
. That means it is too late to make any changes to the response, such as adding
an extra header. For such scenarios, you can implement ResponseBodyAdvice
and either
declare it as an Controller Advice bean or configure it directly on
RequestMappingHandlerAdapter
.
1.1.8. Exceptions
If an exception occurs during request mapping or is thrown from a request handler (such as
a @Controller
), the DispatcherServlet
delegates to a chain of HandlerExceptionResolver
beans to resolve the exception and provide alternative handling, which is typically an
error response.
The following table lists the available HandlerExceptionResolver
implementations:
HandlerExceptionResolver |
Description |
---|---|
|
A mapping between exception class names and error view names. Useful for rendering |
|
Resolves exceptions raised by Spring MVC and maps them to HTTP status codes. |
|
Resolves exceptions with the |
|
Resolves exceptions by invoking an |
Chain of Resolvers
You can form an exception resolver chain by declaring multiple HandlerExceptionResolver
beans in your Spring configuration and setting their order
properties as needed.
The higher the order property, the later the exception resolver is positioned.
The contract of HandlerExceptionResolver
specifies that it can return:
-
a
ModelAndView
that points to an error view. -
An empty
ModelAndView
if the exception was handled within the resolver. -
null
if the exception remains unresolved, for subsequent resolvers to try, and, if the
exception remains at the end, it is allowed to bubble up to the Servlet container.
The MVC Config automatically declares built-in resolvers for default Spring MVC
exceptions, for @ResponseStatus
annotated exceptions, and for support of
@ExceptionHandler
methods. You can customize that list or replace it.
Container Error Page
If an exception remains unresolved by any HandlerExceptionResolver
and is, therefore,
left to propagate or if the response status is set to an error status (that is, 4xx, 5xx),
Servlet containers can render a default error page in HTML. To customize the default
error page of the container, you can declare an error page mapping in web.xml
.
The following example shows how to do so:
<error-page>
<location>/error</location>
</error-page>
Given the preceding example, when an exception bubbles up or the response has an error status, the
Servlet container makes an ERROR dispatch within the container to the configured URL
(for example, /error
). This is then processed by the DispatcherServlet
, possibly mapping it
to a @Controller
, which could be implemented to return an error view name with a model
or to render a JSON response, as the following example shows:
Java
@RestController
public class ErrorController {
@RequestMapping(path = "/error")
public Map<String, Object> handle(HttpServletRequest request) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("status", request.getAttribute("jakarta.servlet.error.status_code"));
map.put("reason", request.getAttribute("jakarta.servlet.error.message"));
return map;
}
}
Kotlin
@RestController
class ErrorController {
@RequestMapping(path = ["/error"])
fun handle(request: HttpServletRequest): Map<String, Any> {
val map = HashMap<String, Any>()
map["status"] = request.getAttribute("jakarta.servlet.error.status_code")
map["reason"] = request.getAttribute("jakarta.servlet.error.message")
return map
}
}
The Servlet API does not provide a way to create error page mappings in Java. You can, however, use both a WebApplicationInitializer and a minimal web.xml .
|
1.1.9. View Resolution
Spring MVC defines the ViewResolver
and View
interfaces that let you render
models in a browser without tying you to a specific view technology. ViewResolver
provides a mapping between view names and actual views. View
addresses the preparation
of data before handing over to a specific view technology.
The following table provides more details on the ViewResolver
hierarchy:
ViewResolver | Description |
---|---|
|
Subclasses of |
|
Simple implementation of the |
|
Convenient subclass of |
|
Convenient subclass of |
|
Implementation of the |
|
Implementation of the |
Handling
You can chain view resolvers by declaring more than one resolver bean and, if necessary, by
setting the order
property to specify ordering. Remember, the higher the order property,
the later the view resolver is positioned in the chain.
The contract of a ViewResolver
specifies that it can return null to indicate that the
view could not be found. However, in the case of JSPs and InternalResourceViewResolver
,
the only way to figure out if a JSP exists is to perform a dispatch through
RequestDispatcher
. Therefore, you must always configure an InternalResourceViewResolver
to be last in the overall order of view resolvers.
Configuring view resolution is as simple as adding ViewResolver
beans to your Spring
configuration. The MVC Config provides a dedicated configuration API for
View Resolvers and for adding logic-less
View Controllers which are useful for HTML template
rendering without controller logic.
Redirecting
The special redirect:
prefix in a view name lets you perform a redirect. The
UrlBasedViewResolver
(and its subclasses) recognize this as an instruction that a
redirect is needed. The rest of the view name is the redirect URL.
The net effect is the same as if the controller had returned a RedirectView
, but now
the controller itself can operate in terms of logical view names. A logical view
name (such as redirect:/myapp/some/resource
) redirects relative to the current
Servlet context, while a name such as redirect:https://myhost.com/some/arbitrary/path
redirects to an absolute URL.
Note that, if a controller method is annotated with the @ResponseStatus
, the annotation
value takes precedence over the response status set by RedirectView
.
Forwarding
You can also use a special forward:
prefix for view names that are
ultimately resolved by UrlBasedViewResolver
and subclasses. This creates an
InternalResourceView
, which does a RequestDispatcher.forward()
.
Therefore, this prefix is not useful with InternalResourceViewResolver
and
InternalResourceView
(for JSPs), but it can be helpful if you use another view
technology but still want to force a forward of a resource to be handled by the
Servlet/JSP engine. Note that you may also chain multiple view resolvers, instead.
Content Negotiation
ContentNegotiatingViewResolver
does not resolve views itself but rather delegates
to other view resolvers and selects the view that resembles the representation requested
by the client. The representation can be determined from the Accept
header or from a
query parameter (for example, "/path?format=pdf"
).
The ContentNegotiatingViewResolver
selects an appropriate View
to handle the request
by comparing the request media types with the media type (also known as
Content-Type
) supported by the View
associated with each of its ViewResolvers
. The
first View
in the list that has a compatible Content-Type
returns the representation
to the client. If a compatible view cannot be supplied by the ViewResolver
chain,
the list of views specified through the DefaultViews
property is consulted. This
latter option is appropriate for singleton Views
that can render an appropriate
representation of the current resource regardless of the logical view name. The Accept
header can include wildcards (for example text/*
), in which case a View
whose
Content-Type
is text/xml
is a compatible match.
See View Resolvers under MVC Config for configuration details.
1.1.10. Locale
Most parts of Spring’s architecture support internationalization, as the Spring web
MVC framework does. DispatcherServlet
lets you automatically resolve messages
by using the client’s locale. This is done with LocaleResolver
objects.
When a request comes in, the DispatcherServlet
looks for a locale resolver and, if it
finds one, it tries to use it to set the locale. By using the RequestContext.getLocale()
method, you can always retrieve the locale that was resolved by the locale resolver.
In addition to automatic locale resolution, you can also attach an interceptor to the
handler mapping (see Interception for more information on handler
mapping interceptors) to change the locale under specific circumstances (for example,
based on a parameter in the request).
Locale resolvers and interceptors are defined in the
org.springframework.web.servlet.i18n
package and are configured in your application
context in the normal way. The following selection of locale resolvers is included in
Spring.
-
Time Zone
-
Header Resolver
-
Cookie Resolver
-
Session Resolver
-
Locale Interceptor
Time Zone
In addition to obtaining the client’s locale, it is often useful to know its time zone.
The LocaleContextResolver
interface offers an extension to LocaleResolver
that lets
resolvers provide a richer LocaleContext
, which may include time zone information.
When available, the user’s TimeZone
can be obtained by using the
RequestContext.getTimeZone()
method. Time zone information is automatically used
by any Date/Time Converter
and Formatter
objects that are registered with Spring’s
ConversionService
.
This locale resolver inspects the accept-language
header in the request that was sent
by the client (for example, a web browser). Usually, this header field contains the locale of
the client’s operating system. Note that this resolver does not support time zone
information.
Cookie Resolver
This locale resolver inspects a Cookie
that might exist on the client to see if a
Locale
or TimeZone
is specified. If so, it uses the specified details. By using the
properties of this locale resolver, you can specify the name of the cookie as well as the
maximum age. The following example defines a CookieLocaleResolver
:
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
<property name="cookieName" value="clientlanguage"/>
<!-- in seconds. If set to -1, the cookie is not persisted (deleted when browser shuts down) -->
<property name="cookieMaxAge" value="100000"/>
</bean>
The following table describes the properties CookieLocaleResolver
:
Property | Default | Description |
---|---|---|
|
class name + LOCALE |
The name of the cookie |
|
Servlet container default |
The maximum time a cookie persists on the client. If |
|
/ |
Limits the visibility of the cookie to a certain part of your site. When |
Session Resolver
The SessionLocaleResolver
lets you retrieve Locale
and TimeZone
from the
session that might be associated with the user’s request. In contrast to
CookieLocaleResolver
, this strategy stores locally chosen locale settings in the
Servlet container’s HttpSession
. As a consequence, those settings are temporary
for each session and are, therefore, lost when each session ends.
Note that there is no direct relationship with external session management mechanisms,
such as the Spring Session project. This SessionLocaleResolver
evaluates and
modifies the corresponding HttpSession
attributes against the current HttpServletRequest
.
Locale Interceptor
You can enable changing of locales by adding the LocaleChangeInterceptor
to one of the
HandlerMapping
definitions. It detects a parameter in the request and changes the locale
accordingly, calling the setLocale
method on the LocaleResolver
in the dispatcher’s
application context. The next example shows that calls to all *.view
resources
that contain a parameter named siteLanguage
now changes the locale. So, for example,
a request for the URL, https://www.sf.net/home.view?siteLanguage=nl
, changes the site
language to Dutch. The following example shows how to intercept the locale:
<bean id="localeChangeInterceptor"
class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="siteLanguage"/>
</bean>
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.CookieLocaleResolver"/>
<bean id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="interceptors">
<list>
<ref bean="localeChangeInterceptor"/>
</list>
</property>
<property name="mappings">
<value>/**/*.view=someController</value>
</property>
</bean>
1.1.11. Themes
You can apply Spring Web MVC framework themes to set the overall look-and-feel of your
application, thereby enhancing user experience. A theme is a collection of static
resources, typically style sheets and images, that affect the visual style of the
application.
as of 6.0 support for themes has been deprecated theme in favor of using CSS, and without any special support on the server side. |
Defining a theme
To use themes in your web application, you must set up an implementation of the
org.springframework.ui.context.ThemeSource
interface. The WebApplicationContext
interface extends ThemeSource
but delegates its responsibilities to a dedicated
implementation. By default, the delegate is an
org.springframework.ui.context.support.ResourceBundleThemeSource
implementation that
loads properties files from the root of the classpath. To use a custom ThemeSource
implementation or to configure the base name prefix of the ResourceBundleThemeSource
,
you can register a bean in the application context with the reserved name, themeSource
.
The web application context automatically detects a bean with that name and uses it.
When you use the ResourceBundleThemeSource
, a theme is defined in a simple properties
file. The properties file lists the resources that make up the theme, as the following example shows:
styleSheet=/themes/cool/style.css background=/themes/cool/img/coolBg.jpg
The keys of the properties are the names that refer to the themed elements from view
code. For a JSP, you typically do this using the spring:theme
custom tag, which is
very similar to the spring:message
tag. The following JSP fragment uses the theme
defined in the previous example to customize the look and feel:
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<html>
<head>
<link rel="stylesheet" href="<spring:theme code='styleSheet'/>" type="text/css"/>
</head>
<body style="background=<spring:theme code='background'/>">
...
</body>
</html>
By default, the ResourceBundleThemeSource
uses an empty base name prefix. As a result,
the properties files are loaded from the root of the classpath. Thus, you would put the
cool.properties
theme definition in a directory at the root of the classpath (for
example, in /WEB-INF/classes
). The ResourceBundleThemeSource
uses the standard Java
resource bundle loading mechanism, allowing for full internationalization of themes. For
example, we could have a /WEB-INF/classes/cool_nl.properties
that references a special
background image with Dutch text on it.
Resolving Themes
After you define themes, as described in the preceding section,
you decide which theme to use. The DispatcherServlet
looks for a bean named themeResolver
to find out which ThemeResolver
implementation to use. A theme resolver works in much the same
way as a LocaleResolver
. It detects the theme to use for a particular request and can also
alter the request’s theme. The following table describes the theme resolvers provided by Spring:
Class | Description |
---|---|
|
Selects a fixed theme, set by using the |
|
The theme is maintained in the user’s HTTP session. It needs to be set only once for |
|
The selected theme is stored in a cookie on the client. |
Spring also provides a ThemeChangeInterceptor
that lets theme changes on every
request with a simple request parameter.
1.1.12. Multipart Resolver
MultipartResolver
from the org.springframework.web.multipart
package is a strategy
for parsing multipart requests including file uploads. There is a container-based
StandardServletMultipartResolver
implementation for Servlet multipart request parsing.
Note that the outdated CommonsMultipartResolver
based on Apache Commons FileUpload is
not available anymore, as of Spring Framework 6.0 with its new Servlet 5.0+ baseline.
To enable multipart handling, you need to declare a MultipartResolver
bean in your
DispatcherServlet
Spring configuration with a name of multipartResolver
.
The DispatcherServlet
detects it and applies it to the incoming request. When a POST
with a content type of multipart/form-data
is received, the resolver parses the
content wraps the current HttpServletRequest
as a MultipartHttpServletRequest
to
provide access to resolved files in addition to exposing parts as request parameters.
Servlet Multipart Parsing
Servlet multipart parsing needs to be enabled through Servlet container configuration.
To do so:
-
In Java, set a
MultipartConfigElement
on the Servlet registration. -
In
web.xml
, add a"<multipart-config>"
section to the servlet declaration.
The following example shows how to set a MultipartConfigElement
on the Servlet registration:
Java
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
// ...
@Override
protected void customizeRegistration(ServletRegistration.Dynamic registration) {
// Optionally also set maxFileSize, maxRequestSize, fileSizeThreshold
registration.setMultipartConfig(new MultipartConfigElement("/tmp"));
}
}
Kotlin
class AppInitializer : AbstractAnnotationConfigDispatcherServletInitializer() {
// ...
override fun customizeRegistration(registration: ServletRegistration.Dynamic) {
// Optionally also set maxFileSize, maxRequestSize, fileSizeThreshold
registration.setMultipartConfig(MultipartConfigElement("/tmp"))
}
}
Once the Servlet multipart configuration is in place, you can add a bean of type
StandardServletMultipartResolver
with a name of multipartResolver
.
This resolver variant uses your Servlet container’s multipart parser as-is, |
1.1.13. Logging
DEBUG-level logging in Spring MVC is designed to be compact, minimal, and
human-friendly. It focuses on high-value bits of information that are useful over and
over again versus others that are useful only when debugging a specific issue.
TRACE-level logging generally follows the same principles as DEBUG (and, for example, also
should not be a fire hose) but can be used for debugging any issue. In addition, some log
messages may show a different level of detail at TRACE versus DEBUG.
Good logging comes from the experience of using the logs. If you spot anything that does
not meet the stated goals, please let us know.
Sensitive Data
DEBUG and TRACE logging may log sensitive information. This is why request parameters and
headers are masked by default and their logging in full must be enabled explicitly
through the enableLoggingRequestDetails
property on DispatcherServlet
.
The following example shows how to do so by using Java configuration:
Java
public class MyInitializer
extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return ... ;
}
@Override
protected Class<?>[] getServletConfigClasses() {
return ... ;
}
@Override
protected String[] getServletMappings() {
return ... ;
}
@Override
protected void customizeRegistration(ServletRegistration.Dynamic registration) {
registration.setInitParameter("enableLoggingRequestDetails", "true");
}
}
Kotlin
class MyInitializer : AbstractAnnotationConfigDispatcherServletInitializer() {
override fun getRootConfigClasses(): Array<Class<*>>? {
return ...
}
override fun getServletConfigClasses(): Array<Class<*>>? {
return ...
}
override fun getServletMappings(): Array<String> {
return ...
}
override fun customizeRegistration(registration: ServletRegistration.Dynamic) {
registration.setInitParameter("enableLoggingRequestDetails", "true")
}
}
1.2. Filters
The spring-web
module provides some useful filters:
-
Form Data
-
Forwarded Headers
-
Shallow ETag
-
CORS
1.2.1. Form Data
Browsers can submit form data only through HTTP GET or HTTP POST but non-browser clients can also
use HTTP PUT, PATCH, and DELETE. The Servlet API requires ServletRequest.getParameter*()
methods to support form field access only for HTTP POST.
The spring-web
module provides FormContentFilter
to intercept HTTP PUT, PATCH, and DELETE
requests with a content type of application/x-www-form-urlencoded
, read the form data from
the body of the request, and wrap the ServletRequest
to make the form data
available through the ServletRequest.getParameter*()
family of methods.
As a request goes through proxies (such as load balancers) the host, port, and
scheme may change, and that makes it a challenge to create links that point to the correct
host, port, and scheme from a client perspective.
RFC 7239 defines the Forwarded
HTTP header
that proxies can use to provide information about the original request. There are other
non-standard headers, too, including X-Forwarded-Host
, X-Forwarded-Port
,
X-Forwarded-Proto
, X-Forwarded-Ssl
, and X-Forwarded-Prefix
.
ForwardedHeaderFilter
is a Servlet filter that modifies the request in order to
a) change the host, port, and scheme based on Forwarded
headers, and b) to remove those
headers to eliminate further impact. The filter relies on wrapping the request, and
therefore it must be ordered ahead of other filters, such as RequestContextFilter
, that
should work with the modified and not the original request.
There are security considerations for forwarded headers since an application cannot know
if the headers were added by a proxy, as intended, or by a malicious client. This is why
a proxy at the boundary of trust should be configured to remove untrusted Forwarded
headers that come from the outside. You can also configure the ForwardedHeaderFilter
with removeOnly=true
, in which case it removes but does not use the headers.
In order to support asynchronous requests and error dispatches this
filter should be mapped with DispatcherType.ASYNC
and also DispatcherType.ERROR
.
If using Spring Framework’s AbstractAnnotationConfigDispatcherServletInitializer
(see Servlet Config) all filters are automatically registered for all dispatch
types. However if registering the filter via web.xml
or in Spring Boot via a
FilterRegistrationBean
be sure to include DispatcherType.ASYNC
and
DispatcherType.ERROR
in addition to DispatcherType.REQUEST
.
1.2.3. Shallow ETag
The ShallowEtagHeaderFilter
filter creates a “shallow” ETag by caching the content
written to the response and computing an MD5 hash from it. The next time a client sends,
it does the same, but it also compares the computed value against the If-None-Match
request header and, if the two are equal, returns a 304 (NOT_MODIFIED).
This strategy saves network bandwidth but not CPU, as the full response must be computed
for each request. Other strategies at the controller level, described earlier, can avoid
the computation. See HTTP Caching.
This filter has a writeWeakETag
parameter that configures the filter to write weak ETags
similar to the following: W/"02a2d595e6ed9a0b24f027f2b63b134d6"
(as defined in
RFC 7232 Section 2.3).
In order to support asynchronous requests this filter must be mapped
with DispatcherType.ASYNC
so that the filter can delay and successfully generate an
ETag to the end of the last async dispatch. If using Spring Framework’s
AbstractAnnotationConfigDispatcherServletInitializer
(see Servlet Config)
all filters are automatically registered for all dispatch types. However if registering
the filter via web.xml
or in Spring Boot via a FilterRegistrationBean
be sure to include
DispatcherType.ASYNC
.
1.2.4. CORS
Spring MVC provides fine-grained support for CORS configuration through annotations on
controllers. However, when used with Spring Security, we advise relying on the built-in
CorsFilter
that must be ordered ahead of Spring Security’s chain of filters.
See the sections on CORS and the CORS Filter for more details.
1.3. Annotated Controllers
Spring MVC provides an annotation-based programming model where @Controller
and
@RestController
components use annotations to express request mappings, request input,
exception handling, and more. Annotated controllers have flexible method signatures and
do not have to extend base classes nor implement specific interfaces.
The following example shows a controller defined by annotations:
Java
@Controller
public class HelloController {
@GetMapping("/hello")
public String handle(Model model) {
model.addAttribute("message", "Hello World!");
return "index";
}
}
Kotlin
import org.springframework.ui.set
@Controller
class HelloController {
@GetMapping("/hello")
fun handle(model: Model): String {
model["message"] = "Hello World!"
return "index"
}
}
In the preceding example, the method accepts a Model
and returns a view name as a String
,
but many other options exist and are explained later in this chapter.
Guides and tutorials on spring.io use the annotation-based programming model described in this section. |
1.3.1. Declaration
You can define controller beans by using a standard Spring bean definition in the
Servlet’s WebApplicationContext
. The @Controller
stereotype allows for auto-detection,
aligned with Spring general support for detecting @Component
classes in the classpath
and auto-registering bean definitions for them. It also acts as a stereotype for the
annotated class, indicating its role as a web component.
To enable auto-detection of such @Controller
beans, you can add component scanning to
your Java configuration, as the following example shows:
Java
@Configuration
@ComponentScan("org.example.web")
public class WebConfig {
// ...
}
Kotlin
@Configuration
@ComponentScan("org.example.web")
class WebConfig {
// ...
}
The following example shows the XML configuration equivalent of the preceding example:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="org.example.web"/>
<!-- ... -->
</beans>
@RestController
is a composed annotation that is
itself meta-annotated with @Controller
and @ResponseBody
to indicate a controller whose
every method inherits the type-level @ResponseBody
annotation and, therefore, writes
directly to the response body versus view resolution and rendering with an HTML template.
AOP Proxies
In some cases, you may need to decorate a controller with an AOP proxy at runtime.
One example is if you choose to have @Transactional
annotations directly on the
controller. When this is the case, for controllers specifically, we recommend
using class-based proxying. This is automatically the case with such annotations
directly on the controller.
If the controller implements an interface, and needs AOP proxying, you may need to
explicitly configure class-based proxying. For example, with @EnableTransactionManagement
you can change to @EnableTransactionManagement(proxyTargetClass = true)
, and with
<tx:annotation-driven/>
you can change to <tx:annotation-driven proxy-target-class="true"/>
.
Keep in mind that as of 6.0, with interface proxying, Spring MVC no longer detects controllers based solely on a type-level @RequestMapping annotation on the interface.Please, enable class based proxying, or otherwise the interface must also have an @Controller annotation.
|
1.3.2. Request Mapping
You can use the @RequestMapping
annotation to map requests to controllers methods. It has
various attributes to match by URL, HTTP method, request parameters, headers, and media
types. You can use it at the class level to express shared mappings or at the method level
to narrow down to a specific endpoint mapping.
There are also HTTP method specific shortcut variants of @RequestMapping
:
-
@GetMapping
-
@PostMapping
-
@PutMapping
-
@DeleteMapping
-
@PatchMapping
The shortcuts are Custom Annotations that are provided because,
arguably, most controller methods should be mapped to a specific HTTP method versus
using @RequestMapping
, which, by default, matches to all HTTP methods.
A @RequestMapping
is still needed at the class level to express shared mappings.
The following example has type and method level mappings:
Java
@RestController
@RequestMapping("/persons")
class PersonController {
@GetMapping("/{id}")
public Person getPerson(@PathVariable Long id) {
// ...
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public void add(@RequestBody Person person) {
// ...
}
}
Kotlin
@RestController
@RequestMapping("/persons")
class PersonController {
@GetMapping("/{id}")
fun getPerson(@PathVariable id: Long): Person {
// ...
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
fun add(@RequestBody person: Person) {
// ...
}
}
URI patterns
@RequestMapping
methods can be mapped using URL patterns. There are two alternatives:
-
PathPattern
— a pre-parsed pattern matched against the URL path also pre-parsed as
PathContainer
. Designed for web use, this solution deals effectively with encoding and
path parameters, and matches efficiently. -
AntPathMatcher
— match String patterns against a String path. This is the original
solution also used in Spring configuration to select resources on the classpath, on the
filesystem, and other locations. It is less efficient and the String path input is a
challenge for dealing effectively with encoding and other issues with URLs.
PathPattern
is the recommended solution for web applications and it is the only choice in
Spring WebFlux. It was enabled for use in Spring MVC from version 5.3 and is enabled by
default from version 6.0. See MVC config for
customizations of path matching options.
PathPattern
supports the same pattern syntax as AntPathMatcher
. In addition, it also
supports the capturing pattern, e.g. {*spring}
, for matching 0 or more path segments
at the end of a path. PathPattern
also restricts the use of **
for matching multiple
path segments such that it’s only allowed at the end of a pattern. This eliminates many
cases of ambiguity when choosing the best matching pattern for a given request.
For full pattern syntax please refer to
PathPattern and
AntPathMatcher.
Some example patterns:
-
"/resources/ima?e.png"
— match one character in a path segment -
"/resources/*.png"
— match zero or more characters in a path segment -
"/resources/**"
— match multiple path segments -
"/projects/{project}/versions"
— match a path segment and capture it as a variable -
"/projects/{project:[a-z]+}/versions"
— match and capture a variable with a regex
Captured URI variables can be accessed with @PathVariable
. For example:
Java
@GetMapping("/owners/{ownerId}/pets/{petId}")
public Pet findPet(@PathVariable Long ownerId, @PathVariable Long petId) {
// ...
}
Kotlin
@GetMapping("/owners/{ownerId}/pets/{petId}")
fun findPet(@PathVariable ownerId: Long, @PathVariable petId: Long): Pet {
// ...
}
You can declare URI variables at the class and method levels, as the following example shows:
Java
@Controller
@RequestMapping("/owners/{ownerId}")
public class OwnerController {
@GetMapping("/pets/{petId}")
public Pet findPet(@PathVariable Long ownerId, @PathVariable Long petId) {
// ...
}
}
Kotlin
@Controller
@RequestMapping("/owners/{ownerId}")
class OwnerController {
@GetMapping("/pets/{petId}")
fun findPet(@PathVariable ownerId: Long, @PathVariable petId: Long): Pet {
// ...
}
}
URI variables are automatically converted to the appropriate type, or TypeMismatchException
is raised. Simple types (int
, long
, Date
, and so on) are supported by default and you can
register support for any other data type.
See Type Conversion and DataBinder
.
You can explicitly name URI variables (for example, @PathVariable("customId")
), but you can
leave that detail out if the names are the same and your code is compiled with the -parameters
compiler flag.
The syntax {varName:regex}
declares a URI variable with a regular expression that has
syntax of {varName:regex}
. For example, given URL "/spring-web-3.0.5.jar"
, the following method
extracts the name, version, and file extension:
Java
@GetMapping("/{name:[a-z-]+}-{version:\d\.\d\.\d}{ext:\.[a-z]+}")
public void handle(@PathVariable String name, @PathVariable String version, @PathVariable String ext) {
// ...
}
Kotlin
@GetMapping("/{name:[a-z-]+}-{version:\d\.\d\.\d}{ext:\.[a-z]+}")
fun handle(@PathVariable name: String, @PathVariable version: String, @PathVariable ext: String) {
// ...
}
URI path patterns can also have embedded ${…}
placeholders that are resolved on startup
by using PropertySourcesPlaceholderConfigurer
against local, system, environment, and
other property sources. You can use this, for example, to parameterize a base URL based on
some external configuration.
Pattern Comparison
When multiple patterns match a URL, the best match must be selected. This is done with
one of the following depending on whether use of parsed PathPattern
is enabled for use or not:
-
PathPattern.SPECIFICITY_COMPARATOR
-
AntPathMatcher.getPatternComparator(String path)
Both help to sort patterns with more specific ones on top. A pattern is less specific if
it has a lower count of URI variables (counted as 1), single wildcards (counted as 1),
and double wildcards (counted as 2). Given an equal score, the longer pattern is chosen.
Given the same score and length, the pattern with more URI variables than wildcards is
chosen.
The default mapping pattern (/**
) is excluded from scoring and always
sorted last. Also, prefix patterns (such as /public/**
) are considered less
specific than other pattern that do not have double wildcards.
For the full details, follow the above links to the pattern Comparators.
Suffix Match
Starting in 5.3, by default Spring MVC no longer performs .*
suffix pattern
matching where a controller mapped to /person
is also implicitly mapped to
/person.*
. As a consequence path extensions are no longer used to interpret
the requested content type for the response — for example, /person.pdf
, /person.xml
,
and so on.
Using file extensions in this way was necessary when browsers used to send Accept
headers
that were hard to interpret consistently. At present, that is no longer a necessity and
using the Accept
header should be the preferred choice.
Over time, the use of file name extensions has proven problematic in a variety of ways.
It can cause ambiguity when overlain with the use of URI variables, path parameters, and
URI encoding. Reasoning about URL-based authorization
and security (see next section for more details) also becomes more difficult.
To completely disable the use of path extensions in versions prior to 5.3, set the following:
-
useSuffixPatternMatching(false)
, see PathMatchConfigurer -
favorPathExtension(false)
, see ContentNegotiationConfigurer
Having a way to request content types other than through the "Accept"
header can still
be useful, e.g. when typing a URL in a browser. A safe alternative to path extensions is
to use the query parameter strategy. If you must use file extensions, consider restricting
them to a list of explicitly registered extensions through the mediaTypes
property of
ContentNegotiationConfigurer.
Suffix Match and RFD
A reflected file download (RFD) attack is similar to XSS in that it relies on request input
(for example, a query parameter and a URI variable) being reflected in the response. However, instead of
inserting JavaScript into HTML, an RFD attack relies on the browser switching to perform a
download and treating the response as an executable script when double-clicked later.
In Spring MVC, @ResponseBody
and ResponseEntity
methods are at risk, because
they can render different content types, which clients can request through URL path extensions.
Disabling suffix pattern matching and using path extensions for content negotiation
lower the risk but are not sufficient to prevent RFD attacks.
To prevent RFD attacks, prior to rendering the response body, Spring MVC adds a
Content-Disposition:inline;filename=f.txt
header to suggest a fixed and safe download
file. This is done only if the URL path contains a file extension that is neither
allowed as safe nor explicitly registered for content negotiation. However, it can
potentially have side effects when URLs are typed directly into a browser.
Many common path extensions are allowed as safe by default. Applications with custom
HttpMessageConverter
implementations can explicitly register file extensions for content
negotiation to avoid having a Content-Disposition
header added for those extensions.
See Content Types.
See CVE-2015-5211 for additional
recommendations related to RFD.
Consumable Media Types
You can narrow the request mapping based on the Content-Type
of the request,
as the following example shows:
Java
@PostMapping(path = "/pets", consumes = "application/json") (1)
public void addPet(@RequestBody Pet pet) {
// ...
}
1 | Using a consumes attribute to narrow the mapping by the content type. |
Kotlin
@PostMapping("/pets", consumes = ["application/json"]) (1)
fun addPet(@RequestBody pet: Pet) {
// ...
}
1 | Using a consumes attribute to narrow the mapping by the content type. |
The consumes
attribute also supports negation expressions — for example, !text/plain
means any
content type other than text/plain
.
You can declare a shared consumes
attribute at the class level. Unlike most other
request-mapping attributes, however, when used at the class level, a method-level consumes
attribute
overrides rather than extends the class-level declaration.
MediaType provides constants for commonly used media types, such asAPPLICATION_JSON_VALUE and APPLICATION_XML_VALUE .
|
Producible Media Types
You can narrow the request mapping based on the Accept
request header and the list of
content types that a controller method produces, as the following example shows:
Java
@GetMapping(path = "/pets/{petId}", produces = "application/json") (1)
@ResponseBody
public Pet getPet(@PathVariable String petId) {
// ...
}
1 | Using a produces attribute to narrow the mapping by the content type. |
Kotlin
@GetMapping("/pets/{petId}", produces = ["application/json"]) (1)
@ResponseBody
fun getPet(@PathVariable petId: String): Pet {
// ...
}
1 | Using a produces attribute to narrow the mapping by the content type. |
The media type can specify a character set. Negated expressions are supported — for example,
!text/plain
means any content type other than «text/plain».
You can declare a shared produces
attribute at the class level. Unlike most other
request-mapping attributes, however, when used at the class level, a method-level produces
attribute
overrides rather than extends the class-level declaration.
MediaType provides constants for commonly used media types, such asAPPLICATION_JSON_VALUE and APPLICATION_XML_VALUE .
|
Parameters, headers
You can narrow request mappings based on request parameter conditions. You can test for the
presence of a request parameter (myParam
), for the absence of one (!myParam
), or for a
specific value (myParam=myValue
). The following example shows how to test for a specific value:
Java
@GetMapping(path = "/pets/{petId}", params = "myParam=myValue") (1)
public void findPet(@PathVariable String petId) {
// ...
}
1 | Testing whether myParam equals myValue . |
Kotlin
@GetMapping("/pets/{petId}", params = ["myParam=myValue"]) (1)
fun findPet(@PathVariable petId: String) {
// ...
}
1 | Testing whether myParam equals myValue . |
You can also use the same with request header conditions, as the following example shows:
Java
@GetMapping(path = "/pets", headers = "myHeader=myValue") (1)
public void findPet(@PathVariable String petId) {
// ...
}
1 | Testing whether myHeader equals myValue . |
Kotlin
@GetMapping("/pets", headers = ["myHeader=myValue"]) (1)
fun findPet(@PathVariable petId: String) {
// ...
}
1 | Testing whether myHeader equals myValue . |
You can match Content-Type and Accept with the headers condition, but it is better to useconsumes and produces instead. |
HTTP HEAD, OPTIONS
@GetMapping
(and @RequestMapping(method=HttpMethod.GET)
) support HTTP HEAD
transparently for request mapping. Controller methods do not need to change.
A response wrapper, applied in jakarta.servlet.http.HttpServlet
, ensures a Content-Length
header is set to the number of bytes written (without actually writing to the response).
@GetMapping
(and @RequestMapping(method=HttpMethod.GET)
) are implicitly mapped to
and support HTTP HEAD. An HTTP HEAD request is processed as if it were HTTP GET except
that, instead of writing the body, the number of bytes are counted and the Content-Length
header is set.
By default, HTTP OPTIONS is handled by setting the Allow
response header to the list of HTTP
methods listed in all @RequestMapping
methods that have matching URL patterns.
For a @RequestMapping
without HTTP method declarations, the Allow
header is set to
GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS
. Controller methods should always declare the
supported HTTP methods (for example, by using the HTTP method specific variants:
@GetMapping
, @PostMapping
, and others).
You can explicitly map the @RequestMapping
method to HTTP HEAD and HTTP OPTIONS, but that
is not necessary in the common case.
Custom Annotations
Spring MVC supports the use of composed annotations
for request mapping. Those are annotations that are themselves meta-annotated with
@RequestMapping
and composed to redeclare a subset (or all) of the @RequestMapping
attributes with a narrower, more specific purpose.
@GetMapping
, @PostMapping
, @PutMapping
, @DeleteMapping
, and @PatchMapping
are
examples of composed annotations. They are provided because, arguably, most
controller methods should be mapped to a specific HTTP method versus using @RequestMapping
,
which, by default, matches to all HTTP methods. If you need an example of composed
annotations, look at how those are declared.
Spring MVC also supports custom request-mapping attributes with custom request-matching
logic. This is a more advanced option that requires subclassing
RequestMappingHandlerMapping
and overriding the getCustomMethodCondition
method, where
you can check the custom attribute and return your own RequestCondition
.
Explicit Registrations
You can programmatically register handler methods, which you can use for dynamic
registrations or for advanced cases, such as different instances of the same handler
under different URLs. The following example registers a handler method:
Java
@Configuration
public class MyConfig {
@Autowired
public void setHandlerMapping(RequestMappingHandlerMapping mapping, UserHandler handler) (1)
throws NoSuchMethodException {
RequestMappingInfo info = RequestMappingInfo
.paths("/user/{id}").methods(RequestMethod.GET).build(); (2)
Method method = UserHandler.class.getMethod("getUser", Long.class); (3)
mapping.registerMapping(info, handler, method); (4)
}
}
1 | Inject the target handler and the handler mapping for controllers. |
2 | Prepare the request mapping meta data. |
3 | Get the handler method. |
4 | Add the registration. |
Kotlin
@Configuration
class MyConfig {
@Autowired
fun setHandlerMapping(mapping: RequestMappingHandlerMapping, handler: UserHandler) { (1)
val info = RequestMappingInfo.paths("/user/{id}").methods(RequestMethod.GET).build() (2)
val method = UserHandler::class.java.getMethod("getUser", Long::class.java) (3)
mapping.registerMapping(info, handler, method) (4)
}
}
1 | Inject the target handler and the handler mapping for controllers. |
2 | Prepare the request mapping meta data. |
3 | Get the handler method. |
4 | Add the registration. |
1.3.3. Handler Methods
@RequestMapping
handler methods have a flexible signature and can choose from a range of
supported controller method arguments and return values.
Method Arguments
The next table describes the supported controller method arguments. Reactive types are not supported
for any arguments.
JDK 8’s java.util.Optional
is supported as a method argument in combination with
annotations that have a required
attribute (for example, @RequestParam
, @RequestHeader
,
and others) and is equivalent to required=false
.
Controller method argument | Description |
---|---|
|
Generic access to request parameters and request and session attributes, without direct |
|
Choose any specific request or response type — for example, |
|
Enforces the presence of a session. As a consequence, such an argument is never |
|
Servlet 4.0 push builder API for programmatic HTTP/2 resource pushes. |
|
Currently authenticated user — possibly a specific Note that this argument is not resolved eagerly, if it is annotated in order to allow a custom resolver to resolve it |
|
The HTTP method of the request. |
|
The current request locale, determined by the most specific |
|
The time zone associated with the current request, as determined by a |
|
For access to the raw request body as exposed by the Servlet API. |
|
For access to the raw response body as exposed by the Servlet API. |
|
For access to URI template variables. See URI patterns. |
|
For access to name-value pairs in URI path segments. See Matrix Variables. |
|
For access to the Servlet request parameters, including multipart files. Parameter values Note that use of |
|
For access to request headers. Header values are converted to the declared method argument |
|
For access to cookies. Cookies values are converted to the declared method argument |
|
For access to the HTTP request body. Body content is converted to the declared method |
|
For access to request headers and body. The body is converted with an |
|
For access to a part in a |
|
For access to the model that is used in HTML controllers and exposed to templates as |
|
Specify attributes to use in case of a redirect (that is, to be appended to the query |
|
For access to an existing attribute in the model (instantiated if not present) with Note that use of |
|
For access to errors from validation and data binding for a command object |
|
For marking form processing complete, which triggers cleanup of session attributes |
|
For preparing a URL relative to the current request’s host, port, scheme, context path, and |
|
For access to any session attribute, in contrast to model attributes stored in the session |
|
For access to request attributes. See |
Any other argument |
If a method argument is not matched to any of the earlier values in this table and it is |
Return Values
The next table describes the supported controller method return values. Reactive types are
supported for all return values.
Controller method return value | Description |
---|---|
|
The return value is converted through |
|
The return value that specifies the full response (including HTTP headers and body) is to be converted |
|
For returning a response with headers and no body. |
|
To render an RFC 7807 error response with details in the body, |
|
To render an RFC 7807 error response with details in the body, |
|
A view name to be resolved with |
|
A |
|
Attributes to be added to the implicit model, with the view name implicitly determined |
|
An attribute to be added to the model, with the view name implicitly determined through Note that |
|
The view and model attributes to use and, optionally, a response status. |
|
A method with a If none of the above is true, a |
|
Produce any of the preceding return values asynchronously from any thread — for example, as a |
|
Produce any of the above return values asynchronously in a Spring MVC-managed thread. |
|
Alternative to |
|
Emit a stream of objects asynchronously to be written to the response with |
|
Write to the response |
Reactor and other reactive types registered via |
A single value type, e.g. |
Other return values |
If a return value remains unresolved in any other way, it is treated as a model |
Type Conversion
Some annotated controller method arguments that represent String
-based request input (such as
@RequestParam
, @RequestHeader
, @PathVariable
, @MatrixVariable
, and @CookieValue
)
can require type conversion if the argument is declared as something other than String
.
For such cases, type conversion is automatically applied based on the configured converters.
By default, simple types (int
, long
, Date
, and others) are supported. You can customize
type conversion through a WebDataBinder
(see DataBinder
) or by registering
Formatters
with the FormattingConversionService
.
See Spring Field Formatting.
A practical issue in type conversion is the treatment of an empty String source value.
Such a value is treated as missing if it becomes null
as a result of type conversion.
This can be the case for Long
, UUID
, and other target types. If you want to allow null
to be injected, either use the required
flag on the argument annotation, or declare the
argument as @Nullable
.
As of 5.3, non-null arguments will be enforced even after type conversion. If your handler Alternatively, you may specifically handle e.g. the resulting |
Matrix Variables
RFC 3986 discusses name-value pairs in
path segments. In Spring MVC, we refer to those as “matrix variables” based on an
“old post” by Tim Berners-Lee, but they
can be also be referred to as URI path parameters.
Matrix variables can appear in any path segment, with each variable separated by a semicolon and
multiple values separated by comma (for example, /cars;color=red,green;year=2012
). Multiple
values can also be specified through repeated variable names (for example,
color=red;color=green;color=blue
).
If a URL is expected to contain matrix variables, the request mapping for a controller
method must use a URI variable to mask that variable content and ensure the request can
be matched successfully independent of matrix variable order and presence.
The following example uses a matrix variable:
Java
// GET /pets/42;q=11;r=22
@GetMapping("/pets/{petId}")
public void findPet(@PathVariable String petId, @MatrixVariable int q) {
// petId == 42
// q == 11
}
Kotlin
// GET /pets/42;q=11;r=22
@GetMapping("/pets/{petId}")
fun findPet(@PathVariable petId: String, @MatrixVariable q: Int) {
// petId == 42
// q == 11
}
Given that all path segments may contain matrix variables, you may sometimes need to
disambiguate which path variable the matrix variable is expected to be in.
The following example shows how to do so:
Java
// GET /owners/42;q=11/pets/21;q=22
@GetMapping("/owners/{ownerId}/pets/{petId}")
public void findPet(
@MatrixVariable(name="q", pathVar="ownerId") int q1,
@MatrixVariable(name="q", pathVar="petId") int q2) {
// q1 == 11
// q2 == 22
}
Kotlin
// GET /owners/42;q=11/pets/21;q=22
@GetMapping("/owners/{ownerId}/pets/{petId}")
fun findPet(
@MatrixVariable(name = "q", pathVar = "ownerId") q1: Int,
@MatrixVariable(name = "q", pathVar = "petId") q2: Int) {
// q1 == 11
// q2 == 22
}
A matrix variable may be defined as optional and a default value specified, as the
following example shows:
Java
// GET /pets/42
@GetMapping("/pets/{petId}")
public void findPet(@MatrixVariable(required=false, defaultValue="1") int q) {
// q == 1
}
Kotlin
// GET /pets/42
@GetMapping("/pets/{petId}")
fun findPet(@MatrixVariable(required = false, defaultValue = "1") q: Int) {
// q == 1
}
To get all matrix variables, you can use a MultiValueMap
, as the following example shows:
Java
// GET /owners/42;q=11;r=12/pets/21;q=22;s=23
@GetMapping("/owners/{ownerId}/pets/{petId}")
public void findPet(
@MatrixVariable MultiValueMap<String, String> matrixVars,
@MatrixVariable(pathVar="petId") MultiValueMap<String, String> petMatrixVars) {
// matrixVars: ["q" : [11,22], "r" : 12, "s" : 23]
// petMatrixVars: ["q" : 22, "s" : 23]
}
Kotlin
// GET /owners/42;q=11;r=12/pets/21;q=22;s=23
@GetMapping("/owners/{ownerId}/pets/{petId}")
fun findPet(
@MatrixVariable matrixVars: MultiValueMap<String, String>,
@MatrixVariable(pathVar="petId") petMatrixVars: MultiValueMap<String, String>) {
// matrixVars: ["q" : [11,22], "r" : 12, "s" : 23]
// petMatrixVars: ["q" : 22, "s" : 23]
}
Note that you need to enable the use of matrix variables. In the MVC Java configuration,
you need to set a UrlPathHelper
with removeSemicolonContent=false
through
Path Matching. In the MVC XML namespace, you can set
<mvc:annotation-driven enable-matrix-variables="true"/>
.
@RequestParam
You can use the @RequestParam
annotation to bind Servlet request parameters (that is,
query parameters or form data) to a method argument in a controller.
The following example shows how to do so:
Java
@Controller
@RequestMapping("/pets")
public class EditPetForm {
// ...
@GetMapping
public String setupForm(@RequestParam("petId") int petId, Model model) { (1)
Pet pet = this.clinic.loadPet(petId);
model.addAttribute("pet", pet);
return "petForm";
}
// ...
}
1 | Using @RequestParam to bind petId . |
Kotlin
import org.springframework.ui.set
@Controller
@RequestMapping("/pets")
class EditPetForm {
// ...
@GetMapping
fun setupForm(@RequestParam("petId") petId: Int, model: Model): String { (1)
val pet = this.clinic.loadPet(petId);
model["pet"] = pet
return "petForm"
}
// ...
}
1 | Using @RequestParam to bind petId . |
By default, method parameters that use this annotation are required, but you can specify that
a method parameter is optional by setting the @RequestParam
annotation’s required
flag to
false
or by declaring the argument with an java.util.Optional
wrapper.
Type conversion is automatically applied if the target method parameter type is not
String
. See Type Conversion.
Declaring the argument type as an array or list allows for resolving multiple parameter
values for the same parameter name.
When an @RequestParam
annotation is declared as a Map<String, String>
or
MultiValueMap<String, String>
, without a parameter name specified in the annotation,
then the map is populated with the request parameter values for each given parameter name.
Note that use of @RequestParam
is optional (for example, to set its attributes).
By default, any argument that is a simple value type (as determined by
BeanUtils#isSimpleProperty)
and is not resolved by any other argument resolver, is treated as if it were annotated
with @RequestParam
.
You can use the @RequestHeader
annotation to bind a request header to a method argument in a
controller.
Consider the following request, with headers:
Host localhost:8080 Accept text/html,application/xhtml+xml,application/xml;q=0.9 Accept-Language fr,en-gb;q=0.7,en;q=0.3 Accept-Encoding gzip,deflate Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7 Keep-Alive 300
The following example gets the value of the Accept-Encoding
and Keep-Alive
headers:
Java
@GetMapping("/demo")
public void handle(
@RequestHeader("Accept-Encoding") String encoding, (1)
@RequestHeader("Keep-Alive") long keepAlive) { (2)
//...
}
1 | Get the value of the Accept-Encoding header. |
2 | Get the value of the Keep-Alive header. |
Kotlin
@GetMapping("/demo")
fun handle(
@RequestHeader("Accept-Encoding") encoding: String, (1)
@RequestHeader("Keep-Alive") keepAlive: Long) { (2)
//...
}
1 | Get the value of the Accept-Encoding header. |
2 | Get the value of the Keep-Alive header. |
If the target method parameter type is not
String
, type conversion is automatically applied. See Type Conversion.
When an @RequestHeader
annotation is used on a Map<String, String>
,
MultiValueMap<String, String>
, or HttpHeaders
argument, the map is populated
with all header values.
Built-in support is available for converting a comma-separated string into an array or collection of strings or other types known to the type conversion system. For example, a method parameter annotated with @RequestHeader("Accept") can be of typeString but also String[] or List<String> .
|
@CookieValue
You can use the @CookieValue
annotation to bind the value of an HTTP cookie to a method argument
in a controller.
Consider a request with the following cookie:
JSESSIONID=415A4AC178C59DACE0B2C9CA727CDD84
The following example shows how to get the cookie value:
Java
@GetMapping("/demo")
public void handle(@CookieValue("JSESSIONID") String cookie) { (1)
//...
}
1 | Get the value of the JSESSIONID cookie. |
Kotlin
@GetMapping("/demo")
fun handle(@CookieValue("JSESSIONID") cookie: String) { (1)
//...
}
1 | Get the value of the JSESSIONID cookie. |
If the target method parameter type is not String
, type conversion is applied automatically.
See Type Conversion.
@ModelAttribute
You can use the @ModelAttribute
annotation on a method argument to access an attribute from
the model or have it be instantiated if not present. The model attribute is also overlain with
values from HTTP Servlet request parameters whose names match to field names. This is referred
to as data binding, and it saves you from having to deal with parsing and converting individual
query parameters and form fields. The following example shows how to do so:
Java
@PostMapping("/owners/{ownerId}/pets/{petId}/edit")
public String processSubmit(@ModelAttribute Pet pet) { (1)
// method logic...
}
1 | Bind an instance of Pet . |
Kotlin
@PostMapping("/owners/{ownerId}/pets/{petId}/edit")
fun processSubmit(@ModelAttribute pet: Pet): String { (1)
// method logic...
}
1 | Bind an instance of Pet . |
The Pet
instance above is sourced in one of the following ways:
-
Retrieved from the model where it may have been added by a
@ModelAttribute method. -
Retrieved from the HTTP session if the model attribute was listed in
the class-level@SessionAttributes
annotation. -
Obtained through a
Converter
where the model attribute name matches the name of a
request value such as a path variable or a request parameter (see next example). -
Instantiated using its default constructor.
-
Instantiated through a “primary constructor” with arguments that match to Servlet
request parameters. Argument names are determined through JavaBeans
@ConstructorProperties
or through runtime-retained parameter names in the bytecode.
One alternative to using a @ModelAttribute method to
supply it or relying on the framework to create the model attribute, is to have a
Converter<String, T>
to provide the instance. This is applied when the model attribute
name matches to the name of a request value such as a path variable or a request
parameter, and there is a Converter
from String
to the model attribute type.
In the following example, the model attribute name is account
which matches the URI
path variable account
, and there is a registered Converter<String, Account>
which
could load the Account
from a data store:
Java
@PutMapping("/accounts/{account}")
public String save(@ModelAttribute("account") Account account) { (1)
// ...
}
1 | Bind an instance of Account using an explicit attribute name. |
Kotlin
@PutMapping("/accounts/{account}")
fun save(@ModelAttribute("account") account: Account): String { (1)
// ...
}
1 | Bind an instance of Account using an explicit attribute name. |
After the model attribute instance is obtained, data binding is applied. The
WebDataBinder
class matches Servlet request parameter names (query parameters and form
fields) to field names on the target Object
. Matching fields are populated after type
conversion is applied, where necessary. For more on data binding (and validation), see
Validation. For more on customizing data binding, see
DataBinder
.
Data binding can result in errors. By default, a BindException
is raised. However, to check
for such errors in the controller method, you can add a BindingResult
argument immediately next
to the @ModelAttribute
, as the following example shows:
Java
@PostMapping("/owners/{ownerId}/pets/{petId}/edit")
public String processSubmit(@ModelAttribute("pet") Pet pet, BindingResult result) { (1)
if (result.hasErrors()) {
return "petForm";
}
// ...
}
1 | Adding a BindingResult next to the @ModelAttribute . |
Kotlin
@PostMapping("/owners/{ownerId}/pets/{petId}/edit")
fun processSubmit(@ModelAttribute("pet") pet: Pet, result: BindingResult): String { (1)
if (result.hasErrors()) {
return "petForm"
}
// ...
}
1 | Adding a BindingResult next to the @ModelAttribute . |
In some cases, you may want access to a model attribute without data binding. For such
cases, you can inject the Model
into the controller and access it directly or,
alternatively, set @ModelAttribute(binding=false)
, as the following example shows:
Java
@ModelAttribute
public AccountForm setUpForm() {
return new AccountForm();
}
@ModelAttribute
public Account findAccount(@PathVariable String accountId) {
return accountRepository.findOne(accountId);
}
@PostMapping("update")
public String update(@Valid AccountForm form, BindingResult result,
@ModelAttribute(binding=false) Account account) { (1)
// ...
}
1 | Setting @ModelAttribute(binding=false) . |
Kotlin
@ModelAttribute
fun setUpForm(): AccountForm {
return AccountForm()
}
@ModelAttribute
fun findAccount(@PathVariable accountId: String): Account {
return accountRepository.findOne(accountId)
}
@PostMapping("update")
fun update(@Valid form: AccountForm, result: BindingResult,
@ModelAttribute(binding = false) account: Account): String { (1)
// ...
}
1 | Setting @ModelAttribute(binding=false) . |
You can automatically apply validation after data binding by adding the
jakarta.validation.Valid
annotation or Spring’s @Validated
annotation
(Bean Validation and
Spring validation). The following example shows how to do so:
Java
@PostMapping("/owners/{ownerId}/pets/{petId}/edit")
public String processSubmit(@Valid @ModelAttribute("pet") Pet pet, BindingResult result) { (1)
if (result.hasErrors()) {
return "petForm";
}
// ...
}
1 | Validate the Pet instance. |
Kotlin
@PostMapping("/owners/{ownerId}/pets/{petId}/edit")
fun processSubmit(@Valid @ModelAttribute("pet") pet: Pet, result: BindingResult): String { (1)
if (result.hasErrors()) {
return "petForm"
}
// ...
}
1 | Validate the Pet instance. |
Note that using @ModelAttribute
is optional (for example, to set its attributes).
By default, any argument that is not a simple value type (as determined by
BeanUtils#isSimpleProperty)
and is not resolved by any other argument resolver is treated as if it were annotated
with @ModelAttribute
.
@SessionAttributes
@SessionAttributes
is used to store model attributes in the HTTP Servlet session between
requests. It is a type-level annotation that declares the session attributes used by a
specific controller. This typically lists the names of model attributes or types of
model attributes that should be transparently stored in the session for subsequent
requests to access.
The following example uses the @SessionAttributes
annotation:
Java
@Controller
@SessionAttributes("pet") (1)
public class EditPetForm {
// ...
}
1 | Using the @SessionAttributes annotation. |
Kotlin
@Controller
@SessionAttributes("pet") (1)
class EditPetForm {
// ...
}
1 | Using the @SessionAttributes annotation. |
On the first request, when a model attribute with the name, pet
, is added to the model,
it is automatically promoted to and saved in the HTTP Servlet session. It remains there
until another controller method uses a SessionStatus
method argument to clear the
storage, as the following example shows:
Java
@Controller
@SessionAttributes("pet") (1)
public class EditPetForm {
// ...
@PostMapping("/pets/{id}")
public String handle(Pet pet, BindingResult errors, SessionStatus status) {
if (errors.hasErrors) {
// ...
}
status.setComplete(); (2)
// ...
}
}
1 | Storing the Pet value in the Servlet session. |
2 | Clearing the Pet value from the Servlet session. |
Kotlin
@Controller
@SessionAttributes("pet") (1)
class EditPetForm {
// ...
@PostMapping("/pets/{id}")
fun handle(pet: Pet, errors: BindingResult, status: SessionStatus): String {
if (errors.hasErrors()) {
// ...
}
status.setComplete() (2)
// ...
}
}
1 | Storing the Pet value in the Servlet session. |
2 | Clearing the Pet value from the Servlet session. |
@SessionAttribute
If you need access to pre-existing session attributes that are managed globally
(that is, outside the controller — for example, by a filter) and may or may not be present,
you can use the @SessionAttribute
annotation on a method parameter,
as the following example shows:
Java
@RequestMapping("/")
public String handle(@SessionAttribute User user) { (1)
// ...
}
1 | Using a @SessionAttribute annotation. |
Kotlin
@RequestMapping("/")
fun handle(@SessionAttribute user: User): String { (1)
// ...
}
1 | Using a @SessionAttribute annotation. |
For use cases that require adding or removing session attributes, consider injecting
org.springframework.web.context.request.WebRequest
or
jakarta.servlet.http.HttpSession
into the controller method.
For temporary storage of model attributes in the session as part of a controller
workflow, consider using @SessionAttributes
as described in
@SessionAttributes
.
@RequestAttribute
Similar to @SessionAttribute
, you can use the @RequestAttribute
annotations to
access pre-existing request attributes created earlier (for example, by a Servlet Filter
or HandlerInterceptor
):
Java
@GetMapping("/")
public String handle(@RequestAttribute Client client) { (1)
// ...
}
1 | Using the @RequestAttribute annotation. |
Kotlin
@GetMapping("/")
fun handle(@RequestAttribute client: Client): String { (1)
// ...
}
1 | Using the @RequestAttribute annotation. |
Redirect Attributes
By default, all model attributes are considered to be exposed as URI template variables in
the redirect URL. Of the remaining attributes, those that are primitive types or
collections or arrays of primitive types are automatically appended as query parameters.
Appending primitive type attributes as query parameters can be the desired result if a
model instance was prepared specifically for the redirect. However, in annotated
controllers, the model can contain additional attributes added for rendering purposes (for example,
drop-down field values). To avoid the possibility of having such attributes appear in the
URL, a @RequestMapping
method can declare an argument of type RedirectAttributes
and
use it to specify the exact attributes to make available to RedirectView
. If the method
does redirect, the content of RedirectAttributes
is used. Otherwise, the content of the
model is used.
The RequestMappingHandlerAdapter
provides a flag called
ignoreDefaultModelOnRedirect
, which you can use to indicate that the content of the default
Model
should never be used if a controller method redirects. Instead, the controller
method should declare an attribute of type RedirectAttributes
or, if it does not do so,
no attributes should be passed on to RedirectView
. Both the MVC namespace and the MVC
Java configuration keep this flag set to false
, to maintain backwards compatibility.
However, for new applications, we recommend setting it to true
.
Note that URI template variables from the present request are automatically made
available when expanding a redirect URL, and you don’t need to explicitly add them
through Model
or RedirectAttributes
. The following example shows how to define a redirect:
Java
@PostMapping("/files/{path}")
public String upload(...) {
// ...
return "redirect:files/{path}";
}
Kotlin
@PostMapping("/files/{path}")
fun upload(...): String {
// ...
return "redirect:files/{path}"
}
Another way of passing data to the redirect target is by using flash attributes. Unlike
other redirect attributes, flash attributes are saved in the HTTP session (and, hence, do
not appear in the URL). See Flash Attributes for more information.
Flash Attributes
Flash attributes provide a way for one request to store attributes that are intended for use in
another. This is most commonly needed when redirecting — for example, the
Post-Redirect-Get pattern. Flash attributes are saved temporarily before the
redirect (typically in the session) to be made available to the request after the
redirect and are removed immediately.
Spring MVC has two main abstractions in support of flash attributes. FlashMap
is used
to hold flash attributes, while FlashMapManager
is used to store, retrieve, and manage
FlashMap
instances.
Flash attribute support is always “on” and does not need to be enabled explicitly.
However, if not used, it never causes HTTP session creation. On each request, there is an
“input” FlashMap
with attributes passed from a previous request (if any) and an
“output” FlashMap
with attributes to save for a subsequent request. Both FlashMap
instances are accessible from anywhere in Spring MVC through static methods in
RequestContextUtils
.
Annotated controllers typically do not need to work with FlashMap
directly. Instead, a
@RequestMapping
method can accept an argument of type RedirectAttributes
and use it
to add flash attributes for a redirect scenario. Flash attributes added through
RedirectAttributes
are automatically propagated to the “output” FlashMap. Similarly,
after the redirect, attributes from the “input” FlashMap
are automatically added to the
Model
of the controller that serves the target URL.
Multipart
After a MultipartResolver
has been enabled, the content of POST
requests with multipart/form-data
is parsed and accessible as regular request
parameters. The following example accesses one regular form field and one uploaded
file:
Java
@Controller
public class FileUploadController {
@PostMapping("/form")
public String handleFormUpload(@RequestParam("name") String name,
@RequestParam("file") MultipartFile file) {
if (!file.isEmpty()) {
byte[] bytes = file.getBytes();
// store the bytes somewhere
return "redirect:uploadSuccess";
}
return "redirect:uploadFailure";
}
}
Kotlin
@Controller
class FileUploadController {
@PostMapping("/form")
fun handleFormUpload(@RequestParam("name") name: String,
@RequestParam("file") file: MultipartFile): String {
if (!file.isEmpty) {
val bytes = file.bytes
// store the bytes somewhere
return "redirect:uploadSuccess"
}
return "redirect:uploadFailure"
}
}
Declaring the argument type as a List<MultipartFile>
allows for resolving multiple
files for the same parameter name.
When the @RequestParam
annotation is declared as a Map<String, MultipartFile>
or
MultiValueMap<String, MultipartFile>
, without a parameter name specified in the annotation,
then the map is populated with the multipart files for each given parameter name.
With Servlet multipart parsing, you may also declare jakarta.servlet.http.Part instead of Spring’s MultipartFile , as a method argument or collection value type.
|
You can also use multipart content as part of data binding to a
command object. For example, the form field
and file from the preceding example could be fields on a form object,
as the following example shows:
Java
class MyForm {
private String name;
private MultipartFile file;
// ...
}
@Controller
public class FileUploadController {
@PostMapping("/form")
public String handleFormUpload(MyForm form, BindingResult errors) {
if (!form.getFile().isEmpty()) {
byte[] bytes = form.getFile().getBytes();
// store the bytes somewhere
return "redirect:uploadSuccess";
}
return "redirect:uploadFailure";
}
}
Kotlin
class MyForm(val name: String, val file: MultipartFile, ...)
@Controller
class FileUploadController {
@PostMapping("/form")
fun handleFormUpload(form: MyForm, errors: BindingResult): String {
if (!form.file.isEmpty) {
val bytes = form.file.bytes
// store the bytes somewhere
return "redirect:uploadSuccess"
}
return "redirect:uploadFailure"
}
}
Multipart requests can also be submitted from non-browser clients in a RESTful service
scenario. The following example shows a file with JSON:
POST /someUrl Content-Type: multipart/mixed --edt7Tfrdusa7r3lNQc79vXuhIIMlatb7PQg7Vp Content-Disposition: form-data; name="meta-data" Content-Type: application/json; charset=UTF-8 Content-Transfer-Encoding: 8bit { "name": "value" } --edt7Tfrdusa7r3lNQc79vXuhIIMlatb7PQg7Vp Content-Disposition: form-data; name="file-data"; filename="file.properties" Content-Type: text/xml Content-Transfer-Encoding: 8bit ... File Data ...
You can access the «meta-data» part with @RequestParam
as a String
but you’ll
probably want it deserialized from JSON (similar to @RequestBody
). Use the
@RequestPart
annotation to access a multipart after converting it with an
HttpMessageConverter:
Java
@PostMapping("/")
public String handle(@RequestPart("meta-data") MetaData metadata,
@RequestPart("file-data") MultipartFile file) {
// ...
}
Kotlin
@PostMapping("/")
fun handle(@RequestPart("meta-data") metadata: MetaData,
@RequestPart("file-data") file: MultipartFile): String {
// ...
}
You can use @RequestPart
in combination with jakarta.validation.Valid
or use Spring’s
@Validated
annotation, both of which cause Standard Bean Validation to be applied.
By default, validation errors cause a MethodArgumentNotValidException
, which is turned
into a 400 (BAD_REQUEST) response. Alternatively, you can handle validation errors locally
within the controller through an Errors
or BindingResult
argument,
as the following example shows:
Java
@PostMapping("/")
public String handle(@Valid @RequestPart("meta-data") MetaData metadata,
BindingResult result) {
// ...
}
Kotlin
@PostMapping("/")
fun handle(@Valid @RequestPart("meta-data") metadata: MetaData,
result: BindingResult): String {
// ...
}
@RequestBody
You can use the @RequestBody
annotation to have the request body read and deserialized into an
Object
through an HttpMessageConverter
.
The following example uses a @RequestBody
argument:
Java
@PostMapping("/accounts")
public void handle(@RequestBody Account account) {
// ...
}
Kotlin
@PostMapping("/accounts")
fun handle(@RequestBody account: Account) {
// ...
}
You can use the Message Converters option of the MVC Config to
configure or customize message conversion.
You can use @RequestBody
in combination with jakarta.validation.Valid
or Spring’s
@Validated
annotation, both of which cause Standard Bean Validation to be applied.
By default, validation errors cause a MethodArgumentNotValidException
, which is turned
into a 400 (BAD_REQUEST) response. Alternatively, you can handle validation errors locally
within the controller through an Errors
or BindingResult
argument,
as the following example shows:
Java
@PostMapping("/accounts")
public void handle(@Valid @RequestBody Account account, BindingResult result) {
// ...
}
Kotlin
@PostMapping("/accounts")
fun handle(@Valid @RequestBody account: Account, result: BindingResult) {
// ...
}
HttpEntity
HttpEntity
is more or less identical to using @RequestBody
but is based on a
container object that exposes request headers and body. The following listing shows an example:
Java
@PostMapping("/accounts")
public void handle(HttpEntity<Account> entity) {
// ...
}
Kotlin
@PostMapping("/accounts")
fun handle(entity: HttpEntity<Account>) {
// ...
}
@ResponseBody
You can use the @ResponseBody
annotation on a method to have the return serialized
to the response body through an
HttpMessageConverter.
The following listing shows an example:
Java
@GetMapping("/accounts/{id}")
@ResponseBody
public Account handle() {
// ...
}
Kotlin
@GetMapping("/accounts/{id}")
@ResponseBody
fun handle(): Account {
// ...
}
@ResponseBody
is also supported at the class level, in which case it is inherited by
all controller methods. This is the effect of @RestController
, which is nothing more
than a meta-annotation marked with @Controller
and @ResponseBody
.
You can use @ResponseBody
with reactive types.
See Asynchronous Requests and Reactive Types for more details.
You can use the Message Converters option of the MVC Config to
configure or customize message conversion.
You can combine @ResponseBody
methods with JSON serialization views.
See Jackson JSON for details.
ResponseEntity
ResponseEntity
is like @ResponseBody
but with status and headers. For example:
Java
@GetMapping("/something")
public ResponseEntity<String> handle() {
String body = ... ;
String etag = ... ;
return ResponseEntity.ok().eTag(etag).body(body);
}
Kotlin
@GetMapping("/something")
fun handle(): ResponseEntity<String> {
val body = ...
val etag = ...
return ResponseEntity.ok().eTag(etag).build(body)
}
Spring MVC supports using a single value reactive type
to produce the ResponseEntity
asynchronously, and/or single and multi-value reactive
types for the body. This allows the following types of async responses:
-
ResponseEntity<Mono<T>>
orResponseEntity<Flux<T>>
make the response status and
headers known immediately while the body is provided asynchronously at a later point.
UseMono
if the body consists of 0..1 values orFlux
if it can produce multiple values. -
Mono<ResponseEntity<T>>
provides all three — response status, headers, and body,
asynchronously at a later point. This allows the response status and headers to vary
depending on the outcome of asynchronous request handling.
Jackson JSON
Spring offers support for the Jackson JSON library.
JSON Views
Spring MVC provides built-in support for
Jackson’s Serialization Views,
which allow rendering only a subset of all fields in an Object
. To use it with
@ResponseBody
or ResponseEntity
controller methods, you can use Jackson’s
@JsonView
annotation to activate a serialization view class, as the following example shows:
Java
@RestController
public class UserController {
@GetMapping("/user")
@JsonView(User.WithoutPasswordView.class)
public User getUser() {
return new User("eric", "7!jd#h23");
}
}
public class User {
public interface WithoutPasswordView {};
public interface WithPasswordView extends WithoutPasswordView {};
private String username;
private String password;
public User() {
}
public User(String username, String password) {
this.username = username;
this.password = password;
}
@JsonView(WithoutPasswordView.class)
public String getUsername() {
return this.username;
}
@JsonView(WithPasswordView.class)
public String getPassword() {
return this.password;
}
}
Kotlin
@RestController
class UserController {
@GetMapping("/user")
@JsonView(User.WithoutPasswordView::class)
fun getUser() = User("eric", "7!jd#h23")
}
class User(
@JsonView(WithoutPasswordView::class) val username: String,
@JsonView(WithPasswordView::class) val password: String) {
interface WithoutPasswordView
interface WithPasswordView : WithoutPasswordView
}
@JsonView allows an array of view classes, but you can specify only one percontroller method. If you need to activate multiple views, you can use a composite interface. |
If you want to do the above programmatically, instead of declaring an @JsonView
annotation,
wrap the return value with MappingJacksonValue
and use it to supply the serialization view:
Java
@RestController
public class UserController {
@GetMapping("/user")
public MappingJacksonValue getUser() {
User user = new User("eric", "7!jd#h23");
MappingJacksonValue value = new MappingJacksonValue(user);
value.setSerializationView(User.WithoutPasswordView.class);
return value;
}
}
Kotlin
@RestController
class UserController {
@GetMapping("/user")
fun getUser(): MappingJacksonValue {
val value = MappingJacksonValue(User("eric", "7!jd#h23"))
value.serializationView = User.WithoutPasswordView::class.java
return value
}
}
For controllers that rely on view resolution, you can add the serialization view class
to the model, as the following example shows:
Java
@Controller
public class UserController extends AbstractController {
@GetMapping("/user")
public String getUser(Model model) {
model.addAttribute("user", new User("eric", "7!jd#h23"));
model.addAttribute(JsonView.class.getName(), User.WithoutPasswordView.class);
return "userView";
}
}
Kotlin
@Controller
class UserController : AbstractController() {
@GetMapping("/user")
fun getUser(model: Model): String {
model["user"] = User("eric", "7!jd#h23")
model[JsonView::class.qualifiedName] = User.WithoutPasswordView::class.java
return "userView"
}
}
1.3.4. Model
You can use the @ModelAttribute
annotation:
-
On a method argument in
@RequestMapping
methods
to create or access anObject
from the model and to bind it to the request through a
WebDataBinder
. -
As a method-level annotation in
@Controller
or@ControllerAdvice
classes that help
to initialize the model prior to any@RequestMapping
method invocation. -
On a
@RequestMapping
method to mark its return value is a model attribute.
This section discusses @ModelAttribute
methods — the second item in the preceding list.
A controller can have any number of @ModelAttribute
methods. All such methods are
invoked before @RequestMapping
methods in the same controller. A @ModelAttribute
method can also be shared across controllers through @ControllerAdvice
. See the section on
Controller Advice for more details.
@ModelAttribute
methods have flexible method signatures. They support many of the same
arguments as @RequestMapping
methods, except for @ModelAttribute
itself or anything
related to the request body.
The following example shows a @ModelAttribute
method:
Java
@ModelAttribute
public void populateModel(@RequestParam String number, Model model) {
model.addAttribute(accountRepository.findAccount(number));
// add more ...
}
Kotlin
@ModelAttribute
fun populateModel(@RequestParam number: String, model: Model) {
model.addAttribute(accountRepository.findAccount(number))
// add more ...
}
The following example adds only one attribute:
Java
@ModelAttribute
public Account addAccount(@RequestParam String number) {
return accountRepository.findAccount(number);
}
Kotlin
@ModelAttribute
fun addAccount(@RequestParam number: String): Account {
return accountRepository.findAccount(number)
}
When a name is not explicitly specified, a default name is chosen based on the Object type, as explained in the javadoc for Conventions .You can always assign an explicit name by using the overloaded addAttribute method orthrough the name attribute on @ModelAttribute (for a return value).
|
You can also use @ModelAttribute
as a method-level annotation on @RequestMapping
methods,
in which case the return value of the @RequestMapping
method is interpreted as a model
attribute. This is typically not required, as it is the default behavior in HTML controllers,
unless the return value is a String
that would otherwise be interpreted as a view name.
@ModelAttribute
can also customize the model attribute name, as the following example shows:
Java
@GetMapping("/accounts/{id}")
@ModelAttribute("myAccount")
public Account handle() {
// ...
return account;
}
Kotlin
@GetMapping("/accounts/{id}")
@ModelAttribute("myAccount")
fun handle(): Account {
// ...
return account
}
1.3.5. DataBinder
@Controller
or @ControllerAdvice
classes can have @InitBinder
methods that
initialize instances of WebDataBinder
, and those, in turn, can:
-
Bind request parameters (that is, form or query data) to a model object.
-
Convert String-based request values (such as request parameters, path variables,
headers, cookies, and others) to the target type of controller method arguments. -
Format model object values as
String
values when rendering HTML forms.
@InitBinder
methods can register controller-specific java.beans.PropertyEditor
or
Spring Converter
and Formatter
components. In addition, you can use the
MVC config to register Converter
and Formatter
types in a globally shared FormattingConversionService
.
@InitBinder
methods support many of the same arguments that @RequestMapping
methods
do, except for @ModelAttribute
(command object) arguments. Typically, they are declared
with a WebDataBinder
argument (for registrations) and a void
return value.
The following listing shows an example:
Java
@Controller
public class FormController {
@InitBinder (1)
public void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
}
// ...
}
1 | Defining an @InitBinder method. |
Kotlin
@Controller
class FormController {
@InitBinder (1)
fun initBinder(binder: WebDataBinder) {
val dateFormat = SimpleDateFormat("yyyy-MM-dd")
dateFormat.isLenient = false
binder.registerCustomEditor(Date::class.java, CustomDateEditor(dateFormat, false))
}
// ...
}
1 | Defining an @InitBinder method. |
Alternatively, when you use a Formatter
-based setup through a shared
FormattingConversionService
, you can re-use the same approach and register
controller-specific Formatter
implementations, as the following example shows:
Java
@Controller
public class FormController {
@InitBinder (1)
protected void initBinder(WebDataBinder binder) {
binder.addCustomFormatter(new DateFormatter("yyyy-MM-dd"));
}
// ...
}
1 | Defining an @InitBinder method on a custom formatter. |
Kotlin
@Controller
class FormController {
@InitBinder (1)
protected fun initBinder(binder: WebDataBinder) {
binder.addCustomFormatter(DateFormatter("yyyy-MM-dd"))
}
// ...
}
1 | Defining an @InitBinder method on a custom formatter. |
Model Design
In the context of web applications, data binding involves the binding of HTTP request
parameters (that is, form data or query parameters) to properties in a model object and
its nested objects.
Only public
properties following the
JavaBeans naming conventions
are exposed for data binding — for example, public String getFirstName()
and
public void setFirstName(String)
methods for a firstName
property.
The model object, and its nested object graph, is also sometimes referred to as a command object, form-backing object, or POJO (Plain Old Java Object). |
By default, Spring permits binding to all public properties in the model object graph.
This means you need to carefully consider what public properties the model has, since a
client could target any public property path, even some that are not expected to be
targeted for a given use case.
For example, given an HTTP form data endpoint, a malicious client could supply values for
properties that exist in the model object graph but are not part of the HTML form
presented in the browser. This could lead to data being set on the model object and any
of its nested objects, that is not expected to be updated.
The recommended approach is to use a dedicated model object that exposes only
properties that are relevant for the form submission. For example, on a form for changing
a user’s email address, the model object should declare a minimum set of properties such
as in the following ChangeEmailForm
.
public class ChangeEmailForm {
private String oldEmailAddress;
private String newEmailAddress;
public void setOldEmailAddress(String oldEmailAddress) {
this.oldEmailAddress = oldEmailAddress;
}
public String getOldEmailAddress() {
return this.oldEmailAddress;
}
public void setNewEmailAddress(String newEmailAddress) {
this.newEmailAddress = newEmailAddress;
}
public String getNewEmailAddress() {
return this.newEmailAddress;
}
}
If you cannot or do not want to use a dedicated model object for each data
binding use case, you must limit the properties that are allowed for data binding.
Ideally, you can achieve this by registering allowed field patterns via the
setAllowedFields()
method on WebDataBinder
.
For example, to register allowed field patterns in your application, you can implement an
@InitBinder
method in a @Controller
or @ControllerAdvice
component as shown below:
@Controller
public class ChangeEmailController {
@InitBinder
void initBinder(WebDataBinder binder) {
binder.setAllowedFields("oldEmailAddress", "newEmailAddress");
}
// @RequestMapping methods, etc.
}
In addition to registering allowed patterns, it is also possible to register disallowed
field patterns via the setDisallowedFields()
method in DataBinder
and its subclasses.
Please note, however, that an «allow list» is safer than a «deny list». Consequently,
setAllowedFields()
should be favored over setDisallowedFields()
.
Note that matching against allowed field patterns is case-sensitive; whereas, matching
against disallowed field patterns is case-insensitive. In addition, a field matching a
disallowed pattern will not be accepted even if it also happens to match a pattern in the
allowed list.
It is extremely important to properly configure allowed and disallowed field patterns Furthermore, it is strongly recommended that you do not use types from your domain |
1.3.6. Exceptions
@Controller
and @ControllerAdvice classes can have
@ExceptionHandler
methods to handle exceptions from controller methods, as the following example shows:
Java
@Controller
public class SimpleController {
// ...
@ExceptionHandler
public ResponseEntity<String> handle(IOException ex) {
// ...
}
}
Kotlin
@Controller
class SimpleController {
// ...
@ExceptionHandler
fun handle(ex: IOException): ResponseEntity<String> {
// ...
}
}
The exception may match against a top-level exception being propagated (e.g. a direct
IOException
being thrown) or against a nested cause within a wrapper exception (e.g.
an IOException
wrapped inside an IllegalStateException
). As of 5.3, this can match
at arbitrary cause levels, whereas previously only an immediate cause was considered.
For matching exception types, preferably declare the target exception as a method argument,
as the preceding example shows. When multiple exception methods match, a root exception match is
generally preferred to a cause exception match. More specifically, the ExceptionDepthComparator
is used to sort exceptions based on their depth from the thrown exception type.
Alternatively, the annotation declaration may narrow the exception types to match,
as the following example shows:
Java
@ExceptionHandler({FileSystemException.class, RemoteException.class})
public ResponseEntity<String> handle(IOException ex) {
// ...
}
Kotlin
@ExceptionHandler(FileSystemException::class, RemoteException::class)
fun handle(ex: IOException): ResponseEntity<String> {
// ...
}
You can even use a list of specific exception types with a very generic argument signature,
as the following example shows:
Java
@ExceptionHandler({FileSystemException.class, RemoteException.class})
public ResponseEntity<String> handle(Exception ex) {
// ...
}
Kotlin
@ExceptionHandler(FileSystemException::class, RemoteException::class)
fun handle(ex: Exception): ResponseEntity<String> {
// ...
}
The distinction between root and cause exception matching can be surprising. In the The behavior is even simpler in the |
We generally recommend that you be as specific as possible in the argument signature,
reducing the potential for mismatches between root and cause exception types.
Consider breaking a multi-matching method into individual @ExceptionHandler
methods, each matching a single specific exception type through its signature.
In a multi-@ControllerAdvice
arrangement, we recommend declaring your primary root exception
mappings on a @ControllerAdvice
prioritized with a corresponding order. While a root
exception match is preferred to a cause, this is defined among the methods of a given
controller or @ControllerAdvice
class. This means a cause match on a higher-priority
@ControllerAdvice
bean is preferred to any match (for example, root) on a lower-priority
@ControllerAdvice
bean.
Last but not least, an @ExceptionHandler
method implementation can choose to back
out of dealing with a given exception instance by rethrowing it in its original form.
This is useful in scenarios where you are interested only in root-level matches or in
matches within a specific context that cannot be statically determined. A rethrown
exception is propagated through the remaining resolution chain, as though
the given @ExceptionHandler
method would not have matched in the first place.
Support for @ExceptionHandler
methods in Spring MVC is built on the DispatcherServlet
level, HandlerExceptionResolver mechanism.
Method Arguments
@ExceptionHandler
methods support the following arguments:
Method argument | Description |
---|---|
Exception type |
For access to the raised exception. |
|
For access to the controller method that raised the exception. |
|
Generic access to request parameters and request and session attributes without direct |
|
Choose any specific request or response type (for example, |
|
Enforces the presence of a session. As a consequence, such an argument is never |
|
Currently authenticated user — possibly a specific |
|
The HTTP method of the request. |
|
The current request locale, determined by the most specific |
|
The time zone associated with the current request, as determined by a |
|
For access to the raw response body, as exposed by the Servlet API. |
|
For access to the model for an error response. Always empty. |
|
Specify attributes to use in case of a redirect — (that is to be appended to the query |
|
For access to any session attribute, in contrast to model attributes stored in the |
|
For access to request attributes. See |
Return Values
@ExceptionHandler
methods support the following return values:
Return value | Description |
---|---|
|
The return value is converted through |
|
The return value specifies that the full response (including the HTTP headers and the body) |
|
To render an RFC 7807 error response with details in the body, |
|
To render an RFC 7807 error response with details in the body, |
|
A view name to be resolved with |
|
A |
|
Attributes to be added to the implicit model with the view name implicitly determined |
|
An attribute to be added to the model with the view name implicitly determined through Note that |
|
The view and model attributes to use and, optionally, a response status. |
|
A method with a If none of the above is true, a |
Any other return value |
If a return value is not matched to any of the above and is not a simple type (as determined by |
1.3.7. Controller Advice
@ExceptionHandler
, @InitBinder
, and @ModelAttribute
methods apply only to the
@Controller
class, or class hierarchy, in which they are declared. If, instead, they
are declared in an @ControllerAdvice
or @RestControllerAdvice
class, then they apply
to any controller. Moreover, as of 5.3, @ExceptionHandler
methods in @ControllerAdvice
can be used to handle exceptions from any @Controller
or any other handler.
@ControllerAdvice
is meta-annotated with @Component
and therefore can be registered as
a Spring bean through component scanning. @RestControllerAdvice
is meta-annotated with @ControllerAdvice
and @ResponseBody
, and that means @ExceptionHandler
methods will have their return
value rendered via response body message conversion, rather than via HTML views.
On startup, RequestMappingHandlerMapping
and ExceptionHandlerExceptionResolver
detect
controller advice beans and apply them at runtime. Global @ExceptionHandler
methods,
from an @ControllerAdvice
, are applied after local ones, from the @Controller
.
By contrast, global @ModelAttribute
and @InitBinder
methods are applied before local ones.
The @ControllerAdvice
annotation has attributes that let you narrow the set of controllers
and handlers that they apply to. For example:
Java
// Target all Controllers annotated with @RestController
@ControllerAdvice(annotations = RestController.class)
public class ExampleAdvice1 {}
// Target all Controllers within specific packages
@ControllerAdvice("org.example.controllers")
public class ExampleAdvice2 {}
// Target all Controllers assignable to specific classes
@ControllerAdvice(assignableTypes = {ControllerInterface.class, AbstractController.class})
public class ExampleAdvice3 {}
Kotlin
// Target all Controllers annotated with @RestController
@ControllerAdvice(annotations = [RestController::class])
class ExampleAdvice1
// Target all Controllers within specific packages
@ControllerAdvice("org.example.controllers")
class ExampleAdvice2
// Target all Controllers assignable to specific classes
@ControllerAdvice(assignableTypes = [ControllerInterface::class, AbstractController::class])
class ExampleAdvice3
The selectors in the preceding example are evaluated at runtime and may negatively impact
performance if used extensively. See the
@ControllerAdvice
javadoc for more details.
1.4. Functional Endpoints
Spring Web MVC includes WebMvc.fn, a lightweight functional programming model in which functions
are used to route and handle requests and contracts are designed for immutability.
It is an alternative to the annotation-based programming model but otherwise runs on
the same DispatcherServlet.
1.4.1. Overview
In WebMvc.fn, an HTTP request is handled with a HandlerFunction
: a function that takes
ServerRequest
and returns a ServerResponse
.
Both the request and the response object have immutable contracts that offer JDK 8-friendly
access to the HTTP request and response.
HandlerFunction
is the equivalent of the body of a @RequestMapping
method in the
annotation-based programming model.
Incoming requests are routed to a handler function with a RouterFunction
: a function that
takes ServerRequest
and returns an optional HandlerFunction
(i.e. Optional<HandlerFunction>
).
When the router function matches, a handler function is returned; otherwise an empty Optional.
RouterFunction
is the equivalent of a @RequestMapping
annotation, but with the major
difference that router functions provide not just data, but also behavior.
RouterFunctions.route()
provides a router builder that facilitates the creation of routers,
as the following example shows:
Java
import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.web.servlet.function.RequestPredicates.*;
import static org.springframework.web.servlet.function.RouterFunctions.route;
PersonRepository repository = ...
PersonHandler handler = new PersonHandler(repository);
RouterFunction<ServerResponse> route = route() (1)
.GET("/person/{id}", accept(APPLICATION_JSON), handler::getPerson)
.GET("/person", accept(APPLICATION_JSON), handler::listPeople)
.POST("/person", handler::createPerson)
.build();
public class PersonHandler {
// ...
public ServerResponse listPeople(ServerRequest request) {
// ...
}
public ServerResponse createPerson(ServerRequest request) {
// ...
}
public ServerResponse getPerson(ServerRequest request) {
// ...
}
}
1 | Create router using route() . |
Kotlin
import org.springframework.web.servlet.function.router
val repository: PersonRepository = ...
val handler = PersonHandler(repository)
val route = router { (1)
accept(APPLICATION_JSON).nest {
GET("/person/{id}", handler::getPerson)
GET("/person", handler::listPeople)
}
POST("/person", handler::createPerson)
}
class PersonHandler(private val repository: PersonRepository) {
// ...
fun listPeople(request: ServerRequest): ServerResponse {
// ...
}
fun createPerson(request: ServerRequest): ServerResponse {
// ...
}
fun getPerson(request: ServerRequest): ServerResponse {
// ...
}
}
1 | Create router using the router DSL. |
If you register the RouterFunction
as a bean, for instance by exposing it in a
@Configuration
class, it will be auto-detected by the servlet, as explained in Running a Server.
1.4.2. HandlerFunction
ServerRequest
and ServerResponse
are immutable interfaces that offer JDK 8-friendly
access to the HTTP request and response, including headers, body, method, and status code.
ServerRequest
ServerRequest
provides access to the HTTP method, URI, headers, and query parameters,
while access to the body is provided through the body
methods.
The following example extracts the request body to a String
:
Java
String string = request.body(String.class);
Kotlin
val string = request.body<String>()
The following example extracts the body to a List<Person>
,
where Person
objects are decoded from a serialized form, such as JSON or XML:
Java
List<Person> people = request.body(new ParameterizedTypeReference<List<Person>>() {});
Kotlin
val people = request.body<Person>()
The following example shows how to access parameters:
Java
MultiValueMap<String, String> params = request.params();
Kotlin
val map = request.params()
ServerResponse
ServerResponse
provides access to the HTTP response and, since it is immutable, you can use
a build
method to create it. You can use the builder to set the response status, to add response
headers, or to provide a body. The following example creates a 200 (OK) response with JSON
content:
Java
Person person = ...
ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).body(person);
Kotlin
val person: Person = ...
ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).body(person)
The following example shows how to build a 201 (CREATED) response with a Location
header and no body:
Java
URI location = ...
ServerResponse.created(location).build();
Kotlin
val location: URI = ...
ServerResponse.created(location).build()
You can also use an asynchronous result as the body, in the form of a CompletableFuture
,
Publisher
, or any other type supported by the ReactiveAdapterRegistry
. For instance:
Java
Mono<Person> person = webClient.get().retrieve().bodyToMono(Person.class);
ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).body(person);
Kotlin
val person = webClient.get().retrieve().awaitBody<Person>()
ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).body(person)
If not just the body, but also the status or headers are based on an asynchronous type,
you can use the static async
method on ServerResponse
, which
accepts CompletableFuture<ServerResponse>
, Publisher<ServerResponse>
, or
any other asynchronous type supported by the ReactiveAdapterRegistry
. For instance:
Java
Mono<ServerResponse> asyncResponse = webClient.get().retrieve().bodyToMono(Person.class)
.map(p -> ServerResponse.ok().header("Name", p.name()).body(p));
ServerResponse.async(asyncResponse);
Server-Sent Events can be provided via the
static sse
method on ServerResponse
. The builder provided by that method
allows you to send Strings, or other objects as JSON. For example:
Java
public RouterFunction<ServerResponse> sse() {
return route(GET("/sse"), request -> ServerResponse.sse(sseBuilder -> {
// Save the sseBuilder object somewhere..
}));
}
// In some other thread, sending a String
sseBuilder.send("Hello world");
// Or an object, which will be transformed into JSON
Person person = ...
sseBuilder.send(person);
// Customize the event by using the other methods
sseBuilder.id("42")
.event("sse event")
.data(person);
// and done at some point
sseBuilder.complete();
Kotlin
fun sse(): RouterFunction<ServerResponse> = router {
GET("/sse") { request -> ServerResponse.sse { sseBuilder ->
// Save the sseBuilder object somewhere..
}
}
// In some other thread, sending a String
sseBuilder.send("Hello world")
// Or an object, which will be transformed into JSON
val person = ...
sseBuilder.send(person)
// Customize the event by using the other methods
sseBuilder.id("42")
.event("sse event")
.data(person)
// and done at some point
sseBuilder.complete()
Handler Classes
We can write a handler function as a lambda, as the following example shows:
Java
HandlerFunction<ServerResponse> helloWorld =
request -> ServerResponse.ok().body("Hello World");
Kotlin
val helloWorld: (ServerRequest) -> ServerResponse =
{ ServerResponse.ok().body("Hello World") }
That is convenient, but in an application we need multiple functions, and multiple inline
lambda’s can get messy.
Therefore, it is useful to group related handler functions together into a handler class, which
has a similar role as @Controller
in an annotation-based application.
For example, the following class exposes a reactive Person
repository:
Java
import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.web.reactive.function.server.ServerResponse.ok;
public class PersonHandler {
private final PersonRepository repository;
public PersonHandler(PersonRepository repository) {
this.repository = repository;
}
public ServerResponse listPeople(ServerRequest request) { (1)
List<Person> people = repository.allPeople();
return ok().contentType(APPLICATION_JSON).body(people);
}
public ServerResponse createPerson(ServerRequest request) throws Exception { (2)
Person person = request.body(Person.class);
repository.savePerson(person);
return ok().build();
}
public ServerResponse getPerson(ServerRequest request) { (3)
int personId = Integer.parseInt(request.pathVariable("id"));
Person person = repository.getPerson(personId);
if (person != null) {
return ok().contentType(APPLICATION_JSON).body(person);
}
else {
return ServerResponse.notFound().build();
}
}
}
1 | listPeople is a handler function that returns all Person objects found in the repository asJSON. |
2 | createPerson is a handler function that stores a new Person contained in the request body. |
3 | getPerson is a handler function that returns a single person, identified by the id pathvariable. We retrieve that Person from the repository and create a JSON response, if it isfound. If it is not found, we return a 404 Not Found response. |
Kotlin
class PersonHandler(private val repository: PersonRepository) {
fun listPeople(request: ServerRequest): ServerResponse { (1)
val people: List<Person> = repository.allPeople()
return ok().contentType(APPLICATION_JSON).body(people);
}
fun createPerson(request: ServerRequest): ServerResponse { (2)
val person = request.body<Person>()
repository.savePerson(person)
return ok().build()
}
fun getPerson(request: ServerRequest): ServerResponse { (3)
val personId = request.pathVariable("id").toInt()
return repository.getPerson(personId)?.let { ok().contentType(APPLICATION_JSON).body(it) }
?: ServerResponse.notFound().build()
}
}
1 | listPeople is a handler function that returns all Person objects found in the repository asJSON. |
2 | createPerson is a handler function that stores a new Person contained in the request body. |
3 | getPerson is a handler function that returns a single person, identified by the id pathvariable. We retrieve that Person from the repository and create a JSON response, if it isfound. If it is not found, we return a 404 Not Found response. |
Validation
A functional endpoint can use Spring’s validation facilities to
apply validation to the request body. For example, given a custom Spring
Validator implementation for a Person
:
Java
public class PersonHandler {
private final Validator validator = new PersonValidator(); (1)
// ...
public ServerResponse createPerson(ServerRequest request) {
Person person = request.body(Person.class);
validate(person); (2)
repository.savePerson(person);
return ok().build();
}
private void validate(Person person) {
Errors errors = new BeanPropertyBindingResult(person, "person");
validator.validate(person, errors);
if (errors.hasErrors()) {
throw new ServerWebInputException(errors.toString()); (3)
}
}
}
1 | Create Validator instance. |
2 | Apply validation. |
3 | Raise exception for a 400 response. |
Kotlin
class PersonHandler(private val repository: PersonRepository) {
private val validator = PersonValidator() (1)
// ...
fun createPerson(request: ServerRequest): ServerResponse {
val person = request.body<Person>()
validate(person) (2)
repository.savePerson(person)
return ok().build()
}
private fun validate(person: Person) {
val errors: Errors = BeanPropertyBindingResult(person, "person")
validator.validate(person, errors)
if (errors.hasErrors()) {
throw ServerWebInputException(errors.toString()) (3)
}
}
}
1 | Create Validator instance. |
2 | Apply validation. |
3 | Raise exception for a 400 response. |
Handlers can also use the standard bean validation API (JSR-303) by creating and injecting
a global Validator
instance based on LocalValidatorFactoryBean
.
See Spring Validation.
1.4.3. RouterFunction
Router functions are used to route the requests to the corresponding HandlerFunction
.
Typically, you do not write router functions yourself, but rather use a method on the
RouterFunctions
utility class to create one.
RouterFunctions.route()
(no parameters) provides you with a fluent builder for creating a router
function, whereas RouterFunctions.route(RequestPredicate, HandlerFunction)
offers a direct way
to create a router.
Generally, it is recommended to use the route()
builder, as it provides
convenient short-cuts for typical mapping scenarios without requiring hard-to-discover
static imports.
For instance, the router function builder offers the method GET(String, HandlerFunction)
to create a mapping for GET requests; and POST(String, HandlerFunction)
for POSTs.
Besides HTTP method-based mapping, the route builder offers a way to introduce additional
predicates when mapping to requests.
For each HTTP method there is an overloaded variant that takes a RequestPredicate
as a
parameter, through which additional constraints can be expressed.
Predicates
You can write your own RequestPredicate
, but the RequestPredicates
utility class
offers commonly used implementations, based on the request path, HTTP method, content-type,
and so on.
The following example uses a request predicate to create a constraint based on the Accept
header:
Java
RouterFunction<ServerResponse> route = RouterFunctions.route()
.GET("/hello-world", accept(MediaType.TEXT_PLAIN),
request -> ServerResponse.ok().body("Hello World")).build();
Kotlin
import org.springframework.web.servlet.function.router
val route = router {
GET("/hello-world", accept(TEXT_PLAIN)) {
ServerResponse.ok().body("Hello World")
}
}
You can compose multiple request predicates together by using:
-
RequestPredicate.and(RequestPredicate)
— both must match. -
RequestPredicate.or(RequestPredicate)
— either can match.
Many of the predicates from RequestPredicates
are composed.
For example, RequestPredicates.GET(String)
is composed from RequestPredicates.method(HttpMethod)
and RequestPredicates.path(String)
.
The example shown above also uses two request predicates, as the builder uses
RequestPredicates.GET
internally, and composes that with the accept
predicate.
Routes
Router functions are evaluated in order: if the first route does not match, the
second is evaluated, and so on.
Therefore, it makes sense to declare more specific routes before general ones.
This is also important when registering router functions as Spring beans, as will
be described later.
Note that this behavior is different from the annotation-based programming model, where the
«most specific» controller method is picked automatically.
When using the router function builder, all defined routes are composed into one
RouterFunction
that is returned from build()
.
There are also other ways to compose multiple router functions together:
-
add(RouterFunction)
on theRouterFunctions.route()
builder -
RouterFunction.and(RouterFunction)
-
RouterFunction.andRoute(RequestPredicate, HandlerFunction)
— shortcut for
RouterFunction.and()
with nestedRouterFunctions.route()
.
The following example shows the composition of four routes:
Java
import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.web.servlet.function.RequestPredicates.*;
PersonRepository repository = ...
PersonHandler handler = new PersonHandler(repository);
RouterFunction<ServerResponse> otherRoute = ...
RouterFunction<ServerResponse> route = route()
.GET("/person/{id}", accept(APPLICATION_JSON), handler::getPerson) (1)
.GET("/person", accept(APPLICATION_JSON), handler::listPeople) (2)
.POST("/person", handler::createPerson) (3)
.add(otherRoute) (4)
.build();
1 | GET /person/{id} with an Accept header that matches JSON is routed toPersonHandler.getPerson |
2 | GET /person with an Accept header that matches JSON is routed toPersonHandler.listPeople |
3 | POST /person with no additional predicates is mapped toPersonHandler.createPerson , and |
4 | otherRoute is a router function that is created elsewhere, and added to the route built. |
Kotlin
import org.springframework.http.MediaType.APPLICATION_JSON
import org.springframework.web.servlet.function.router
val repository: PersonRepository = ...
val handler = PersonHandler(repository);
val otherRoute = router { }
val route = router {
GET("/person/{id}", accept(APPLICATION_JSON), handler::getPerson) (1)
GET("/person", accept(APPLICATION_JSON), handler::listPeople) (2)
POST("/person", handler::createPerson) (3)
}.and(otherRoute) (4)
1 | GET /person/{id} with an Accept header that matches JSON is routed toPersonHandler.getPerson |
2 | GET /person with an Accept header that matches JSON is routed toPersonHandler.listPeople |
3 | POST /person with no additional predicates is mapped toPersonHandler.createPerson , and |
4 | otherRoute is a router function that is created elsewhere, and added to the route built. |
Nested Routes
It is common for a group of router functions to have a shared predicate, for instance a shared
path.
In the example above, the shared predicate would be a path predicate that matches /person
,
used by three of the routes.
When using annotations, you would remove this duplication by using a type-level @RequestMapping
annotation that maps to /person
.
In WebMvc.fn, path predicates can be shared through the path
method on the router function builder.
For instance, the last few lines of the example above can be improved in the following way by using nested routes:
Java
RouterFunction<ServerResponse> route = route()
.path("/person", builder -> builder (1)
.GET("/{id}", accept(APPLICATION_JSON), handler::getPerson)
.GET(accept(APPLICATION_JSON), handler::listPeople)
.POST(handler::createPerson))
.build();
1 | Note that second parameter of path is a consumer that takes the router builder. |
Kotlin
import org.springframework.web.servlet.function.router
val route = router {
"/person".nest { (1)
GET("/{id}", accept(APPLICATION_JSON), handler::getPerson)
GET(accept(APPLICATION_JSON), handler::listPeople)
POST(handler::createPerson)
}
}
Though path-based nesting is the most common, you can nest on any kind of predicate by using
the nest
method on the builder.
The above still contains some duplication in the form of the shared Accept
-header predicate.
We can further improve by using the nest
method together with accept
:
Java
RouterFunction<ServerResponse> route = route()
.path("/person", b1 -> b1
.nest(accept(APPLICATION_JSON), b2 -> b2
.GET("/{id}", handler::getPerson)
.GET(handler::listPeople))
.POST(handler::createPerson))
.build();
Kotlin
import org.springframework.web.servlet.function.router
val route = router {
"/person".nest {
accept(APPLICATION_JSON).nest {
GET("/{id}", handler::getPerson)
GET("", handler::listPeople)
POST(handler::createPerson)
}
}
}
1.4.4. Running a Server
You typically run router functions in a DispatcherHandler
-based setup through the
MVC Config, which uses Spring configuration to declare the
components required to process requests. The MVC Java configuration declares the following
infrastructure components to support functional endpoints:
-
RouterFunctionMapping
: Detects one or moreRouterFunction<?>
beans in the Spring
configuration, orders them, combines them through
RouterFunction.andOther
, and routes requests to the resulting composedRouterFunction
. -
HandlerFunctionAdapter
: Simple adapter that letsDispatcherHandler
invoke
aHandlerFunction
that was mapped to a request.
The preceding components let functional endpoints fit within the DispatcherServlet
request
processing lifecycle and also (potentially) run side by side with annotated controllers, if
any are declared. It is also how functional endpoints are enabled by the Spring Boot Web
starter.
The following example shows a WebFlux Java configuration:
Java
@Configuration
@EnableMvc
public class WebConfig implements WebMvcConfigurer {
@Bean
public RouterFunction<?> routerFunctionA() {
// ...
}
@Bean
public RouterFunction<?> routerFunctionB() {
// ...
}
// ...
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
// configure message conversion...
}
@Override
public void addCorsMappings(CorsRegistry registry) {
// configure CORS...
}
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
// configure view resolution for HTML rendering...
}
}
Kotlin
@Configuration
@EnableMvc
class WebConfig : WebMvcConfigurer {
@Bean
fun routerFunctionA(): RouterFunction<*> {
// ...
}
@Bean
fun routerFunctionB(): RouterFunction<*> {
// ...
}
// ...
override fun configureMessageConverters(converters: List<HttpMessageConverter<*>>) {
// configure message conversion...
}
override fun addCorsMappings(registry: CorsRegistry) {
// configure CORS...
}
override fun configureViewResolvers(registry: ViewResolverRegistry) {
// configure view resolution for HTML rendering...
}
}
1.4.5. Filtering Handler Functions
You can filter handler functions by using the before
, after
, or filter
methods on the routing
function builder.
With annotations, you can achieve similar functionality by using @ControllerAdvice
, a ServletFilter
, or both.
The filter will apply to all routes that are built by the builder.
This means that filters defined in nested routes do not apply to «top-level» routes.
For instance, consider the following example:
Java
RouterFunction<ServerResponse> route = route()
.path("/person", b1 -> b1
.nest(accept(APPLICATION_JSON), b2 -> b2
.GET("/{id}", handler::getPerson)
.GET(handler::listPeople)
.before(request -> ServerRequest.from(request) (1)
.header("X-RequestHeader", "Value")
.build()))
.POST(handler::createPerson))
.after((request, response) -> logResponse(response)) (2)
.build();
1 | The before filter that adds a custom request header is only applied to the two GET routes. |
2 | The after filter that logs the response is applied to all routes, including the nested ones. |
Kotlin
import org.springframework.web.servlet.function.router
val route = router {
"/person".nest {
GET("/{id}", handler::getPerson)
GET(handler::listPeople)
before { (1)
ServerRequest.from(it)
.header("X-RequestHeader", "Value").build()
}
}
POST(handler::createPerson)
after { _, response -> (2)
logResponse(response)
}
}
1 | The before filter that adds a custom request header is only applied to the two GET routes. |
2 | The after filter that logs the response is applied to all routes, including the nested ones. |
The filter
method on the router builder takes a HandlerFilterFunction
: a
function that takes a ServerRequest
and HandlerFunction
and returns a ServerResponse
.
The handler function parameter represents the next element in the chain.
This is typically the handler that is routed to, but it can also be another
filter if multiple are applied.
Now we can add a simple security filter to our route, assuming that we have a SecurityManager
that
can determine whether a particular path is allowed.
The following example shows how to do so:
Java
SecurityManager securityManager = ...
RouterFunction<ServerResponse> route = route()
.path("/person", b1 -> b1
.nest(accept(APPLICATION_JSON), b2 -> b2
.GET("/{id}", handler::getPerson)
.GET(handler::listPeople))
.POST(handler::createPerson))
.filter((request, next) -> {
if (securityManager.allowAccessTo(request.path())) {
return next.handle(request);
}
else {
return ServerResponse.status(UNAUTHORIZED).build();
}
})
.build();
Kotlin
import org.springframework.web.servlet.function.router
val securityManager: SecurityManager = ...
val route = router {
("/person" and accept(APPLICATION_JSON)).nest {
GET("/{id}", handler::getPerson)
GET("", handler::listPeople)
POST(handler::createPerson)
filter { request, next ->
if (securityManager.allowAccessTo(request.path())) {
next(request)
}
else {
status(UNAUTHORIZED).build();
}
}
}
}
The preceding example demonstrates that invoking the next.handle(ServerRequest)
is optional.
We only let the handler function be run when access is allowed.
Besides using the filter
method on the router function builder, it is possible to apply a
filter to an existing router function via RouterFunction.filter(HandlerFilterFunction)
.
CORS support for functional endpoints is provided through a dedicatedCorsFilter .
|
1.5. URI Links
This section describes various options available in the Spring Framework to work with URI’s.
1.5.1. UriComponents
Spring MVC and Spring WebFlux
UriComponentsBuilder
helps to build URI’s from URI templates with variables, as the following example shows:
Java
UriComponents uriComponents = UriComponentsBuilder
.fromUriString("https://example.com/hotels/{hotel}") (1)
.queryParam("q", "{q}") (2)
.encode() (3)
.build(); (4)
URI uri = uriComponents.expand("Westin", "123").toUri(); (5)
1 | Static factory method with a URI template. |
2 | Add or replace URI components. |
3 | Request to have the URI template and URI variables encoded. |
4 | Build a UriComponents . |
5 | Expand variables and obtain the URI . |
Kotlin
val uriComponents = UriComponentsBuilder
.fromUriString("https://example.com/hotels/{hotel}") (1)
.queryParam("q", "{q}") (2)
.encode() (3)
.build() (4)
val uri = uriComponents.expand("Westin", "123").toUri() (5)
1 | Static factory method with a URI template. |
2 | Add or replace URI components. |
3 | Request to have the URI template and URI variables encoded. |
4 | Build a UriComponents . |
5 | Expand variables and obtain the URI . |
The preceding example can be consolidated into one chain and shortened with buildAndExpand
,
as the following example shows:
Java
URI uri = UriComponentsBuilder
.fromUriString("https://example.com/hotels/{hotel}")
.queryParam("q", "{q}")
.encode()
.buildAndExpand("Westin", "123")
.toUri();
Kotlin
val uri = UriComponentsBuilder
.fromUriString("https://example.com/hotels/{hotel}")
.queryParam("q", "{q}")
.encode()
.buildAndExpand("Westin", "123")
.toUri()
You can shorten it further by going directly to a URI (which implies encoding),
as the following example shows:
Java
URI uri = UriComponentsBuilder
.fromUriString("https://example.com/hotels/{hotel}")
.queryParam("q", "{q}")
.build("Westin", "123");
Kotlin
val uri = UriComponentsBuilder
.fromUriString("https://example.com/hotels/{hotel}")
.queryParam("q", "{q}")
.build("Westin", "123")
You can shorten it further still with a full URI template, as the following example shows:
Java
URI uri = UriComponentsBuilder
.fromUriString("https://example.com/hotels/{hotel}?q={q}")
.build("Westin", "123");
Kotlin
val uri = UriComponentsBuilder
.fromUriString("https://example.com/hotels/{hotel}?q={q}")
.build("Westin", "123")
1.5.2. UriBuilder
Spring MVC and Spring WebFlux
UriComponentsBuilder
implements UriBuilder
. You can create a
UriBuilder
, in turn, with a UriBuilderFactory
. Together, UriBuilderFactory
and
UriBuilder
provide a pluggable mechanism to build URIs from URI templates, based on
shared configuration, such as a base URL, encoding preferences, and other details.
You can configure RestTemplate
and WebClient
with a UriBuilderFactory
to customize the preparation of URIs. DefaultUriBuilderFactory
is a default
implementation of UriBuilderFactory
that uses UriComponentsBuilder
internally and
exposes shared configuration options.
The following example shows how to configure a RestTemplate
:
Java
// import org.springframework.web.util.DefaultUriBuilderFactory.EncodingMode;
String baseUrl = "https://example.org";
DefaultUriBuilderFactory factory = new DefaultUriBuilderFactory(baseUrl);
factory.setEncodingMode(EncodingMode.TEMPLATE_AND_VALUES);
RestTemplate restTemplate = new RestTemplate();
restTemplate.setUriTemplateHandler(factory);
Kotlin
// import org.springframework.web.util.DefaultUriBuilderFactory.EncodingMode
val baseUrl = "https://example.org"
val factory = DefaultUriBuilderFactory(baseUrl)
factory.encodingMode = EncodingMode.TEMPLATE_AND_VALUES
val restTemplate = RestTemplate()
restTemplate.uriTemplateHandler = factory
The following example configures a WebClient
:
Java
// import org.springframework.web.util.DefaultUriBuilderFactory.EncodingMode;
String baseUrl = "https://example.org";
DefaultUriBuilderFactory factory = new DefaultUriBuilderFactory(baseUrl);
factory.setEncodingMode(EncodingMode.TEMPLATE_AND_VALUES);
WebClient client = WebClient.builder().uriBuilderFactory(factory).build();
Kotlin
// import org.springframework.web.util.DefaultUriBuilderFactory.EncodingMode
val baseUrl = "https://example.org"
val factory = DefaultUriBuilderFactory(baseUrl)
factory.encodingMode = EncodingMode.TEMPLATE_AND_VALUES
val client = WebClient.builder().uriBuilderFactory(factory).build()
In addition, you can also use DefaultUriBuilderFactory
directly. It is similar to using
UriComponentsBuilder
but, instead of static factory methods, it is an actual instance
that holds configuration and preferences, as the following example shows:
Java
String baseUrl = "https://example.com";
DefaultUriBuilderFactory uriBuilderFactory = new DefaultUriBuilderFactory(baseUrl);
URI uri = uriBuilderFactory.uriString("/hotels/{hotel}")
.queryParam("q", "{q}")
.build("Westin", "123");
Kotlin
val baseUrl = "https://example.com"
val uriBuilderFactory = DefaultUriBuilderFactory(baseUrl)
val uri = uriBuilderFactory.uriString("/hotels/{hotel}")
.queryParam("q", "{q}")
.build("Westin", "123")
1.5.3. URI Encoding
Spring MVC and Spring WebFlux
UriComponentsBuilder
exposes encoding options at two levels:
-
UriComponentsBuilder#encode():
Pre-encodes the URI template first and then strictly encodes URI variables when expanded. -
UriComponents#encode():
Encodes URI components after URI variables are expanded.
Both options replace non-ASCII and illegal characters with escaped octets. However, the first option
also replaces characters with reserved meaning that appear in URI variables.
Consider «;», which is legal in a path but has reserved meaning. The first option replaces «;» with «%3B» in URI variables but not in the URI template. By contrast, the second option never replaces «;», since it is a legal character in a path. |
For most cases, the first option is likely to give the expected result, because it treats URI
variables as opaque data to be fully encoded, while the second option is useful if URI
variables do intentionally contain reserved characters. The second option is also useful
when not expanding URI variables at all since that will also encode anything that
incidentally looks like a URI variable.
The following example uses the first option:
Java
URI uri = UriComponentsBuilder.fromPath("/hotel list/{city}")
.queryParam("q", "{q}")
.encode()
.buildAndExpand("New York", "foo+bar")
.toUri();
// Result is "/hotel%20list/New%20York?q=foo%2Bbar"
Kotlin
val uri = UriComponentsBuilder.fromPath("/hotel list/{city}")
.queryParam("q", "{q}")
.encode()
.buildAndExpand("New York", "foo+bar")
.toUri()
// Result is "/hotel%20list/New%20York?q=foo%2Bbar"
You can shorten the preceding example by going directly to the URI (which implies encoding),
as the following example shows:
Java
URI uri = UriComponentsBuilder.fromPath("/hotel list/{city}")
.queryParam("q", "{q}")
.build("New York", "foo+bar");
Kotlin
val uri = UriComponentsBuilder.fromPath("/hotel list/{city}")
.queryParam("q", "{q}")
.build("New York", "foo+bar")
You can shorten it further still with a full URI template, as the following example shows:
Java
URI uri = UriComponentsBuilder.fromUriString("/hotel list/{city}?q={q}")
.build("New York", "foo+bar");
Kotlin
val uri = UriComponentsBuilder.fromUriString("/hotel list/{city}?q={q}")
.build("New York", "foo+bar")
The WebClient
and the RestTemplate
expand and encode URI templates internally through
the UriBuilderFactory
strategy. Both can be configured with a custom strategy,
as the following example shows:
Java
String baseUrl = "https://example.com";
DefaultUriBuilderFactory factory = new DefaultUriBuilderFactory(baseUrl)
factory.setEncodingMode(EncodingMode.TEMPLATE_AND_VALUES);
// Customize the RestTemplate..
RestTemplate restTemplate = new RestTemplate();
restTemplate.setUriTemplateHandler(factory);
// Customize the WebClient..
WebClient client = WebClient.builder().uriBuilderFactory(factory).build();
Kotlin
val baseUrl = "https://example.com"
val factory = DefaultUriBuilderFactory(baseUrl).apply {
encodingMode = EncodingMode.TEMPLATE_AND_VALUES
}
// Customize the RestTemplate..
val restTemplate = RestTemplate().apply {
uriTemplateHandler = factory
}
// Customize the WebClient..
val client = WebClient.builder().uriBuilderFactory(factory).build()
The DefaultUriBuilderFactory
implementation uses UriComponentsBuilder
internally to
expand and encode URI templates. As a factory, it provides a single place to configure
the approach to encoding, based on one of the below encoding modes:
-
TEMPLATE_AND_VALUES
: UsesUriComponentsBuilder#encode()
, corresponding to
the first option in the earlier list, to pre-encode the URI template and strictly encode URI variables when
expanded. -
VALUES_ONLY
: Does not encode the URI template and, instead, applies strict encoding
to URI variables throughUriUtils#encodeUriVariables
prior to expanding them into the
template. -
URI_COMPONENT
: UsesUriComponents#encode()
, corresponding to the second option in the earlier list, to
encode URI component value after URI variables are expanded. -
NONE
: No encoding is applied.
The RestTemplate
is set to EncodingMode.URI_COMPONENT
for historic
reasons and for backwards compatibility. The WebClient
relies on the default value
in DefaultUriBuilderFactory
, which was changed from EncodingMode.URI_COMPONENT
in
5.0.x to EncodingMode.TEMPLATE_AND_VALUES
in 5.1.
1.5.4. Relative Servlet Requests
You can use ServletUriComponentsBuilder
to create URIs relative to the current request,
as the following example shows:
Java
HttpServletRequest request = ...
// Re-uses scheme, host, port, path, and query string...
URI uri = ServletUriComponentsBuilder.fromRequest(request)
.replaceQueryParam("accountId", "{id}")
.build("123");
Kotlin
val request: HttpServletRequest = ...
// Re-uses scheme, host, port, path, and query string...
val uri = ServletUriComponentsBuilder.fromRequest(request)
.replaceQueryParam("accountId", "{id}")
.build("123")
You can create URIs relative to the context path, as the following example shows:
Java
HttpServletRequest request = ...
// Re-uses scheme, host, port, and context path...
URI uri = ServletUriComponentsBuilder.fromContextPath(request)
.path("/accounts")
.build()
.toUri();
Kotlin
val request: HttpServletRequest = ...
// Re-uses scheme, host, port, and context path...
val uri = ServletUriComponentsBuilder.fromContextPath(request)
.path("/accounts")
.build()
.toUri()
You can create URIs relative to a Servlet (for example, /main/*
),
as the following example shows:
Java
HttpServletRequest request = ...
// Re-uses scheme, host, port, context path, and Servlet mapping prefix...
URI uri = ServletUriComponentsBuilder.fromServletMapping(request)
.path("/accounts")
.build()
.toUri();
Kotlin
val request: HttpServletRequest = ...
// Re-uses scheme, host, port, context path, and Servlet mapping prefix...
val uri = ServletUriComponentsBuilder.fromServletMapping(request)
.path("/accounts")
.build()
.toUri()
As of 5.1, ServletUriComponentsBuilder ignores information from the Forwarded andX-Forwarded-* headers, which specify the client-originated address. Consider using theForwardedHeaderFilter to extract and use or to discardsuch headers. |
1.5.5. Links to Controllers
Spring MVC provides a mechanism to prepare links to controller methods. For example,
the following MVC controller allows for link creation:
Java
@Controller
@RequestMapping("/hotels/{hotel}")
public class BookingController {
@GetMapping("/bookings/{booking}")
public ModelAndView getBooking(@PathVariable Long booking) {
// ...
}
}
Kotlin
@Controller
@RequestMapping("/hotels/{hotel}")
class BookingController {
@GetMapping("/bookings/{booking}")
fun getBooking(@PathVariable booking: Long): ModelAndView {
// ...
}
}
You can prepare a link by referring to the method by name, as the following example shows:
Java
UriComponents uriComponents = MvcUriComponentsBuilder
.fromMethodName(BookingController.class, "getBooking", 21).buildAndExpand(42);
URI uri = uriComponents.encode().toUri();
Kotlin
val uriComponents = MvcUriComponentsBuilder
.fromMethodName(BookingController::class.java, "getBooking", 21).buildAndExpand(42)
val uri = uriComponents.encode().toUri()
In the preceding example, we provide actual method argument values (in this case, the long value: 21
)
to be used as a path variable and inserted into the URL. Furthermore, we provide the
value, 42
, to fill in any remaining URI variables, such as the hotel
variable inherited
from the type-level request mapping. If the method had more arguments, we could supply null for
arguments not needed for the URL. In general, only @PathVariable
and @RequestParam
arguments
are relevant for constructing the URL.
There are additional ways to use MvcUriComponentsBuilder
. For example, you can use a technique
akin to mock testing through proxies to avoid referring to the controller method by name, as the following example shows
(the example assumes static import of MvcUriComponentsBuilder.on
):
Java
UriComponents uriComponents = MvcUriComponentsBuilder
.fromMethodCall(on(BookingController.class).getBooking(21)).buildAndExpand(42);
URI uri = uriComponents.encode().toUri();
Kotlin
val uriComponents = MvcUriComponentsBuilder
.fromMethodCall(on(BookingController::class.java).getBooking(21)).buildAndExpand(42)
val uri = uriComponents.encode().toUri()
Controller method signatures are limited in their design when they are supposed to be usable for link creation with fromMethodCall . Aside from needing a proper parameter signature,there is a technical limitation on the return type (namely, generating a runtime proxy for link builder invocations), so the return type must not be final . In particular,the common String return type for view names does not work here. You should use ModelAndView or even plain Object (with a String return value) instead.
|
The earlier examples use static methods in MvcUriComponentsBuilder
. Internally, they rely
on ServletUriComponentsBuilder
to prepare a base URL from the scheme, host, port,
context path, and servlet path of the current request. This works well in most cases.
However, sometimes, it can be insufficient. For example, you may be outside the context of
a request (such as a batch process that prepares links) or perhaps you need to insert a path
prefix (such as a locale prefix that was removed from the request path and needs to be
re-inserted into links).
For such cases, you can use the static fromXxx
overloaded methods that accept a
UriComponentsBuilder
to use a base URL. Alternatively, you can create an instance of MvcUriComponentsBuilder
with a base URL and then use the instance-based withXxx
methods. For example, the
following listing uses withMethodCall
:
Java
UriComponentsBuilder base = ServletUriComponentsBuilder.fromCurrentContextPath().path("/en");
MvcUriComponentsBuilder builder = MvcUriComponentsBuilder.relativeTo(base);
builder.withMethodCall(on(BookingController.class).getBooking(21)).buildAndExpand(42);
URI uri = uriComponents.encode().toUri();
Kotlin
val base = ServletUriComponentsBuilder.fromCurrentContextPath().path("/en")
val builder = MvcUriComponentsBuilder.relativeTo(base)
builder.withMethodCall(on(BookingController::class.java).getBooking(21)).buildAndExpand(42)
val uri = uriComponents.encode().toUri()
As of 5.1, MvcUriComponentsBuilder ignores information from the Forwarded andX-Forwarded-* headers, which specify the client-originated address. Consider using theForwardedHeaderFilter to extract and use or to discard such headers. |
1.5.6. Links in Views
In views such as Thymeleaf, FreeMarker, or JSP, you can build links to annotated controllers
by referring to the implicitly or explicitly assigned name for each request mapping.
Consider the following example:
Java
@RequestMapping("/people/{id}/addresses")
public class PersonAddressController {
@RequestMapping("/{country}")
public HttpEntity<PersonAddress> getAddress(@PathVariable String country) { ... }
}
Kotlin
@RequestMapping("/people/{id}/addresses")
class PersonAddressController {
@RequestMapping("/{country}")
fun getAddress(@PathVariable country: String): HttpEntity<PersonAddress> { ... }
}
Given the preceding controller, you can prepare a link from a JSP, as follows:
<%@ taglib uri="http://www.springframework.org/tags" prefix="s" %>
...
<a href="${s:mvcUrl('PAC#getAddress').arg(0,'US').buildAndExpand('123')}">Get Address</a>
The preceding example relies on the mvcUrl
function declared in the Spring tag library
(that is, META-INF/spring.tld), but it is easy to define your own function or prepare a
similar one for other templating technologies.
Here is how this works. On startup, every @RequestMapping
is assigned a default name
through HandlerMethodMappingNamingStrategy
, whose default implementation uses the
capital letters of the class and the method name (for example, the getThing
method in
ThingController
becomes «TC#getThing»). If there is a name clash, you can use
@RequestMapping(name="..")
to assign an explicit name or implement your own
HandlerMethodMappingNamingStrategy
.
1.6. Asynchronous Requests
Spring MVC has an extensive integration with Servlet asynchronous request
processing:
-
DeferredResult
andCallable
return values in controller methods provide basic support for a single asynchronous
return value. -
Controllers can stream multiple values, including
SSE and raw data. -
Controllers can use reactive clients and return
reactive types for response handling.
For an overview of how this differs from Spring WebFlux, see the Async Spring MVC compared to WebFlux section below.
1.6.1. DeferredResult
Once the asynchronous request processing feature is enabled
in the Servlet container, controller methods can wrap any supported controller method
return value with DeferredResult
, as the following example shows:
Java
@GetMapping("/quotes")
@ResponseBody
public DeferredResult<String> quotes() {
DeferredResult<String> deferredResult = new DeferredResult<String>();
// Save the deferredResult somewhere..
return deferredResult;
}
// From some other thread...
deferredResult.setResult(result);
Kotlin
@GetMapping("/quotes")
@ResponseBody
fun quotes(): DeferredResult<String> {
val deferredResult = DeferredResult<String>()
// Save the deferredResult somewhere..
return deferredResult
}
// From some other thread...
deferredResult.setResult(result)
The controller can produce the return value asynchronously, from a different thread — for
example, in response to an external event (JMS message), a scheduled task, or other event.
1.6.2. Callable
A controller can wrap any supported return value with java.util.concurrent.Callable
,
as the following example shows:
Java
@PostMapping
public Callable<String> processUpload(final MultipartFile file) {
return () -> "someView";
}
Kotlin
@PostMapping
fun processUpload(file: MultipartFile) = Callable<String> {
// ...
"someView"
}
The return value can then be obtained by running the given task through the
configured TaskExecutor
.
1.6.3. Processing
Here is a very concise overview of Servlet asynchronous request processing:
-
A
ServletRequest
can be put in asynchronous mode by callingrequest.startAsync()
.
The main effect of doing so is that the Servlet (as well as any filters) can exit, but
the response remains open to let processing complete later. -
The call to
request.startAsync()
returnsAsyncContext
, which you can use for
further control over asynchronous processing. For example, it provides thedispatch
method,
which is similar to a forward from the Servlet API, except that it lets an
application resume request processing on a Servlet container thread. -
The
ServletRequest
provides access to the currentDispatcherType
, which you can
use to distinguish between processing the initial request, an asynchronous
dispatch, a forward, and other dispatcher types.
DeferredResult
processing works as follows:
-
The controller returns a
DeferredResult
and saves it in some in-memory
queue or list where it can be accessed. -
Spring MVC calls
request.startAsync()
. -
Meanwhile, the
DispatcherServlet
and all configured filters exit the request
processing thread, but the response remains open. -
The application sets the
DeferredResult
from some thread, and Spring MVC
dispatches the request back to the Servlet container. -
The
DispatcherServlet
is invoked again, and processing resumes with the
asynchronously produced return value.
Callable
processing works as follows:
-
The controller returns a
Callable
. -
Spring MVC calls
request.startAsync()
and submits theCallable
to
aTaskExecutor
for processing in a separate thread. -
Meanwhile, the
DispatcherServlet
and all filters exit the Servlet container thread,
but the response remains open. -
Eventually the
Callable
produces a result, and Spring MVC dispatches the request back
to the Servlet container to complete processing. -
The
DispatcherServlet
is invoked again, and processing resumes with the
asynchronously produced return value from theCallable
.
For further background and context, you can also read
the
blog posts that introduced asynchronous request processing support in Spring MVC 3.2.
Exception Handling
When you use a DeferredResult
, you can choose whether to call setResult
or
setErrorResult
with an exception. In both cases, Spring MVC dispatches the request back
to the Servlet container to complete processing. It is then treated either as if the
controller method returned the given value or as if it produced the given exception.
The exception then goes through the regular exception handling mechanism (for example, invoking
@ExceptionHandler
methods).
When you use Callable
, similar processing logic occurs, the main difference being that
the result is returned from the Callable
or an exception is raised by it.
Interception
HandlerInterceptor
instances can be of type AsyncHandlerInterceptor
, to receive the
afterConcurrentHandlingStarted
callback on the initial request that starts asynchronous
processing (instead of postHandle
and afterCompletion
).
HandlerInterceptor
implementations can also register a CallableProcessingInterceptor
or a DeferredResultProcessingInterceptor
, to integrate more deeply with the
lifecycle of an asynchronous request (for example, to handle a timeout event). See
AsyncHandlerInterceptor
for more details.
DeferredResult
provides onTimeout(Runnable)
and onCompletion(Runnable)
callbacks.
See the javadoc of DeferredResult
for more details. Callable
can be substituted for WebAsyncTask
that exposes additional
methods for timeout and completion callbacks.
Async Spring MVC compared to WebFlux
The Servlet API was originally built for making a single pass through the Filter-Servlet
chain. Asynchronous request processing lets applications exit the Filter-Servlet chain
but leave the response open for further processing. The Spring MVC asynchronous support
is built around that mechanism. When a controller returns a DeferredResult
, the
Filter-Servlet chain is exited, and the Servlet container thread is released. Later, when
the DeferredResult
is set, an ASYNC
dispatch (to the same URL) is made, during which the
controller is mapped again but, rather than invoking it, the DeferredResult
value is used
(as if the controller returned it) to resume processing.
By contrast, Spring WebFlux is neither built on the Servlet API, nor does it need such an
asynchronous request processing feature, because it is asynchronous by design. Asynchronous
handling is built into all framework contracts and is intrinsically supported through all
stages of request processing.
From a programming model perspective, both Spring MVC and Spring WebFlux support
asynchronous and Reactive Types as return values in controller methods.
Spring MVC even supports streaming, including reactive back pressure. However, individual
writes to the response remain blocking (and are performed on a separate thread), unlike WebFlux,
which relies on non-blocking I/O and does not need an extra thread for each write.
Another fundamental difference is that Spring MVC does not support asynchronous or reactive
types in controller method arguments (for example, @RequestBody
, @RequestPart
, and others),
nor does it have any explicit support for asynchronous and reactive types as model attributes.
Spring WebFlux does support all that.
Finally, from a configuration perspective the asynchronous request processing feature must be
enabled at the Servlet container level.
1.6.4. HTTP Streaming
You can use DeferredResult
and Callable
for a single asynchronous return value.
What if you want to produce multiple asynchronous values and have those written to the
response? This section describes how to do so.
Objects
You can use the ResponseBodyEmitter
return value to produce a stream of objects, where
each object is serialized with an
HttpMessageConverter
and written to the
response, as the following example shows:
Java
@GetMapping("/events")
public ResponseBodyEmitter handle() {
ResponseBodyEmitter emitter = new ResponseBodyEmitter();
// Save the emitter somewhere..
return emitter;
}
// In some other thread
emitter.send("Hello once");
// and again later on
emitter.send("Hello again");
// and done at some point
emitter.complete();
Kotlin
@GetMapping("/events")
fun handle() = ResponseBodyEmitter().apply {
// Save the emitter somewhere..
}
// In some other thread
emitter.send("Hello once")
// and again later on
emitter.send("Hello again")
// and done at some point
emitter.complete()
You can also use ResponseBodyEmitter
as the body in a ResponseEntity
, letting you
customize the status and headers of the response.
When an emitter
throws an IOException
(for example, if the remote client went away), applications
are not responsible for cleaning up the connection and should not invoke emitter.complete
or emitter.completeWithError
. Instead, the servlet container automatically initiates an
AsyncListener
error notification, in which Spring MVC makes a completeWithError
call.
This call, in turn, performs one final ASYNC
dispatch to the application, during which Spring MVC
invokes the configured exception resolvers and completes the request.
SSE
SseEmitter
(a subclass of ResponseBodyEmitter
) provides support for
Server-Sent Events, where events sent from the server
are formatted according to the W3C SSE specification. To produce an SSE
stream from a controller, return SseEmitter
, as the following example shows:
Java
@GetMapping(path="/events", produces=MediaType.TEXT_EVENT_STREAM_VALUE)
public SseEmitter handle() {
SseEmitter emitter = new SseEmitter();
// Save the emitter somewhere..
return emitter;
}
// In some other thread
emitter.send("Hello once");
// and again later on
emitter.send("Hello again");
// and done at some point
emitter.complete();
Kotlin
@GetMapping("/events", produces = [MediaType.TEXT_EVENT_STREAM_VALUE])
fun handle() = SseEmitter().apply {
// Save the emitter somewhere..
}
// In some other thread
emitter.send("Hello once")
// and again later on
emitter.send("Hello again")
// and done at some point
emitter.complete()
While SSE is the main option for streaming into browsers, note that Internet Explorer
does not support Server-Sent Events. Consider using Spring’s
WebSocket messaging with
SockJS fallback transports (including SSE) that target
a wide range of browsers.
See also previous section for notes on exception handling.
Raw Data
Sometimes, it is useful to bypass message conversion and stream directly to the response
OutputStream
(for example, for a file download). You can use the StreamingResponseBody
return value type to do so, as the following example shows:
Java
@GetMapping("/download")
public StreamingResponseBody handle() {
return new StreamingResponseBody() {
@Override
public void writeTo(OutputStream outputStream) throws IOException {
// write...
}
};
}
Kotlin
@GetMapping("/download")
fun handle() = StreamingResponseBody {
// write...
}
You can use StreamingResponseBody
as the body in a ResponseEntity
to
customize the status and headers of the response.
1.6.5. Reactive Types
Spring MVC supports use of reactive client libraries in a controller (also read
Reactive Libraries in the WebFlux section).
This includes the WebClient
from spring-webflux
and others, such as Spring Data
reactive data repositories. In such scenarios, it is convenient to be able to return
reactive types from the controller method.
Reactive return values are handled as follows:
-
A single-value promise is adapted to, similar to using
DeferredResult
. Examples
includeMono
(Reactor) orSingle
(RxJava). -
A multi-value stream with a streaming media type (such as
application/x-ndjson
ortext/event-stream
) is adapted to, similar to usingResponseBodyEmitter
or
SseEmitter
. Examples includeFlux
(Reactor) orObservable
(RxJava).
Applications can also returnFlux<ServerSentEvent>
orObservable<ServerSentEvent>
. -
A multi-value stream with any other media type (such as
application/json
) is adapted
to, similar to usingDeferredResult<List<?>>
.
Spring MVC supports Reactor and RxJava through theReactiveAdapterRegistry fromspring-core , which lets it adapt from multiple reactive libraries.
|
For streaming to the response, reactive back pressure is supported, but writes to the
response are still blocking and are run on a separate thread through the
configured TaskExecutor
, to avoid
blocking the upstream source (such as a Flux
returned from WebClient
).
By default, SimpleAsyncTaskExecutor
is used for the blocking writes, but that is not
suitable under load. If you plan to stream with a reactive type, you should use the
MVC configuration to configure a task executor.
1.6.6. Context Propagation
It is common to propagate context via java.lang.ThreadLocal
. This works transparently
for handling on the same thread, but requires additional work for asynchronous handling
across multiple threads. The Micrometer
Context Propagation
library simplifies context propagation across threads, and across context mechanisms such
as ThreadLocal
values,
Reactor context,
GraphQL Java context,
and others.
If Micrometer Context Propagation is present on the classpath, when a controller method
returns a reactive type such as Flux
or Mono
, all
ThreadLocal
values, for which there is a registered io.micrometer.ThreadLocalAccessor
,
are written to the Reactor Context
as key-value pairs, using the key assigned by the
ThreadLocalAccessor
.
For other asynchronous handling scenarios, you can use the Context Propagation library
directly. For example:
Java
// Capture ThreadLocal values from the main thread ...
ContextSnapshot snapshot = ContextSnapshot.captureAll();
// On a different thread: restore ThreadLocal values
try (ContextSnapshot.Scope scoped = snapshot.setThreadLocals()) {
// ...
}
For more details, see the
documentation of the Micrometer Context
Propagation library.
1.6.7. Disconnects
The Servlet API does not provide any notification when a remote client goes away.
Therefore, while streaming to the response, whether through SseEmitter
or reactive types, it is important to send data periodically,
since the write fails if the client has disconnected. The send could take the form of an
empty (comment-only) SSE event or any other data that the other side would have to interpret
as a heartbeat and ignore.
Alternatively, consider using web messaging solutions (such as
STOMP over WebSocket or WebSocket with SockJS)
that have a built-in heartbeat mechanism.
1.6.8. Configuration
The asynchronous request processing feature must be enabled at the Servlet container level.
The MVC configuration also exposes several options for asynchronous requests.
Servlet Container
Filter and Servlet declarations have an asyncSupported
flag that needs to be set to true
to enable asynchronous request processing. In addition, Filter mappings should be
declared to handle the ASYNC
jakarta.servlet.DispatchType
.
In Java configuration, when you use AbstractAnnotationConfigDispatcherServletInitializer
to initialize the Servlet container, this is done automatically.
In web.xml
configuration, you can add <async-supported>true</async-supported>
to the
DispatcherServlet
and to Filter
declarations and add
<dispatcher>ASYNC</dispatcher>
to filter mappings.
Spring MVC
The MVC configuration exposes the following options related to asynchronous request processing:
-
Java configuration: Use the
configureAsyncSupport
callback onWebMvcConfigurer
. -
XML namespace: Use the
<async-support>
element under<mvc:annotation-driven>
.
You can configure the following:
-
Default timeout value for async requests, which if not set, depends
on the underlying Servlet container. -
AsyncTaskExecutor
to use for blocking writes when streaming with
Reactive Types and for executingCallable
instances returned from
controller methods. We highly recommended configuring this property if you
stream with reactive types or have controller methods that returnCallable
, since
by default, it is aSimpleAsyncTaskExecutor
. -
DeferredResultProcessingInterceptor
implementations andCallableProcessingInterceptor
implementations.
Note that you can also set the default timeout value on a DeferredResult
,
a ResponseBodyEmitter
, and an SseEmitter
. For a Callable
, you can use
WebAsyncTask
to provide a timeout value.
1.7. CORS
Spring MVC lets you handle CORS (Cross-Origin Resource Sharing). This section
describes how to do so.
1.7.1. Introduction
For security reasons, browsers prohibit AJAX calls to resources outside the current origin.
For example, you could have your bank account in one tab and evil.com in another. Scripts
from evil.com should not be able to make AJAX requests to your bank API with your
credentials — for example withdrawing money from your account!
Cross-Origin Resource Sharing (CORS) is a W3C specification
implemented by most browsers that lets you specify
what kind of cross-domain requests are authorized, rather than using less secure and less
powerful workarounds based on IFRAME or JSONP.
1.7.2. Processing
The CORS specification distinguishes between preflight, simple, and actual requests.
To learn how CORS works, you can read
this article, among
many others, or see the specification for more details.
Spring MVC HandlerMapping
implementations provide built-in support for CORS. After successfully
mapping a request to a handler, HandlerMapping
implementations check the CORS configuration for the
given request and handler and take further actions. Preflight requests are handled
directly, while simple and actual CORS requests are intercepted, validated, and have
required CORS response headers set.
In order to enable cross-origin requests (that is, the Origin
header is present and
differs from the host of the request), you need to have some explicitly declared CORS
configuration. If no matching CORS configuration is found, preflight requests are
rejected. No CORS headers are added to the responses of simple and actual CORS requests
and, consequently, browsers reject them.
Each HandlerMapping
can be
configured
individually with URL pattern-based CorsConfiguration
mappings. In most cases, applications
use the MVC Java configuration or the XML namespace to declare such mappings, which results
in a single global map being passed to all HandlerMapping
instances.
You can combine global CORS configuration at the HandlerMapping
level with more
fine-grained, handler-level CORS configuration. For example, annotated controllers can use
class- or method-level @CrossOrigin
annotations (other handlers can implement
CorsConfigurationSource
).
The rules for combining global and local configuration are generally additive — for example,
all global and all local origins. For those attributes where only a single value can be
accepted, e.g. allowCredentials
and maxAge
, the local overrides the global value. See
CorsConfiguration#combine(CorsConfiguration)
for more details.
To learn more from the source or make advanced customizations, check the code behind:
|
1.7.3. @CrossOrigin
The @CrossOrigin
annotation enables cross-origin requests on annotated controller methods,
as the following example shows:
Java
@RestController
@RequestMapping("/account")
public class AccountController {
@CrossOrigin
@GetMapping("/{id}")
public Account retrieve(@PathVariable Long id) {
// ...
}
@DeleteMapping("/{id}")
public void remove(@PathVariable Long id) {
// ...
}
}
Kotlin
@RestController
@RequestMapping("/account")
class AccountController {
@CrossOrigin
@GetMapping("/{id}")
fun retrieve(@PathVariable id: Long): Account {
// ...
}
@DeleteMapping("/{id}")
fun remove(@PathVariable id: Long) {
// ...
}
}
By default, @CrossOrigin
allows:
-
All origins.
-
All headers.
-
All HTTP methods to which the controller method is mapped.
allowCredentials
is not enabled by default, since that establishes a trust level
that exposes sensitive user-specific information (such as cookies and CSRF tokens) and
should only be used where appropriate. When it is enabled either allowOrigins
must be
set to one or more specific domain (but not the special value "*"
) or alternatively
the allowOriginPatterns
property may be used to match to a dynamic set of origins.
maxAge
is set to 30 minutes.
@CrossOrigin
is supported at the class level, too, and is inherited by all methods,
as the following example shows:
Java
@CrossOrigin(origins = "https://domain2.com", maxAge = 3600)
@RestController
@RequestMapping("/account")
public class AccountController {
@GetMapping("/{id}")
public Account retrieve(@PathVariable Long id) {
// ...
}
@DeleteMapping("/{id}")
public void remove(@PathVariable Long id) {
// ...
}
}
Kotlin
@CrossOrigin(origins = ["https://domain2.com"], maxAge = 3600)
@RestController
@RequestMapping("/account")
class AccountController {
@GetMapping("/{id}")
fun retrieve(@PathVariable id: Long): Account {
// ...
}
@DeleteMapping("/{id}")
fun remove(@PathVariable id: Long) {
// ...
}
You can use @CrossOrigin
at both the class level and the method level,
as the following example shows:
Java
@CrossOrigin(maxAge = 3600)
@RestController
@RequestMapping("/account")
public class AccountController {
@CrossOrigin("https://domain2.com")
@GetMapping("/{id}")
public Account retrieve(@PathVariable Long id) {
// ...
}
@DeleteMapping("/{id}")
public void remove(@PathVariable Long id) {
// ...
}
}
Kotlin
@CrossOrigin(maxAge = 3600)
@RestController
@RequestMapping("/account")
class AccountController {
@CrossOrigin("https://domain2.com")
@GetMapping("/{id}")
fun retrieve(@PathVariable id: Long): Account {
// ...
}
@DeleteMapping("/{id}")
fun remove(@PathVariable id: Long) {
// ...
}
}
1.7.4. Global Configuration
In addition to fine-grained, controller method level configuration, you probably want to
define some global CORS configuration, too. You can set URL-based CorsConfiguration
mappings individually on any HandlerMapping
. Most applications, however, use the
MVC Java configuration or the MVC XML namespace to do that.
By default, global configuration enables the following:
-
All origins.
-
All headers.
-
GET
,HEAD
, andPOST
methods.
allowCredentials
is not enabled by default, since that establishes a trust level
that exposes sensitive user-specific information (such as cookies and CSRF tokens) and
should only be used where appropriate. When it is enabled either allowOrigins
must be
set to one or more specific domain (but not the special value "*"
) or alternatively
the allowOriginPatterns
property may be used to match to a dynamic set of origins.
maxAge
is set to 30 minutes.
Java Configuration
To enable CORS in the MVC Java config, you can use the CorsRegistry
callback,
as the following example shows:
Java
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("https://domain2.com")
.allowedMethods("PUT", "DELETE")
.allowedHeaders("header1", "header2", "header3")
.exposedHeaders("header1", "header2")
.allowCredentials(true).maxAge(3600);
// Add more mappings...
}
}
Kotlin
@Configuration
@EnableWebMvc
class WebConfig : WebMvcConfigurer {
override fun addCorsMappings(registry: CorsRegistry) {
registry.addMapping("/api/**")
.allowedOrigins("https://domain2.com")
.allowedMethods("PUT", "DELETE")
.allowedHeaders("header1", "header2", "header3")
.exposedHeaders("header1", "header2")
.allowCredentials(true).maxAge(3600)
// Add more mappings...
}
}
XML Configuration
To enable CORS in the XML namespace, you can use the <mvc:cors>
element,
as the following example shows:
<mvc:cors>
<mvc:mapping path="/api/**"
allowed-origins="https://domain1.com, https://domain2.com"
allowed-methods="GET, PUT"
allowed-headers="header1, header2, header3"
exposed-headers="header1, header2" allow-credentials="true"
max-age="123" />
<mvc:mapping path="/resources/**"
allowed-origins="https://domain1.com" />
</mvc:cors>
1.7.5. CORS Filter
You can apply CORS support through the built-in
CorsFilter
.
If you try to use the CorsFilter with Spring Security, keep in mind that SpringSecurity has built-in support for CORS. |
To configure the filter, pass a CorsConfigurationSource
to its constructor, as the
following example shows:
Java
CorsConfiguration config = new CorsConfiguration();
// Possibly...
// config.applyPermitDefaultValues()
config.setAllowCredentials(true);
config.addAllowedOrigin("https://domain1.com");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
CorsFilter filter = new CorsFilter(source);
Kotlin
val config = CorsConfiguration()
// Possibly...
// config.applyPermitDefaultValues()
config.allowCredentials = true
config.addAllowedOrigin("https://domain1.com")
config.addAllowedHeader("*")
config.addAllowedMethod("*")
val source = UrlBasedCorsConfigurationSource()
source.registerCorsConfiguration("/**", config)
val filter = CorsFilter(source)
1.8. Error Responses
A common requirement for REST services is to include details in the body of error
responses. The Spring Framework supports the «Problem Details for HTTP APIs»
specification, RFC 7807.
The following are the main abstractions for this support:
-
ProblemDetail
— representation for an RFC 7807 problem detail; a simple container
for both standard fields defined in the spec, and for non-standard ones. -
ErrorResponse
— contract to expose HTTP error response details including HTTP
status, response headers, and a body in the format of RFC 7807; this allows exceptions to
encapsulate and expose the details of how they map to an HTTP response. All Spring MVC
exceptions implement this. -
ErrorResponseException
— basicErrorResponse
implementation that others
can use as a convenient base class. -
ResponseEntityExceptionHandler
— convenient base class for an
@ControllerAdvice that handles all Spring MVC exceptions,
and anyErrorResponseException
, and renders an error response with a body.
1.8.1. Render
You can return ProblemDetail
or ErrorResponse
from any @ExceptionHandler
or from
any @RequestMapping
method to render an RFC 7807 response. This is processed as follows:
-
The
status
property ofProblemDetail
determines the HTTP status. -
The
instance
property ofProblemDetail
is set from the current URL path, if not
already set. -
For content negotiation, the Jackson
HttpMessageConverter
prefers
«application/problem+json» over «application/json» when rendering aProblemDetail
,
and also falls back on it if no compatible media type is found.
To enable RFC 7807 responses for Spring WebFlux exceptions and for any
ErrorResponseException
, extend ResponseEntityExceptionHandler
and declare it as an
@ControllerAdvice in Spring configuration. The handler
has an @ExceptionHandler
method that handles any ErrorResponse
exception, which
includes all built-in web exceptions. You can add more exception handling methods, and
use a protected method to map any exception to a ProblemDetail
.
1.8.2. Non-Standard Fields
You can extend an RFC 7807 response with non-standard fields in one of two ways.
One, insert into the «properties» Map
of ProblemDetail
. When using the Jackson
library, the Spring Framework registers ProblemDetailJacksonMixin
that ensures this
«properties» Map
is unwrapped and rendered as top level JSON properties in the
response, and likewise any unknown property during deserialization is inserted into
this Map
.
You can also extend ProblemDetail
to add dedicated non-standard properties.
The copy constructor in ProblemDetail
allows a subclass to make it easy to be created
from an existing ProblemDetail
. This could be done centrally, e.g. from an
@ControllerAdvice
such as ResponseEntityExceptionHandler
that re-creates the
ProblemDetail
of an exception into a subclass with the additional non-standard fields.
1.8.3. Internationalization
It is a common requirement to internationalize error response details, and good practice
to customize the problem details for Spring MVC exceptions. This is supported as follows:
-
Each
ErrorResponse
exposes a message code and arguments to resolve the «detail» field
through a MessageSource.
The actual message code value is parameterized with placeholders, e.g.
"HTTP method {0} not supported"
to be expanded from the arguments. -
Each
ErrorResponse
also exposes a message code to resolve the «title» field. -
ResponseEntityExceptionHandler
uses the message code and arguments to resolve the
«detail» and the «title» fields.
By default, the message code for the «detail» field is «problemDetail.» + the fully
qualified exception class name. Some exceptions may expose additional message codes in
which case a suffix is added to the default message code. The table below lists message
arguments and codes for Spring MVC exceptions:
Exception | Message Code | Message Code Arguments |
---|---|---|
|
(default) |
|
|
(default) |
|
|
(default) |
|
|
(default) + «.parseError» |
|
|
(default) |
|
|
(default) + «.parseError» |
|
|
(default) |
|
|
(default) |
|
|
(default) |
|
|
(default) |
|
|
(default) |
|
|
(default) |
|
|
(default) |
|
|
(default) |
|
|
(default) |
|
|
(default) |
|
|
(default) |
|
|
(default) |
|
|
(default) |
|
By default, the message code for the «title» field is «problemDetail.title.» + the fully
qualified exception class name.
1.8.4. Client Handling
A client application can catch WebClientResponseException
, when using the WebClient
,
or RestClientResponseException
when using the RestTemplate
, and use their
getResponseBodyAs
methods to decode the error response body to any target type such as
ProblemDetail
, or a subclass of ProblemDetail
.
1.10. HTTP Caching
HTTP caching can significantly improve the performance of a web application. HTTP caching
revolves around the Cache-Control
response header and, subsequently, conditional request
headers (such as Last-Modified
and ETag
). Cache-Control
advises private (for example, browser)
and public (for example, proxy) caches on how to cache and re-use responses. An ETag
header is used
to make a conditional request that may result in a 304 (NOT_MODIFIED) without a body,
if the content has not changed. ETag
can be seen as a more sophisticated successor to
the Last-Modified
header.
This section describes the HTTP caching-related options that are available in Spring Web MVC.
1.10.1. CacheControl
CacheControl
provides support for
configuring settings related to the Cache-Control
header and is accepted as an argument
in a number of places:
-
WebContentInterceptor
-
WebContentGenerator
-
Controllers
-
Static Resources
While RFC 7234 describes all possible
directives for the Cache-Control
response header, the CacheControl
type takes a
use case-oriented approach that focuses on the common scenarios:
Java
// Cache for an hour - "Cache-Control: max-age=3600"
CacheControl ccCacheOneHour = CacheControl.maxAge(1, TimeUnit.HOURS);
// Prevent caching - "Cache-Control: no-store"
CacheControl ccNoStore = CacheControl.noStore();
// Cache for ten days in public and private caches,
// public caches should not transform the response
// "Cache-Control: max-age=864000, public, no-transform"
CacheControl ccCustom = CacheControl.maxAge(10, TimeUnit.DAYS).noTransform().cachePublic();
Kotlin
// Cache for an hour - "Cache-Control: max-age=3600"
val ccCacheOneHour = CacheControl.maxAge(1, TimeUnit.HOURS)
// Prevent caching - "Cache-Control: no-store"
val ccNoStore = CacheControl.noStore()
// Cache for ten days in public and private caches,
// public caches should not transform the response
// "Cache-Control: max-age=864000, public, no-transform"
val ccCustom = CacheControl.maxAge(10, TimeUnit.DAYS).noTransform().cachePublic()
WebContentGenerator
also accepts a simpler cachePeriod
property (defined in seconds) that
works as follows:
-
A
-1
value does not generate aCache-Control
response header. -
A
0
value prevents caching by using the'Cache-Control: no-store'
directive. -
An
n > 0
value caches the given response forn
seconds by using the
'Cache-Control: max-age=n'
directive.
1.10.2. Controllers
Controllers can add explicit support for HTTP caching. We recommended doing so, since the
lastModified
or ETag
value for a resource needs to be calculated before it can be compared
against conditional request headers. A controller can add an ETag
header and Cache-Control
settings to a ResponseEntity
, as the following example shows:
Java
@GetMapping("/book/{id}")
public ResponseEntity<Book> showBook(@PathVariable Long id) {
Book book = findBook(id);
String version = book.getVersion();
return ResponseEntity
.ok()
.cacheControl(CacheControl.maxAge(30, TimeUnit.DAYS))
.eTag(version) // lastModified is also available
.body(book);
}
Kotlin
@GetMapping("/book/{id}")
fun showBook(@PathVariable id: Long): ResponseEntity<Book> {
val book = findBook(id);
val version = book.getVersion()
return ResponseEntity
.ok()
.cacheControl(CacheControl.maxAge(30, TimeUnit.DAYS))
.eTag(version) // lastModified is also available
.body(book)
}
The preceding example sends a 304 (NOT_MODIFIED) response with an empty body if the comparison
to the conditional request headers indicates that the content has not changed. Otherwise, the
ETag
and Cache-Control
headers are added to the response.
You can also make the check against conditional request headers in the controller,
as the following example shows:
Java
@RequestMapping
public String myHandleMethod(WebRequest request, Model model) {
long eTag = ... (1)
if (request.checkNotModified(eTag)) {
return null; (2)
}
model.addAttribute(...); (3)
return "myViewName";
}
1 | Application-specific calculation. |
2 | The response has been set to 304 (NOT_MODIFIED) — no further processing. |
3 | Continue with the request processing. |
Kotlin
@RequestMapping
fun myHandleMethod(request: WebRequest, model: Model): String? {
val eTag: Long = ... (1)
if (request.checkNotModified(eTag)) {
return null (2)
}
model[...] = ... (3)
return "myViewName"
}
1 | Application-specific calculation. |
2 | The response has been set to 304 (NOT_MODIFIED) — no further processing. |
3 | Continue with the request processing. |
There are three variants for checking conditional requests against eTag
values, lastModified
values, or both. For conditional GET
and HEAD
requests, you can set the response to
304 (NOT_MODIFIED). For conditional POST
, PUT
, and DELETE
, you can instead set the response
to 412 (PRECONDITION_FAILED), to prevent concurrent modification.
1.10.3. Static Resources
You should serve static resources with a Cache-Control
and conditional response headers
for optimal performance. See the section on configuring Static Resources.
1.10.4. ETag
Filter
You can use the ShallowEtagHeaderFilter
to add “shallow” eTag
values that are computed from the
response content and, thus, save bandwidth but not CPU time. See Shallow ETag.
1.11. View Technologies
The use of view technologies in Spring MVC is pluggable. Whether you decide to use
Thymeleaf, Groovy Markup Templates, JSPs, or other technologies is primarily a matter of
a configuration change. This chapter covers view technologies integrated with Spring MVC.
We assume you are already familiar with View Resolution.
The views of a Spring MVC application live within the internal trust boundaries of that application. Views have access to all the beans of your application context. As such, it is not recommended to use Spring MVC’s template support in applications where the templates are editable by external sources, since this can have security implications. |
1.11.1. Thymeleaf
Thymeleaf is a modern server-side Java template engine that emphasizes natural HTML
templates that can be previewed in a browser by double-clicking, which is very helpful
for independent work on UI templates (for example, by a designer) without the need for
a running server. If you want to replace JSPs, Thymeleaf offers one of the most
extensive sets of features to make such a transition easier. Thymeleaf is actively
developed and maintained. For a more complete introduction, see the
Thymeleaf project home page.
The Thymeleaf integration with Spring MVC is managed by the Thymeleaf project.
The configuration involves a few bean declarations, such as
ServletContextTemplateResolver
, SpringTemplateEngine
, and ThymeleafViewResolver
.
See Thymeleaf+Spring for more details.
1.11.2. FreeMarker
Apache FreeMarker is a template engine for generating any
kind of text output from HTML to email and others. The Spring Framework has built-in
integration for using Spring MVC with FreeMarker templates.
View Configuration
The following example shows how to configure FreeMarker as a view technology:
Java
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
registry.freeMarker();
}
// Configure FreeMarker...
@Bean
public FreeMarkerConfigurer freeMarkerConfigurer() {
FreeMarkerConfigurer configurer = new FreeMarkerConfigurer();
configurer.setTemplateLoaderPath("/WEB-INF/freemarker");
return configurer;
}
}
Kotlin
@Configuration
@EnableWebMvc
class WebConfig : WebMvcConfigurer {
override fun configureViewResolvers(registry: ViewResolverRegistry) {
registry.freeMarker()
}
// Configure FreeMarker...
@Bean
fun freeMarkerConfigurer() = FreeMarkerConfigurer().apply {
setTemplateLoaderPath("/WEB-INF/freemarker")
}
}
The following example shows how to configure the same in XML:
<mvc:annotation-driven/>
<mvc:view-resolvers>
<mvc:freemarker/>
</mvc:view-resolvers>
<!-- Configure FreeMarker... -->
<mvc:freemarker-configurer>
<mvc:template-loader-path location="/WEB-INF/freemarker"/>
</mvc:freemarker-configurer>
Alternatively, you can also declare the FreeMarkerConfigurer
bean for full control over all
properties, as the following example shows:
<bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPath" value="/WEB-INF/freemarker/"/>
</bean>
Your templates need to be stored in the directory specified by the FreeMarkerConfigurer
shown in the preceding example. Given the preceding configuration, if your controller
returns a view name of welcome
, the resolver looks for the
/WEB-INF/freemarker/welcome.ftl
template.
FreeMarker Configuration
You can pass FreeMarker ‘Settings’ and ‘SharedVariables’ directly to the FreeMarker
Configuration
object (which is managed by Spring) by setting the appropriate bean
properties on the FreeMarkerConfigurer
bean. The freemarkerSettings
property requires
a java.util.Properties
object, and the freemarkerVariables
property requires a
java.util.Map
. The following example shows how to use a FreeMarkerConfigurer
:
<bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPath" value="/WEB-INF/freemarker/"/>
<property name="freemarkerVariables">
<map>
<entry key="xml_escape" value-ref="fmXmlEscape"/>
</map>
</property>
</bean>
<bean id="fmXmlEscape" class="freemarker.template.utility.XmlEscape"/>
See the FreeMarker documentation for details of settings and variables as they apply to
the Configuration
object.
Form Handling
Spring provides a tag library for use in JSPs that contains, among others, a
<spring:bind/>
element. This element primarily lets forms display values from
form-backing objects and show the results of failed validations from a Validator
in the
web or business tier. Spring also has support for the same functionality in FreeMarker,
with additional convenience macros for generating form input elements themselves.
The Bind Macros
A standard set of macros are maintained within the spring-webmvc.jar
file for
FreeMarker, so they are always available to a suitably configured application.
Some of the macros defined in the Spring templating libraries are considered internal
(private), but no such scoping exists in the macro definitions, making all macros visible
to calling code and user templates. The following sections concentrate only on the macros
you need to directly call from within your templates. If you wish to view the macro code
directly, the file is called spring.ftl
and is in the
org.springframework.web.servlet.view.freemarker
package.
Simple Binding
In your HTML forms based on FreeMarker templates that act as a form view for a Spring MVC
controller, you can use code similar to the next example to bind to field values and
display error messages for each input field in similar fashion to the JSP equivalent. The
following example shows a personForm
view:
<!-- FreeMarker macros have to be imported into a namespace.
We strongly recommend sticking to 'spring'. -->
<#import "/spring.ftl" as spring/>
<html>
...
<form action="" method="POST">
Name:
<@spring.bind "personForm.name"/>
<input type="text"
name="${spring.status.expression}"
value="${spring.status.value?html}"/><br />
<#list spring.status.errorMessages as error> <b>${error}</b> <br /> </#list>
<br />
...
<input type="submit" value="submit"/>
</form>
...
</html>
<@spring.bind>
requires a ‘path’ argument, which consists of the name of your command
object (it is ‘command’, unless you changed it in your controller configuration) followed
by a period and the name of the field on the command object to which you wish to bind. You
can also use nested fields, such as command.address.street
. The bind
macro assumes the
default HTML escaping behavior specified by the ServletContext
parameter
defaultHtmlEscape
in web.xml
.
An alternative form of the macro called <@spring.bindEscaped>
takes a second argument
that explicitly specifies whether HTML escaping should be used in the status error
messages or values. You can set it to true
or false
as required. Additional form
handling macros simplify the use of HTML escaping, and you should use these macros
wherever possible. They are explained in the next section.
Input Macros
Additional convenience macros for FreeMarker simplify both binding and form generation
(including validation error display). It is never necessary to use these macros to
generate form input fields, and you can mix and match them with simple HTML or direct
calls to the Spring bind macros that we highlighted previously.
The following table of available macros shows the FreeMarker Template (FTL) definitions
and the parameter list that each takes:
macro | FTL definition |
---|---|
|
<@spring.message code/> |
|
<@spring.messageText code, text/> |
|
<@spring.url relativeUrl/> |
|
<@spring.formInput path, attributes, fieldType/> |
|
<@spring.formHiddenInput path, attributes/> |
|
<@spring.formPasswordInput path, attributes/> |
|
<@spring.formTextarea path, attributes/> |
|
<@spring.formSingleSelect path, options, attributes/> |
|
<@spring.formMultiSelect path, options, attributes/> |
|
<@spring.formRadioButtons path, options separator, attributes/> |
|
<@spring.formCheckboxes path, options, separator, attributes/> |
|
<@spring.formCheckbox path, attributes/> |
|
<@spring.showErrors separator, classOrStyle/> |
In FreeMarker templates, formHiddenInput and formPasswordInput are not actuallyrequired, as you can use the normal formInput macro, specifying hidden or password as the value for the fieldType parameter.
|
The parameters to any of the above macros have consistent meanings:
-
path
: The name of the field to bind to (for example, «command.name») -
options
: AMap
of all the available values that can be selected from in the input
field. The keys to the map represent the values that are POSTed back from the form
and bound to the command object. Map objects stored against the keys are the labels
displayed on the form to the user and may be different from the corresponding values
posted back by the form. Usually, such a map is supplied as reference data by the
controller. You can use anyMap
implementation, depending on required behavior.
For strictly sorted maps, you can use aSortedMap
(such as aTreeMap
) with a
suitableComparator
and, for arbitrary Maps that should return values in insertion
order, use aLinkedHashMap
or aLinkedMap
fromcommons-collections
. -
separator
: Where multiple options are available as discreet elements (radio buttons
or checkboxes), the sequence of characters used to separate each one in the list
(such as<br>
). -
attributes
: An additional string of arbitrary tags or text to be included within
the HTML tag itself. This string is echoed literally by the macro. For example, in a
textarea
field, you may supply attributes (such as ‘rows=»5″ cols=»60″‘), or you
could pass style information such as ‘style=»border:1px solid silver»‘. -
classOrStyle
: For theshowErrors
macro, the name of the CSS class that thespan
element that wraps each error uses. If no information is supplied (or the value is
empty), the errors are wrapped in<b></b>
tags.
The following sections outline examples of the macros.
The formInput
macro takes the path
parameter (command.name
) and an additional attributes
parameter (which is empty in the upcoming example). The macro, along with all other form
generation macros, performs an implicit Spring bind on the path parameter. The binding
remains valid until a new bind occurs, so the showErrors
macro does not need to pass the
path parameter again — it operates on the field for which a binding was last created.
The showErrors
macro takes a separator parameter (the characters that are used to
separate multiple errors on a given field) and also accepts a second parameter — this
time, a class name or style attribute. Note that FreeMarker can specify default
values for the attributes parameter. The following example shows how to use the formInput
and showErrors
macros:
<@spring.formInput "command.name"/>
<@spring.showErrors "<br>"/>
The next example shows the output of the form fragment, generating the name field and displaying a
validation error after the form was submitted with no value in the field. Validation
occurs through Spring’s Validation framework.
The generated HTML resembles the following example:
Name:
<input type="text" name="name" value="">
<br>
<b>required</b>
<br>
<br>
The formTextarea
macro works the same way as the formInput
macro and accepts the same
parameter list. Commonly, the second parameter (attributes
) is used to pass style
information or rows
and cols
attributes for the textarea
.
You can use four selection field macros to generate common UI value selection inputs in
your HTML forms:
-
formSingleSelect
-
formMultiSelect
-
formRadioButtons
-
formCheckboxes
Each of the four macros accepts a Map
of options that contains the value for the form
field and the label that corresponds to that value. The value and the label can be the
same.
The next example is for radio buttons in FTL. The form-backing object specifies a default
value of ‘London’ for this field, so no validation is necessary. When the form is
rendered, the entire list of cities to choose from is supplied as reference data in the
model under the name ‘cityMap’. The following listing shows the example:
...
Town:
<@spring.formRadioButtons "command.address.town", cityMap, ""/><br><br>
The preceding listing renders a line of radio buttons, one for each value in cityMap
, and uses a
separator of ""
. No additional attributes are supplied (the last parameter to the macro is
missing). The cityMap
uses the same String
for each key-value pair in the map. The map’s
keys are what the form actually submits as POST
request parameters. The map values are the
labels that the user sees. In the preceding example, given a list of three well known cities
and a default value in the form backing object, the HTML resembles the following:
Town:
<input type="radio" name="address.town" value="London">London</input>
<input type="radio" name="address.town" value="Paris" checked="checked">Paris</input>
<input type="radio" name="address.town" value="New York">New York</input>
If your application expects to handle cities by internal codes (for example), you can create the map of
codes with suitable keys, as the following example shows:
Java
protected Map<String, ?> referenceData(HttpServletRequest request) throws Exception {
Map<String, String> cityMap = new LinkedHashMap<>();
cityMap.put("LDN", "London");
cityMap.put("PRS", "Paris");
cityMap.put("NYC", "New York");
Map<String, Object> model = new HashMap<>();
model.put("cityMap", cityMap);
return model;
}
Kotlin
protected fun referenceData(request: HttpServletRequest): Map<String, *> {
val cityMap = linkedMapOf(
"LDN" to "London",
"PRS" to "Paris",
"NYC" to "New York"
)
return hashMapOf("cityMap" to cityMap)
}
The code now produces output where the radio values are the relevant codes, but the
user still sees the more user-friendly city names, as follows:
Town:
<input type="radio" name="address.town" value="LDN">London</input>
<input type="radio" name="address.town" value="PRS" checked="checked">Paris</input>
<input type="radio" name="address.town" value="NYC">New York</input>
HTML Escaping
Default usage of the form macros described earlier results in HTML elements that are HTML 4.01
compliant and that use the default value for HTML escaping defined in your web.xml
file, as
used by Spring’s bind support. To make the elements be XHTML compliant or to override
the default HTML escaping value, you can specify two variables in your template (or in
your model, where they are visible to your templates). The advantage of specifying
them in the templates is that they can be changed to different values later in the
template processing to provide different behavior for different fields in your form.
To switch to XHTML compliance for your tags, specify a value of true
for a
model or context variable named xhtmlCompliant
, as the following example shows:
<#-- for FreeMarker -->
<#assign xhtmlCompliant = true>
After processing this directive, any elements generated by the Spring macros are now XHTML
compliant.
In similar fashion, you can specify HTML escaping per field, as the following example shows:
<#-- until this point, default HTML escaping is used -->
<#assign htmlEscape = true>
<#-- next field will use HTML escaping -->
<@spring.formInput "command.name"/>
<#assign htmlEscape = false in spring>
<#-- all future fields will be bound with HTML escaping off -->
1.11.3. Groovy Markup
The Groovy Markup Template Engine
is primarily aimed at generating XML-like markup (XML, XHTML, HTML5, and others), but you can
use it to generate any text-based content. The Spring Framework has a built-in
integration for using Spring MVC with Groovy Markup.
The Groovy Markup Template engine requires Groovy 2.3.1+. |
Configuration
The following example shows how to configure the Groovy Markup Template Engine:
Java
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
registry.groovy();
}
// Configure the Groovy Markup Template Engine...
@Bean
public GroovyMarkupConfigurer groovyMarkupConfigurer() {
GroovyMarkupConfigurer configurer = new GroovyMarkupConfigurer();
configurer.setResourceLoaderPath("/WEB-INF/");
return configurer;
}
}
Kotlin
@Configuration
@EnableWebMvc
class WebConfig : WebMvcConfigurer {
override fun configureViewResolvers(registry: ViewResolverRegistry) {
registry.groovy()
}
// Configure the Groovy Markup Template Engine...
@Bean
fun groovyMarkupConfigurer() = GroovyMarkupConfigurer().apply {
resourceLoaderPath = "/WEB-INF/"
}
}
The following example shows how to configure the same in XML:
<mvc:annotation-driven/>
<mvc:view-resolvers>
<mvc:groovy/>
</mvc:view-resolvers>
<!-- Configure the Groovy Markup Template Engine... -->
<mvc:groovy-configurer resource-loader-path="/WEB-INF/"/>
Example
Unlike traditional template engines, Groovy Markup relies on a DSL that uses a builder
syntax. The following example shows a sample template for an HTML page:
yieldUnescaped '<!DOCTYPE html>'
html(lang:'en') {
head {
meta('http-equiv':'"Content-Type" content="text/html; charset=utf-8"')
title('My page')
}
body {
p('This is an example of HTML contents')
}
}
1.11.4. Script Views
The Spring Framework has a built-in integration for using Spring MVC with any
templating library that can run on top of the
JSR-223 Java scripting engine. We have tested the following
templating libraries on different script engines:
Scripting Library | Scripting Engine |
---|---|
Handlebars |
Nashorn |
Mustache |
Nashorn |
React |
Nashorn |
EJS |
Nashorn |
ERB |
JRuby |
String templates |
Jython |
Kotlin Script templating |
Kotlin |
The basic rule for integrating any other script engine is that it must implement theScriptEngine and Invocable interfaces.
|
Requirements
You need to have the script engine on your classpath, the details of which vary by script engine:
-
The Nashorn JavaScript engine is provided with
Java 8+. Using the latest update release available is highly recommended. -
JRuby should be added as a dependency for Ruby support.
-
Jython should be added as a dependency for Python support.
-
org.jetbrains.kotlin:kotlin-script-util
dependency and aMETA-INF/services/javax.script.ScriptEngineFactory
file containing aorg.jetbrains.kotlin.script.jsr223.KotlinJsr223JvmLocalScriptEngineFactory
line should be added for Kotlin script support. See
this example for more details.
You need to have the script templating library. One way to do that for JavaScript is
through WebJars.
Script Templates
You can declare a ScriptTemplateConfigurer
bean to specify the script engine to use,
the script files to load, what function to call to render templates, and so on.
The following example uses Mustache templates and the Nashorn JavaScript engine:
Java
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
registry.scriptTemplate();
}
@Bean
public ScriptTemplateConfigurer configurer() {
ScriptTemplateConfigurer configurer = new ScriptTemplateConfigurer();
configurer.setEngineName("nashorn");
configurer.setScripts("mustache.js");
configurer.setRenderObject("Mustache");
configurer.setRenderFunction("render");
return configurer;
}
}
Kotlin
@Configuration
@EnableWebMvc
class WebConfig : WebMvcConfigurer {
override fun configureViewResolvers(registry: ViewResolverRegistry) {
registry.scriptTemplate()
}
@Bean
fun configurer() = ScriptTemplateConfigurer().apply {
engineName = "nashorn"
setScripts("mustache.js")
renderObject = "Mustache"
renderFunction = "render"
}
}
The following example shows the same arrangement in XML:
<mvc:annotation-driven/>
<mvc:view-resolvers>
<mvc:script-template/>
</mvc:view-resolvers>
<mvc:script-template-configurer engine-name="nashorn" render-object="Mustache" render-function="render">
<mvc:script location="mustache.js"/>
</mvc:script-template-configurer>
The controller would look no different for the Java and XML configurations, as the following example shows:
Java
@Controller
public class SampleController {
@GetMapping("/sample")
public String test(Model model) {
model.addAttribute("title", "Sample title");
model.addAttribute("body", "Sample body");
return "template";
}
}
Kotlin
@Controller
class SampleController {
@GetMapping("/sample")
fun test(model: Model): String {
model["title"] = "Sample title"
model["body"] = "Sample body"
return "template"
}
}
The following example shows the Mustache template:
<html>
<head>
<title>{{title}}</title>
</head>
<body>
<p>{{body}}</p>
</body>
</html>
The render function is called with the following parameters:
-
String template
: The template content -
Map model
: The view model -
RenderingContext renderingContext
: The
RenderingContext
that gives access to the application context, the locale, the template loader, and the
URL (since 5.0)
Mustache.render()
is natively compatible with this signature, so you can call it directly.
If your templating technology requires some customization, you can provide a script that
implements a custom render function. For example, Handlerbars
needs to compile templates before using them and requires a
polyfill to emulate some
browser facilities that are not available in the server-side script engine.
The following example shows how to do so:
Java
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
registry.scriptTemplate();
}
@Bean
public ScriptTemplateConfigurer configurer() {
ScriptTemplateConfigurer configurer = new ScriptTemplateConfigurer();
configurer.setEngineName("nashorn");
configurer.setScripts("polyfill.js", "handlebars.js", "render.js");
configurer.setRenderFunction("render");
configurer.setSharedEngine(false);
return configurer;
}
}
Kotlin
@Configuration
@EnableWebMvc
class WebConfig : WebMvcConfigurer {
override fun configureViewResolvers(registry: ViewResolverRegistry) {
registry.scriptTemplate()
}
@Bean
fun configurer() = ScriptTemplateConfigurer().apply {
engineName = "nashorn"
setScripts("polyfill.js", "handlebars.js", "render.js")
renderFunction = "render"
isSharedEngine = false
}
}
Setting the sharedEngine property to false is required when using non-thread-safescript engines with templating libraries not designed for concurrency, such as Handlebars or React running on Nashorn. In that case, Java SE 8 update 60 is required, due to this bug, but it is generally recommended to use a recent Java SE patch release in any case. |
polyfill.js
defines only the window
object needed by Handlebars to run properly, as follows:
This basic render.js
implementation compiles the template before using it. A production-ready
implementation should also store any reused cached templates or pre-compiled templates.
You can do so on the script side (and handle any customization you need — managing
template engine configuration, for example). The following example shows how to do so:
function render(template, model) {
var compiledTemplate = Handlebars.compile(template);
return compiledTemplate(model);
}
Check out the Spring Framework unit tests,
Java, and
resources,
for more configuration examples.
1.11.5. JSP and JSTL
The Spring Framework has a built-in integration for using Spring MVC with JSP and JSTL.
View Resolvers
When developing with JSPs, you typically declare an InternalResourceViewResolver
bean.
InternalResourceViewResolver
can be used for dispatching to any Servlet resource but in
particular for JSPs. As a best practice, we strongly encourage placing your JSP files in
a directory under the 'WEB-INF'
directory so there can be no direct access by clients.
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
JSPs versus JSTL
When using the JSP Standard Tag Library (JSTL) you must use a special view class, the
JstlView
, as JSTL needs some preparation before things such as the I18N features can
work.
Spring’s JSP Tag Library
Spring provides data binding of request parameters to command objects, as described in
earlier chapters. To facilitate the development of JSP pages in combination with those
data binding features, Spring provides a few tags that make things even easier. All
Spring tags have HTML escaping features to enable or disable escaping of characters.
The spring.tld
tag library descriptor (TLD) is included in the spring-webmvc.jar
.
For a comprehensive reference on individual tags, browse the
API reference
or see the tag library description.
Spring’s form tag library
As of version 2.0, Spring provides a comprehensive set of data binding-aware tags for
handling form elements when using JSP and Spring Web MVC. Each tag provides support for
the set of attributes of its corresponding HTML tag counterpart, making the tags
familiar and intuitive to use. The tag-generated HTML is HTML 4.01/XHTML 1.0 compliant.
Unlike other form/input tag libraries, Spring’s form tag library is integrated with
Spring Web MVC, giving the tags access to the command object and reference data your
controller deals with. As we show in the following examples, the form tags make
JSPs easier to develop, read, and maintain.
We go through the form tags and look at an example of how each tag is used. We have
included generated HTML snippets where certain tags require further commentary.
Configuration
The form tag library comes bundled in spring-webmvc.jar
. The library descriptor is
called spring-form.tld
.
To use the tags from this library, add the following directive to the top of your JSP
page:
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
where form
is the tag name prefix you want to use for the tags from this library.
The Form Tag
This tag renders an HTML ‘form’ element and exposes a binding path to inner tags for
binding. It puts the command object in the PageContext
so that the command object can
be accessed by inner tags. All the other tags in this library are nested tags of the
form
tag.
Assume that we have a domain object called User
. It is a JavaBean with properties
such as firstName
and lastName
. We can use it as the form-backing object of our
form controller, which returns form.jsp
. The following example shows what form.jsp
could
look like:
<form:form>
<table>
<tr>
<td>First Name:</td>
<td><form:input path="firstName"/></td>
</tr>
<tr>
<td>Last Name:</td>
<td><form:input path="lastName"/></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Save Changes"/>
</td>
</tr>
</table>
</form:form>
The firstName
and lastName
values are retrieved from the command object placed in
the PageContext
by the page controller. Keep reading to see more complex examples of
how inner tags are used with the form
tag.
The following listing shows the generated HTML, which looks like a standard form:
<form method="POST">
<table>
<tr>
<td>First Name:</td>
<td><input name="firstName" type="text" value="Harry"/></td>
</tr>
<tr>
<td>Last Name:</td>
<td><input name="lastName" type="text" value="Potter"/></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Save Changes"/>
</td>
</tr>
</table>
</form>
The preceding JSP assumes that the variable name of the form-backing object is
command
. If you have put the form-backing object into the model under another name
(definitely a best practice), you can bind the form to the named variable, as the
following example shows:
<form:form modelAttribute="user">
<table>
<tr>
<td>First Name:</td>
<td><form:input path="firstName"/></td>
</tr>
<tr>
<td>Last Name:</td>
<td><form:input path="lastName"/></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Save Changes"/>
</td>
</tr>
</table>
</form:form>
The input
Tag
This tag renders an HTML input
element with the bound value and type='text'
by default.
For an example of this tag, see The Form Tag. You can also use
HTML5-specific types, such as email
, tel
, date
, and others.
The checkbox
Tag
This tag renders an HTML input
tag with the type
set to checkbox
.
Assume that our User
has preferences such as newsletter subscription and a list of
hobbies. The following example shows the Preferences
class:
Java
public class Preferences {
private boolean receiveNewsletter;
private String[] interests;
private String favouriteWord;
public boolean isReceiveNewsletter() {
return receiveNewsletter;
}
public void setReceiveNewsletter(boolean receiveNewsletter) {
this.receiveNewsletter = receiveNewsletter;
}
public String[] getInterests() {
return interests;
}
public void setInterests(String[] interests) {
this.interests = interests;
}
public String getFavouriteWord() {
return favouriteWord;
}
public void setFavouriteWord(String favouriteWord) {
this.favouriteWord = favouriteWord;
}
}
Kotlin
class Preferences(
var receiveNewsletter: Boolean,
var interests: StringArray,
var favouriteWord: String
)
The corresponding form.jsp
could then resemble the following:
<form:form>
<table>
<tr>
<td>Subscribe to newsletter?:</td>
<%-- Approach 1: Property is of type java.lang.Boolean --%>
<td><form:checkbox path="preferences.receiveNewsletter"/></td>
</tr>
<tr>
<td>Interests:</td>
<%-- Approach 2: Property is of an array or of type java.util.Collection --%>
<td>
Quidditch: <form:checkbox path="preferences.interests" value="Quidditch"/>
Herbology: <form:checkbox path="preferences.interests" value="Herbology"/>
Defence Against the Dark Arts: <form:checkbox path="preferences.interests" value="Defence Against the Dark Arts"/>
</td>
</tr>
<tr>
<td>Favourite Word:</td>
<%-- Approach 3: Property is of type java.lang.Object --%>
<td>
Magic: <form:checkbox path="preferences.favouriteWord" value="Magic"/>
</td>
</tr>
</table>
</form:form>
There are three approaches to the checkbox
tag, which should meet all your checkbox needs.
-
Approach One: When the bound value is of type
java.lang.Boolean
, the
input(checkbox)
is marked aschecked
if the bound value istrue
. Thevalue
attribute corresponds to the resolved value of thesetValue(Object)
value property. -
Approach Two: When the bound value is of type
array
orjava.util.Collection
, the
input(checkbox)
is marked aschecked
if the configuredsetValue(Object)
value is
present in the boundCollection
. -
Approach Three: For any other bound value type, the
input(checkbox)
is marked as
checked
if the configuredsetValue(Object)
is equal to the bound value.
Note that, regardless of the approach, the same HTML structure is generated. The following
HTML snippet defines some checkboxes:
<tr>
<td>Interests:</td>
<td>
Quidditch: <input name="preferences.interests" type="checkbox" value="Quidditch"/>
<input type="hidden" value="1" name="_preferences.interests"/>
Herbology: <input name="preferences.interests" type="checkbox" value="Herbology"/>
<input type="hidden" value="1" name="_preferences.interests"/>
Defence Against the Dark Arts: <input name="preferences.interests" type="checkbox" value="Defence Against the Dark Arts"/>
<input type="hidden" value="1" name="_preferences.interests"/>
</td>
</tr>
You might not expect to see the additional hidden field after each checkbox.
When a checkbox in an HTML page is not checked, its value is not sent to the
server as part of the HTTP request parameters once the form is submitted, so we need a
workaround for this quirk in HTML for Spring form data binding to work. The
checkbox
tag follows the existing Spring convention of including a hidden parameter
prefixed by an underscore (_
) for each checkbox. By doing this, you are effectively
telling Spring that “the checkbox was visible in the form, and I want my object to
which the form data binds to reflect the state of the checkbox, no matter what.”
The checkboxes
Tag
This tag renders multiple HTML input
tags with the type
set to checkbox
.
This section build on the example from the previous checkbox
tag section. Sometimes, you prefer
not to have to list all the possible hobbies in your JSP page. You would rather provide
a list at runtime of the available options and pass that in to the tag. That is the
purpose of the checkboxes
tag. You can pass in an Array
, a List
, or a Map
that contains
the available options in the items
property. Typically, the bound property is a
collection so that it can hold multiple values selected by the user. The following example
shows a JSP that uses this tag:
<form:form>
<table>
<tr>
<td>Interests:</td>
<td>
<%-- Property is of an array or of type java.util.Collection --%>
<form:checkboxes path="preferences.interests" items="${interestList}"/>
</td>
</tr>
</table>
</form:form>
This example assumes that the interestList
is a List
available as a model attribute
that contains strings of the values to be selected from. If you use a Map
,
the map entry key is used as the value, and the map entry’s value is used as
the label to be displayed. You can also use a custom object where you can provide the
property names for the value by using itemValue
and the label by using itemLabel
.
The radiobutton
Tag
This tag renders an HTML input
element with the type
set to radio
.
A typical usage pattern involves multiple tag instances bound to the same property
but with different values, as the following example shows:
<tr>
<td>Sex:</td>
<td>
Male: <form:radiobutton path="sex" value="M"/> <br/>
Female: <form:radiobutton path="sex" value="F"/>
</td>
</tr>
The radiobuttons
Tag
This tag renders multiple HTML input
elements with the type
set to radio
.
As with the checkboxes
tag, you might want to
pass in the available options as a runtime variable. For this usage, you can use the
radiobuttons
tag. You pass in an Array
, a List
, or a Map
that contains the
available options in the items
property. If you use a Map
, the map entry key is
used as the value and the map entry’s value are used as the label to be displayed.
You can also use a custom object where you can provide the property names for the value
by using itemValue
and the label by using itemLabel
, as the following example shows:
<tr>
<td>Sex:</td>
<td><form:radiobuttons path="sex" items="${sexOptions}"/></td>
</tr>
The password
Tag
This tag renders an HTML input
tag with the type set to password
with the bound value.
<tr>
<td>Password:</td>
<td>
<form:password path="password"/>
</td>
</tr>
Note that, by default, the password value is not shown. If you do want the
password value to be shown, you can set the value of the showPassword
attribute to
true
, as the following example shows:
<tr>
<td>Password:</td>
<td>
<form:password path="password" value="^76525bvHGq" showPassword="true"/>
</td>
</tr>
The select
Tag
This tag renders an HTML ‘select’ element. It supports data binding to the selected
option as well as the use of nested option
and options
tags.
Assume that a User
has a list of skills. The corresponding HTML could be as follows:
<tr>
<td>Skills:</td>
<td><form:select path="skills" items="${skills}"/></td>
</tr>
If the User’s
skill are in Herbology, the HTML source of the ‘Skills’ row could be
as follows:
<tr>
<td>Skills:</td>
<td>
<select name="skills" multiple="true">
<option value="Potions">Potions</option>
<option value="Herbology" selected="selected">Herbology</option>
<option value="Quidditch">Quidditch</option>
</select>
</td>
</tr>
The option
Tag
This tag renders an HTML option
element. It sets selected
, based on the bound
value. The following HTML shows typical output for it:
<tr>
<td>House:</td>
<td>
<form:select path="house">
<form:option value="Gryffindor"/>
<form:option value="Hufflepuff"/>
<form:option value="Ravenclaw"/>
<form:option value="Slytherin"/>
</form:select>
</td>
</tr>
If the User’s
house was in Gryffindor, the HTML source of the ‘House’ row would be
as follows:
<tr>
<td>House:</td>
<td>
<select name="house">
<option value="Gryffindor" selected="selected">Gryffindor</option> (1)
<option value="Hufflepuff">Hufflepuff</option>
<option value="Ravenclaw">Ravenclaw</option>
<option value="Slytherin">Slytherin</option>
</select>
</td>
</tr>
1 | Note the addition of a selected attribute. |
The options
Tag
This tag renders a list of HTML option
elements. It sets the selected
attribute,
based on the bound value. The following HTML shows typical output for it:
<tr>
<td>Country:</td>
<td>
<form:select path="country">
<form:option value="-" label="--Please Select"/>
<form:options items="${countryList}" itemValue="code" itemLabel="name"/>
</form:select>
</td>
</tr>
If the User
lived in the UK, the HTML source of the ‘Country’ row would be as follows:
<tr>
<td>Country:</td>
<td>
<select name="country">
<option value="-">--Please Select</option>
<option value="AT">Austria</option>
<option value="UK" selected="selected">United Kingdom</option> (1)
<option value="US">United States</option>
</select>
</td>
</tr>
1 | Note the addition of a selected attribute. |
As the preceding example shows, the combined usage of an option
tag with the options
tag
generates the same standard HTML but lets you explicitly specify a value in the
JSP that is for display only (where it belongs), such as the default string in the
example: «— Please Select».
The items
attribute is typically populated with a collection or array of item objects.
itemValue
and itemLabel
refer to bean properties of those item objects, if
specified. Otherwise, the item objects themselves are turned into strings. Alternatively,
you can specify a Map
of items, in which case the map keys are interpreted as option
values and the map values correspond to option labels. If itemValue
or itemLabel
(or both)
happen to be specified as well, the item value property applies to the map key, and
the item label property applies to the map value.
The textarea
Tag
This tag renders an HTML textarea
element. The following HTML shows typical output for it:
<tr>
<td>Notes:</td>
<td><form:textarea path="notes" rows="3" cols="20"/></td>
<td><form:errors path="notes"/></td>
</tr>
The hidden
Tag
This tag renders an HTML input
tag with the type
set to hidden
with the bound value. To submit
an unbound hidden value, use the HTML input
tag with the type
set to hidden
.
The following HTML shows typical output for it:
<form:hidden path="house"/>
If we choose to submit the house
value as a hidden one, the HTML would be as follows:
<input name="house" type="hidden" value="Gryffindor"/>
The errors
Tag
This tag renders field errors in an HTML span
element. It provides access to the errors
created in your controller or those that were created by any validators associated with
your controller.
Assume that we want to display all error messages for the firstName
and lastName
fields once we submit the form. We have a validator for instances of the User
class
called UserValidator
, as the following example shows:
Java
public class UserValidator implements Validator {
public boolean supports(Class candidate) {
return User.class.isAssignableFrom(candidate);
}
public void validate(Object obj, Errors errors) {
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName", "required", "Field is required.");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lastName", "required", "Field is required.");
}
}
Kotlin
class UserValidator : Validator {
override fun supports(candidate: Class<*>): Boolean {
return User::class.java.isAssignableFrom(candidate)
}
override fun validate(obj: Any, errors: Errors) {
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName", "required", "Field is required.")
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lastName", "required", "Field is required.")
}
}
The form.jsp
could be as follows:
<form:form>
<table>
<tr>
<td>First Name:</td>
<td><form:input path="firstName"/></td>
<%-- Show errors for firstName field --%>
<td><form:errors path="firstName"/></td>
</tr>
<tr>
<td>Last Name:</td>
<td><form:input path="lastName"/></td>
<%-- Show errors for lastName field --%>
<td><form:errors path="lastName"/></td>
</tr>
<tr>
<td colspan="3">
<input type="submit" value="Save Changes"/>
</td>
</tr>
</table>
</form:form>
If we submit a form with empty values in the firstName
and lastName
fields,
the HTML would be as follows:
<form method="POST">
<table>
<tr>
<td>First Name:</td>
<td><input name="firstName" type="text" value=""/></td>
<%-- Associated errors to firstName field displayed --%>
<td><span name="firstName.errors">Field is required.</span></td>
</tr>
<tr>
<td>Last Name:</td>
<td><input name="lastName" type="text" value=""/></td>
<%-- Associated errors to lastName field displayed --%>
<td><span name="lastName.errors">Field is required.</span></td>
</tr>
<tr>
<td colspan="3">
<input type="submit" value="Save Changes"/>
</td>
</tr>
</table>
</form>
What if we want to display the entire list of errors for a given page? The next example
shows that the errors
tag also supports some basic wildcarding functionality.
-
path="*"
: Displays all errors. -
path="lastName"
: Displays all errors associated with thelastName
field. -
If
path
is omitted, only object errors are displayed.
The following example displays a list of errors at the top of the page, followed by
field-specific errors next to the fields:
<form:form>
<form:errors path="*" cssClass="errorBox"/>
<table>
<tr>
<td>First Name:</td>
<td><form:input path="firstName"/></td>
<td><form:errors path="firstName"/></td>
</tr>
<tr>
<td>Last Name:</td>
<td><form:input path="lastName"/></td>
<td><form:errors path="lastName"/></td>
</tr>
<tr>
<td colspan="3">
<input type="submit" value="Save Changes"/>
</td>
</tr>
</table>
</form:form>
The HTML would be as follows:
<form method="POST">
<span name="*.errors" class="errorBox">Field is required.<br/>Field is required.</span>
<table>
<tr>
<td>First Name:</td>
<td><input name="firstName" type="text" value=""/></td>
<td><span name="firstName.errors">Field is required.</span></td>
</tr>
<tr>
<td>Last Name:</td>
<td><input name="lastName" type="text" value=""/></td>
<td><span name="lastName.errors">Field is required.</span></td>
</tr>
<tr>
<td colspan="3">
<input type="submit" value="Save Changes"/>
</td>
</tr>
</table>
</form>
The spring-form.tld
tag library descriptor (TLD) is included in the spring-webmvc.jar
.
For a comprehensive reference on individual tags, browse the
API reference
or see the tag library description.
HTTP Method Conversion
A key principle of REST is the use of the “Uniform Interface”. This means that all
resources (URLs) can be manipulated by using the same four HTTP methods: GET, PUT, POST,
and DELETE. For each method, the HTTP specification defines the exact semantics. For
instance, a GET should always be a safe operation, meaning that it has no side effects,
and a PUT or DELETE should be idempotent, meaning that you can repeat these operations
over and over again, but the end result should be the same. While HTTP defines these
four methods, HTML only supports two: GET and POST. Fortunately, there are two possible
workarounds: you can either use JavaScript to do your PUT or DELETE, or you can do a POST
with the “real” method as an additional parameter (modeled as a hidden input field in an
HTML form). Spring’s HiddenHttpMethodFilter
uses this latter trick. This
filter is a plain Servlet filter and, therefore, it can be used in combination with any
web framework (not just Spring MVC). Add this filter to your web.xml, and a POST
with a hidden method
parameter is converted into the corresponding HTTP method
request.
To support HTTP method conversion, the Spring MVC form tag was updated to support setting
the HTTP method. For example, the following snippet comes from the Pet Clinic sample:
<form:form method="delete">
<p class="submit"><input type="submit" value="Delete Pet"/></p>
</form:form>
The preceding example performs an HTTP POST, with the “real” DELETE method hidden behind
a request parameter. It is picked up by the HiddenHttpMethodFilter
, which is defined in
web.xml, as the following example shows:
<filter>
<filter-name>httpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>httpMethodFilter</filter-name>
<servlet-name>petclinic</servlet-name>
</filter-mapping>
The following example shows the corresponding @Controller
method:
Java
@RequestMapping(method = RequestMethod.DELETE)
public String deletePet(@PathVariable int ownerId, @PathVariable int petId) {
this.clinic.deletePet(petId);
return "redirect:/owners/" + ownerId;
}
Kotlin
@RequestMapping(method = [RequestMethod.DELETE])
fun deletePet(@PathVariable ownerId: Int, @PathVariable petId: Int): String {
clinic.deletePet(petId)
return "redirect:/owners/$ownerId"
}
HTML5 Tags
The Spring form tag library allows entering dynamic attributes, which means you can
enter any HTML5 specific attributes.
The form input
tag supports entering a type attribute other than text
. This is
intended to allow rendering new HTML5 specific input types, such as email
, date
,
range
, and others. Note that entering type='text'
is not required, since text
is the default type.
1.11.6. Tiles
You can integrate Tiles — just as any other view technology — in web
applications that use Spring. This section describes, in a broad way, how to do so.
This section focuses on Spring’s support for Tiles version 3 in theorg.springframework.web.servlet.view.tiles3 package.
|
Dependencies
To be able to use Tiles, you have to add a dependency on Tiles version 3.0.1 or higher
and its transitive dependencies
to your project.
Configuration
To be able to use Tiles, you have to configure it by using files that contain definitions
(for basic information on definitions and other Tiles concepts, see
https://tiles.apache.org). In Spring, this is done by using the TilesConfigurer
.
The following example ApplicationContext
configuration shows how to do so:
<bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles3.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/defs/general.xml</value>
<value>/WEB-INF/defs/widgets.xml</value>
<value>/WEB-INF/defs/administrator.xml</value>
<value>/WEB-INF/defs/customer.xml</value>
<value>/WEB-INF/defs/templates.xml</value>
</list>
</property>
</bean>
The preceding example defines five files that contain definitions. The files are all
located in the WEB-INF/defs
directory. At initialization of the WebApplicationContext
,
the files are loaded, and the definitions factory are initialized. After that has
been done, the Tiles included in the definition files can be used as views within your
Spring web application. To be able to use the views, you have to have a ViewResolver
as with any other view technology in Spring: typically a convenient TilesViewResolver
.
You can specify locale-specific Tiles definitions by adding an underscore and then
the locale, as the following example shows:
<bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles3.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/defs/tiles.xml</value>
<value>/WEB-INF/defs/tiles_fr_FR.xml</value>
</list>
</property>
</bean>
With the preceding configuration, tiles_fr_FR.xml
is used for requests with the fr_FR
locale,
and tiles.xml
is used by default.
Since underscores are used to indicate locales, we recommended not using them otherwise in the file names for Tiles definitions. |
UrlBasedViewResolver
The UrlBasedViewResolver
instantiates the given viewClass
for each view it has to
resolve. The following bean defines a UrlBasedViewResolver
:
<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.tiles3.TilesView"/>
</bean>
SimpleSpringPreparerFactory
and SpringBeanPreparerFactory
As an advanced feature, Spring also supports two special Tiles PreparerFactory
implementations. See the Tiles documentation for details on how to use
ViewPreparer
references in your Tiles definition files.
You can specify SimpleSpringPreparerFactory
to autowire ViewPreparer
instances based on
specified preparer classes, applying Spring’s container callbacks as well as applying
configured Spring BeanPostProcessors. If Spring’s context-wide annotation configuration has
been activated, annotations in ViewPreparer
classes are automatically detected and
applied. Note that this expects preparer classes in the Tiles definition files, as
the default PreparerFactory
does.
You can specify SpringBeanPreparerFactory
to operate on specified preparer names (instead
of classes), obtaining the corresponding Spring bean from the DispatcherServlet’s
application context. The full bean creation process is in the control of the Spring
application context in this case, allowing for the use of explicit dependency injection
configuration, scoped beans, and so on. Note that you need to define one Spring bean definition
for each preparer name (as used in your Tiles definitions). The following example shows
how to define a SpringBeanPreparerFactory
property on a TilesConfigurer
bean:
<bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles3.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/defs/general.xml</value>
<value>/WEB-INF/defs/widgets.xml</value>
<value>/WEB-INF/defs/administrator.xml</value>
<value>/WEB-INF/defs/customer.xml</value>
<value>/WEB-INF/defs/templates.xml</value>
</list>
</property>
<!-- resolving preparer names as Spring bean definition names -->
<property name="preparerFactoryClass"
value="org.springframework.web.servlet.view.tiles3.SpringBeanPreparerFactory"/>
</bean>
1.11.7. RSS and Atom
Both AbstractAtomFeedView
and AbstractRssFeedView
inherit from the
AbstractFeedView
base class and are used to provide Atom and RSS Feed views, respectively. They
are based on ROME project and are located in the
package org.springframework.web.servlet.view.feed
.
AbstractAtomFeedView
requires you to implement the buildFeedEntries()
method and
optionally override the buildFeedMetadata()
method (the default implementation is
empty). The following example shows how to do so:
Java
public class SampleContentAtomView extends AbstractAtomFeedView {
@Override
protected void buildFeedMetadata(Map<String, Object> model,
Feed feed, HttpServletRequest request) {
// implementation omitted
}
@Override
protected List<Entry> buildFeedEntries(Map<String, Object> model,
HttpServletRequest request, HttpServletResponse response) throws Exception {
// implementation omitted
}
}
Kotlin
class SampleContentAtomView : AbstractAtomFeedView() {
override fun buildFeedMetadata(model: Map<String, Any>,
feed: Feed, request: HttpServletRequest) {
// implementation omitted
}
override fun buildFeedEntries(model: Map<String, Any>,
request: HttpServletRequest, response: HttpServletResponse): List<Entry> {
// implementation omitted
}
}
Similar requirements apply for implementing AbstractRssFeedView
, as the following example shows:
Java
public class SampleContentRssView extends AbstractRssFeedView {
@Override
protected void buildFeedMetadata(Map<String, Object> model,
Channel feed, HttpServletRequest request) {
// implementation omitted
}
@Override
protected List<Item> buildFeedItems(Map<String, Object> model,
HttpServletRequest request, HttpServletResponse response) throws Exception {
// implementation omitted
}
}
Kotlin
class SampleContentRssView : AbstractRssFeedView() {
override fun buildFeedMetadata(model: Map<String, Any>,
feed: Channel, request: HttpServletRequest) {
// implementation omitted
}
override fun buildFeedItems(model: Map<String, Any>,
request: HttpServletRequest, response: HttpServletResponse): List<Item> {
// implementation omitted
}
}
The buildFeedItems()
and buildFeedEntries()
methods pass in the HTTP request, in case
you need to access the Locale. The HTTP response is passed in only for the setting of
cookies or other HTTP headers. The feed is automatically written to the response
object after the method returns.
For an example of creating an Atom view, see Alef Arendsen’s Spring Team Blog
entry.
1.11.8. PDF and Excel
Spring offers ways to return output other than HTML, including PDF and Excel spreadsheets.
This section describes how to use those features.
Introduction to Document Views
An HTML page is not always the best way for the user to view the model output,
and Spring makes it simple to generate a PDF document or an Excel spreadsheet
dynamically from the model data. The document is the view and is streamed from the
server with the correct content type, to (hopefully) enable the client PC to run their
spreadsheet or PDF viewer application in response.
In order to use Excel views, you need to add the Apache POI library to your classpath.
For PDF generation, you need to add (preferably) the OpenPDF library.
You should use the latest versions of the underlying document-generation libraries, if possible. In particular, we strongly recommend OpenPDF (for example, OpenPDF 1.2.12) instead of the outdated original iText 2.1.7, since OpenPDF is actively maintained and fixes an important vulnerability for untrusted PDF content. |
PDF Views
A simple PDF view for a word list could extend
org.springframework.web.servlet.view.document.AbstractPdfView
and implement the
buildPdfDocument()
method, as the following example shows:
Java
public class PdfWordList extends AbstractPdfView {
protected void buildPdfDocument(Map<String, Object> model, Document doc, PdfWriter writer,
HttpServletRequest request, HttpServletResponse response) throws Exception {
List<String> words = (List<String>) model.get("wordList");
for (String word : words) {
doc.add(new Paragraph(word));
}
}
}
Kotlin
class PdfWordList : AbstractPdfView() {
override fun buildPdfDocument(model: Map<String, Any>, doc: Document, writer: PdfWriter,
request: HttpServletRequest, response: HttpServletResponse) {
val words = model["wordList"] as List<String>
for (word in words) {
doc.add(Paragraph(word))
}
}
}
A controller can return such a view either from an external view definition
(referencing it by name) or as a View
instance from the handler method.
Excel Views
Since Spring Framework 4.2,
org.springframework.web.servlet.view.document.AbstractXlsView
is provided as a base
class for Excel views. It is based on Apache POI, with specialized subclasses (AbstractXlsxView
and AbstractXlsxStreamingView
) that supersede the outdated AbstractExcelView
class.
The programming model is similar to AbstractPdfView
, with buildExcelDocument()
as the central template method and controllers being able to return such a view from
an external definition (by name) or as a View
instance from the handler method.
1.11.9. Jackson
Spring offers support for the Jackson JSON library.
Jackson-based JSON MVC Views
The MappingJackson2JsonView
uses the Jackson library’s ObjectMapper
to render the response
content as JSON. By default, the entire contents of the model map (with the exception of
framework-specific classes) are encoded as JSON. For cases where the contents of the
map need to be filtered, you can specify a specific set of model attributes to encode
by using the modelKeys
property. You can also use the extractValueFromSingleKeyModel
property to have the value in single-key models extracted and serialized directly rather
than as a map of model attributes.
You can customize JSON mapping as needed by using Jackson’s provided
annotations. When you need further control, you can inject a custom ObjectMapper
through the ObjectMapper
property, for cases where you need to provide custom JSON
serializers and deserializers for specific types.
Jackson-based XML Views
MappingJackson2XmlView
uses the
Jackson XML extension’s XmlMapper
to render the response content as XML. If the model contains multiple entries, you should
explicitly set the object to be serialized by using the modelKey
bean property. If the
model contains a single entry, it is serialized automatically.
You can customized XML mapping as needed by using JAXB or Jackson’s provided
annotations. When you need further control, you can inject a custom XmlMapper
through the ObjectMapper
property, for cases where custom XML
you need to provide serializers and deserializers for specific types.
1.11.10. XML Marshalling
The MarshallingView
uses an XML Marshaller
(defined in the org.springframework.oxm
package) to render the response content as XML. You can explicitly set the object to be
marshalled by using a MarshallingView
instance’s modelKey
bean property. Alternatively,
the view iterates over all model properties and marshals the first type that is supported
by the Marshaller
. For more information on the functionality in the
org.springframework.oxm
package, see Marshalling XML using O/X Mappers.
1.11.11. XSLT Views
XSLT is a transformation language for XML and is popular as a view technology within web
applications. XSLT can be a good choice as a view technology if your application
naturally deals with XML or if your model can easily be converted to XML. The following
section shows how to produce an XML document as model data and have it transformed with
XSLT in a Spring Web MVC application.
This example is a trivial Spring application that creates a list of words in the
Controller
and adds them to the model map. The map is returned, along with the view
name of our XSLT view. See Annotated Controllers for details of Spring Web MVC’s
Controller
interface. The XSLT controller turns the list of words into a simple XML
document ready for transformation.
Beans
Configuration is standard for a simple Spring web application: The MVC configuration
has to define an XsltViewResolver
bean and regular MVC annotation configuration.
The following example shows how to do so:
Java
@EnableWebMvc
@ComponentScan
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Bean
public XsltViewResolver xsltViewResolver() {
XsltViewResolver viewResolver = new XsltViewResolver();
viewResolver.setPrefix("/WEB-INF/xsl/");
viewResolver.setSuffix(".xslt");
return viewResolver;
}
}
Kotlin
@EnableWebMvc
@ComponentScan
@Configuration
class WebConfig : WebMvcConfigurer {
@Bean
fun xsltViewResolver() = XsltViewResolver().apply {
setPrefix("/WEB-INF/xsl/")
setSuffix(".xslt")
}
}
Controller
We also need a Controller that encapsulates our word-generation logic.
The controller logic is encapsulated in a @Controller
class, with the
handler method being defined as follows:
Java
@Controller
public class XsltController {
@RequestMapping("/")
public String home(Model model) throws Exception {
Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
Element root = document.createElement("wordList");
List<String> words = Arrays.asList("Hello", "Spring", "Framework");
for (String word : words) {
Element wordNode = document.createElement("word");
Text textNode = document.createTextNode(word);
wordNode.appendChild(textNode);
root.appendChild(wordNode);
}
model.addAttribute("wordList", root);
return "home";
}
}
Kotlin
import org.springframework.ui.set
@Controller
class XsltController {
@RequestMapping("/")
fun home(model: Model): String {
val document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument()
val root = document.createElement("wordList")
val words = listOf("Hello", "Spring", "Framework")
for (word in words) {
val wordNode = document.createElement("word")
val textNode = document.createTextNode(word)
wordNode.appendChild(textNode)
root.appendChild(wordNode)
}
model["wordList"] = root
return "home"
}
}
So far, we have only created a DOM document and added it to the Model map. Note that you
can also load an XML file as a Resource
and use it instead of a custom DOM document.
There are software packages available that automatically ‘domify’
an object graph, but, within Spring, you have complete flexibility to create the DOM
from your model in any way you choose. This prevents the transformation of XML playing
too great a part in the structure of your model data, which is a danger when using tools
to manage the DOMification process.
Transformation
Finally, the XsltViewResolver
resolves the “home” XSLT template file and merges the
DOM document into it to generate our view. As shown in the XsltViewResolver
configuration, XSLT templates live in the war
file in the WEB-INF/xsl
directory
and end with an xslt
file extension.
The following example shows an XSLT transform:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" omit-xml-declaration="yes"/>
<xsl:template match="/">
<html>
<head><title>Hello!</title></head>
<body>
<h1>My First Words</h1>
<ul>
<xsl:apply-templates/>
</ul>
</body>
</html>
</xsl:template>
<xsl:template match="word">
<li><xsl:value-of select="."/></li>
</xsl:template>
</xsl:stylesheet>
The preceding transform is rendered as the following HTML:
<html>
<head>
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Hello!</title>
</head>
<body>
<h1>My First Words</h1>
<ul>
<li>Hello</li>
<li>Spring</li>
<li>Framework</li>
</ul>
</body>
</html>
1.12. MVC Config
The MVC Java configuration and the MVC XML namespace provide default configuration
suitable for most applications and a configuration API to customize it.
For more advanced customizations, which are not available in the configuration API,
see Advanced Java Config and Advanced XML Config.
You do not need to understand the underlying beans created by the MVC Java configuration
and the MVC namespace. If you want to learn more, see Special Bean Types
and Web MVC Config.
1.12.1. Enable MVC Configuration
In Java configuration, you can use the @EnableWebMvc
annotation to enable MVC
configuration, as the following example shows:
Java
@Configuration
@EnableWebMvc
public class WebConfig {
}
Kotlin
@Configuration
@EnableWebMvc
class WebConfig
In XML configuration, you can use the <mvc:annotation-driven>
element to enable MVC
configuration, as the following example shows:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<mvc:annotation-driven/>
</beans>
The preceding example registers a number of Spring MVC
infrastructure beans and adapts to dependencies
available on the classpath (for example, payload converters for JSON, XML, and others).
1.12.2. MVC Config API
In Java configuration, you can implement the WebMvcConfigurer
interface, as the
following example shows:
Java
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
// Implement configuration methods...
}
Kotlin
@Configuration
@EnableWebMvc
class WebConfig : WebMvcConfigurer {
// Implement configuration methods...
}
In XML, you can check attributes and sub-elements of <mvc:annotation-driven/>
. You can
view the Spring MVC XML schema or use
the code completion feature of your IDE to discover what attributes and
sub-elements are available.
1.12.3. Type Conversion
By default, formatters for various number and date types are installed, along with support
for customization via @NumberFormat
and @DateTimeFormat
on fields.
To register custom formatters and converters in Java config, use the following:
Java
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
@Override
public void addFormatters(FormatterRegistry registry) {
// ...
}
}
Kotlin
@Configuration
@EnableWebMvc
class WebConfig : WebMvcConfigurer {
override fun addFormatters(registry: FormatterRegistry) {
// ...
}
}
To do the same in XML config, use the following:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<mvc:annotation-driven conversion-service="conversionService"/>
<bean id="conversionService"
class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="org.example.MyConverter"/>
</set>
</property>
<property name="formatters">
<set>
<bean class="org.example.MyFormatter"/>
<bean class="org.example.MyAnnotationFormatterFactory"/>
</set>
</property>
<property name="formatterRegistrars">
<set>
<bean class="org.example.MyFormatterRegistrar"/>
</set>
</property>
</bean>
</beans>
By default Spring MVC considers the request Locale when parsing and formatting date
values. This works for forms where dates are represented as Strings with «input» form
fields. For «date» and «time» form fields, however, browsers use a fixed format defined
in the HTML spec. For such cases date and time formatting can be customized as follows:
Java
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
@Override
public void addFormatters(FormatterRegistry registry) {
DateTimeFormatterRegistrar registrar = new DateTimeFormatterRegistrar();
registrar.setUseIsoFormat(true);
registrar.registerFormatters(registry);
}
}
Kotlin
@Configuration
@EnableWebMvc
class WebConfig : WebMvcConfigurer {
override fun addFormatters(registry: FormatterRegistry) {
val registrar = DateTimeFormatterRegistrar()
registrar.setUseIsoFormat(true)
registrar.registerFormatters(registry)
}
}
See the FormatterRegistrar SPIand the FormattingConversionServiceFactoryBean for more information on when to useFormatterRegistrar implementations. |
1.12.4. Validation
By default, if Bean Validation is present
on the classpath (for example, Hibernate Validator), the LocalValidatorFactoryBean
is
registered as a global Validator for use with @Valid
and
Validated
on controller method arguments.
In Java configuration, you can customize the global Validator
instance, as the
following example shows:
Java
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
@Override
public Validator getValidator() {
// ...
}
}
Kotlin
@Configuration
@EnableWebMvc
class WebConfig : WebMvcConfigurer {
override fun getValidator(): Validator {
// ...
}
}
The following example shows how to achieve the same configuration in XML:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<mvc:annotation-driven validator="globalValidator"/>
</beans>
Note that you can also register Validator
implementations locally, as the following
example shows:
Java
@Controller
public class MyController {
@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.addValidators(new FooValidator());
}
}
Kotlin
@Controller
class MyController {
@InitBinder
protected fun initBinder(binder: WebDataBinder) {
binder.addValidators(FooValidator())
}
}
If you need to have a LocalValidatorFactoryBean injected somewhere, create a bean andmark it with @Primary in order to avoid conflict with the one declared in the MVC configuration.
|
1.12.5. Interceptors
In Java configuration, you can register interceptors to apply to incoming requests, as
the following example shows:
Java
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LocaleChangeInterceptor());
registry.addInterceptor(new ThemeChangeInterceptor()).addPathPatterns("/**").excludePathPatterns("/admin/**");
}
}
Kotlin
@Configuration
@EnableWebMvc
class WebConfig : WebMvcConfigurer {
override fun addInterceptors(registry: InterceptorRegistry) {
registry.addInterceptor(LocaleChangeInterceptor())
registry.addInterceptor(ThemeChangeInterceptor()).addPathPatterns("/**").excludePathPatterns("/admin/**")
}
}
The following example shows how to achieve the same configuration in XML:
<mvc:interceptors>
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"/>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<mvc:exclude-mapping path="/admin/**"/>
<bean class="org.springframework.web.servlet.theme.ThemeChangeInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
Mapped interceptors are not ideally suited as a security layer due to the potential for a mismatch with annotated controller path matching, which can also match trailing slashes and path extensions transparently, along with other path matching options. Many of these options have been deprecated but the potential for a mismatch remains. Generally, we recommend using Spring Security which includes a dedicated MvcRequestMatcher to align with Spring MVC path matching and also has a security firewall that blocks many unwanted characters in URL paths. |
1.12.6. Content Types
You can configure how Spring MVC determines the requested media types from the request
(for example, Accept
header, URL path extension, query parameter, and others).
By default, only the Accept
header is checked.
If you must use URL-based content type resolution, consider using the query parameter
strategy over path extensions. See
Suffix Match and Suffix Match and RFD for
more details.
In Java configuration, you can customize requested content type resolution, as the
following example shows:
Java
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.mediaType("json", MediaType.APPLICATION_JSON);
configurer.mediaType("xml", MediaType.APPLICATION_XML);
}
}
Kotlin
@Configuration
@EnableWebMvc
class WebConfig : WebMvcConfigurer {
override fun configureContentNegotiation(configurer: ContentNegotiationConfigurer) {
configurer.mediaType("json", MediaType.APPLICATION_JSON)
configurer.mediaType("xml", MediaType.APPLICATION_XML)
}
}
The following example shows how to achieve the same configuration in XML:
<mvc:annotation-driven content-negotiation-manager="contentNegotiationManager"/>
<bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
<property name="mediaTypes">
<value>
json=application/json
xml=application/xml
</value>
</property>
</bean>
1.12.7. Message Converters
You can customize HttpMessageConverter
in Java configuration by overriding
configureMessageConverters()
(to replace the default converters created by Spring MVC) or by overriding
extendMessageConverters()
(to customize the default converters or add additional converters to the default ones).
The following example adds XML and Jackson JSON converters with a customized
ObjectMapper
instead of the default ones:
Java
@Configuration
@EnableWebMvc
public class WebConfiguration implements WebMvcConfigurer {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder()
.indentOutput(true)
.dateFormat(new SimpleDateFormat("yyyy-MM-dd"))
.modulesToInstall(new ParameterNamesModule());
converters.add(new MappingJackson2HttpMessageConverter(builder.build()));
converters.add(new MappingJackson2XmlHttpMessageConverter(builder.createXmlMapper(true).build()));
}
}
Kotlin
@Configuration
@EnableWebMvc
class WebConfiguration : WebMvcConfigurer {
override fun configureMessageConverters(converters: MutableList<HttpMessageConverter<*>>) {
val builder = Jackson2ObjectMapperBuilder()
.indentOutput(true)
.dateFormat(SimpleDateFormat("yyyy-MM-dd"))
.modulesToInstall(ParameterNamesModule())
converters.add(MappingJackson2HttpMessageConverter(builder.build()))
converters.add(MappingJackson2XmlHttpMessageConverter(builder.createXmlMapper(true).build()))
In the preceding example,
Jackson2ObjectMapperBuilder
is used to create a common configuration for both MappingJackson2HttpMessageConverter
and
MappingJackson2XmlHttpMessageConverter
with indentation enabled, a customized date format,
and the registration of
jackson-module-parameter-names
,
Which adds support for accessing parameter names (a feature added in Java 8).
This builder customizes Jackson’s default properties as follows:
-
DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES
is disabled. -
MapperFeature.DEFAULT_VIEW_INCLUSION
is disabled.
It also automatically registers the following well-known modules if they are detected on the classpath:
-
jackson-datatype-joda: Support for Joda-Time types.
-
jackson-datatype-jsr310: Support for Java 8 Date and Time API types.
-
jackson-datatype-jdk8: Support for other Java 8 types, such as
Optional
. -
jackson-module-kotlin
: Support for Kotlin classes and data classes.
Other interesting Jackson modules are available:
-
jackson-datatype-money: Support for
javax.money
types (unofficial module). -
jackson-datatype-hibernate: Support for Hibernate-specific types and properties (including lazy-loading aspects).
The following example shows how to achieve the same configuration in XML:
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper" ref="objectMapper"/>
</bean>
<bean class="org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter">
<property name="objectMapper" ref="xmlMapper"/>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<bean id="objectMapper" class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean"
p:indentOutput="true"
p:simpleDateFormat="yyyy-MM-dd"
p:modulesToInstall="com.fasterxml.jackson.module.paramnames.ParameterNamesModule"/>
<bean id="xmlMapper" parent="objectMapper" p:createXmlMapper="true"/>
1.12.8. View Controllers
This is a shortcut for defining a ParameterizableViewController
that immediately
forwards to a view when invoked. You can use it in static cases when there is no Java controller
logic to run before the view generates the response.
The following example of Java configuration forwards a request for /
to a view called home
:
Java
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("home");
}
}
Kotlin
@Configuration
@EnableWebMvc
class WebConfig : WebMvcConfigurer {
override fun addViewControllers(registry: ViewControllerRegistry) {
registry.addViewController("/").setViewName("home")
}
}
The following example achieves the same thing as the preceding example, but with XML, by
using the <mvc:view-controller>
element:
<mvc:view-controller path="/" view-name="home"/>
If an @RequestMapping
method is mapped to a URL for any HTTP method then a view
controller cannot be used to handle the same URL. This is because a match by URL to an
annotated controller is considered a strong enough indication of endpoint ownership so
that a 405 (METHOD_NOT_ALLOWED), a 415 (UNSUPPORTED_MEDIA_TYPE), or similar response can
be sent to the client to help with debugging. For this reason it is recommended to avoid
splitting URL handling across an annotated controller and a view controller.
1.12.9. View Resolvers
The MVC configuration simplifies the registration of view resolvers.
The following Java configuration example configures content negotiation view
resolution by using JSP and Jackson as a default View
for JSON rendering:
Java
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
registry.enableContentNegotiation(new MappingJackson2JsonView());
registry.jsp();
}
}
Kotlin
@Configuration
@EnableWebMvc
class WebConfig : WebMvcConfigurer {
override fun configureViewResolvers(registry: ViewResolverRegistry) {
registry.enableContentNegotiation(MappingJackson2JsonView())
registry.jsp()
}
}
The following example shows how to achieve the same configuration in XML:
<mvc:view-resolvers>
<mvc:content-negotiation>
<mvc:default-views>
<bean class="org.springframework.web.servlet.view.json.MappingJackson2JsonView"/>
</mvc:default-views>
</mvc:content-negotiation>
<mvc:jsp/>
</mvc:view-resolvers>
Note, however, that FreeMarker, Tiles, Groovy Markup, and script templates also require
configuration of the underlying view technology.
The MVC namespace provides dedicated elements. The following example works with FreeMarker:
<mvc:view-resolvers>
<mvc:content-negotiation>
<mvc:default-views>
<bean class="org.springframework.web.servlet.view.json.MappingJackson2JsonView"/>
</mvc:default-views>
</mvc:content-negotiation>
<mvc:freemarker cache="false"/>
</mvc:view-resolvers>
<mvc:freemarker-configurer>
<mvc:template-loader-path location="/freemarker"/>
</mvc:freemarker-configurer>
In Java configuration, you can add the respective Configurer
bean,
as the following example shows:
Java
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
registry.enableContentNegotiation(new MappingJackson2JsonView());
registry.freeMarker().cache(false);
}
@Bean
public FreeMarkerConfigurer freeMarkerConfigurer() {
FreeMarkerConfigurer configurer = new FreeMarkerConfigurer();
configurer.setTemplateLoaderPath("/freemarker");
return configurer;
}
}
Kotlin
@Configuration
@EnableWebMvc
class WebConfig : WebMvcConfigurer {
override fun configureViewResolvers(registry: ViewResolverRegistry) {
registry.enableContentNegotiation(MappingJackson2JsonView())
registry.freeMarker().cache(false)
}
@Bean
fun freeMarkerConfigurer() = FreeMarkerConfigurer().apply {
setTemplateLoaderPath("/freemarker")
}
}
1.12.10. Static Resources
This option provides a convenient way to serve static resources from a list of
Resource
-based locations.
In the next example, given a request that starts with /resources
, the relative path is
used to find and serve static resources relative to /public
under the web application
root or on the classpath under /static
. The resources are served with a one-year future
expiration to ensure maximum use of the browser cache and a reduction in HTTP requests
made by the browser. The Last-Modified
information is deduced from Resource#lastModified
so that HTTP conditional requests are supported with "Last-Modified"
headers.
The following listing shows how to do so with Java configuration:
Java
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**")
.addResourceLocations("/public", "classpath:/static/")
.setCacheControl(CacheControl.maxAge(Duration.ofDays(365)));
}
}
Kotlin
@Configuration
@EnableWebMvc
class WebConfig : WebMvcConfigurer {
override fun addResourceHandlers(registry: ResourceHandlerRegistry) {
registry.addResourceHandler("/resources/**")
.addResourceLocations("/public", "classpath:/static/")
.setCacheControl(CacheControl.maxAge(Duration.ofDays(365)))
}
}
The following example shows how to achieve the same configuration in XML:
<mvc:resources mapping="/resources/**"
location="/public, classpath:/static/"
cache-period="31556926" />
See also
HTTP caching support for static resources.
The resource handler also supports a chain of
ResourceResolver
implementations and
ResourceTransformer
implementations,
which you can use to create a toolchain for working with optimized resources.
You can use the VersionResourceResolver
for versioned resource URLs based on an MD5 hash
computed from the content, a fixed application version, or other. A
ContentVersionStrategy
(MD5 hash) is a good choice — with some notable exceptions, such as
JavaScript resources used with a module loader.
The following example shows how to use VersionResourceResolver
in Java configuration:
Java
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**")
.addResourceLocations("/public/")
.resourceChain(true)
.addResolver(new VersionResourceResolver().addContentVersionStrategy("/**"));
}
}
Kotlin
@Configuration
@EnableWebMvc
class WebConfig : WebMvcConfigurer {
override fun addResourceHandlers(registry: ResourceHandlerRegistry) {
registry.addResourceHandler("/resources/**")
.addResourceLocations("/public/")
.resourceChain(true)
.addResolver(VersionResourceResolver().addContentVersionStrategy("/**"))
}
}
The following example shows how to achieve the same configuration in XML:
<mvc:resources mapping="/resources/**" location="/public/">
<mvc:resource-chain resource-cache="true">
<mvc:resolvers>
<mvc:version-resolver>
<mvc:content-version-strategy patterns="/**"/>
</mvc:version-resolver>
</mvc:resolvers>
</mvc:resource-chain>
</mvc:resources>
You can then use ResourceUrlProvider
to rewrite URLs and apply the full chain of resolvers and
transformers — for example, to insert versions. The MVC configuration provides a ResourceUrlProvider
bean so that it can be injected into others. You can also make the rewrite transparent with the
ResourceUrlEncodingFilter
for Thymeleaf, JSPs, FreeMarker, and others with URL tags that
rely on HttpServletResponse#encodeURL
.
Note that, when using both EncodedResourceResolver
(for example, for serving gzipped or
brotli-encoded resources) and VersionResourceResolver
, you must register them in this order.
That ensures content-based versions are always computed reliably, based on the unencoded file.
For WebJars, versioned URLs like
/webjars/jquery/1.2.0/jquery.min.js
are the recommended and most efficient way to use them.
The related resource location is configured out of the box with Spring Boot (or can be configured
manually via ResourceHandlerRegistry
) and does not require to add the
org.webjars:webjars-locator-core
dependency.
Version-less URLs like /webjars/jquery/jquery.min.js
are supported through the
WebJarsResourceResolver
which is automatically registered when the
org.webjars:webjars-locator-core
library is present on the classpath, at the cost of a
classpath scanning that could slow down application startup. The resolver can re-write URLs to
include the version of the jar and can also match against incoming URLs without versions — for example, from /webjars/jquery/jquery.min.js
to /webjars/jquery/1.2.0/jquery.min.js
.
The Java configuration based on ResourceHandlerRegistry provides further optionsfor fine-grained control, e.g. last-modified behavior and optimized resource resolution. |
1.12.11. Default Servlet
Spring MVC allows for mapping the DispatcherServlet
to /
(thus overriding the mapping
of the container’s default Servlet), while still allowing static resource requests to be
handled by the container’s default Servlet. It configures a
DefaultServletHttpRequestHandler
with a URL mapping of /**
and the lowest priority
relative to other URL mappings.
This handler forwards all requests to the default Servlet. Therefore, it must
remain last in the order of all other URL HandlerMappings
. That is the
case if you use <mvc:annotation-driven>
. Alternatively, if you set up your
own customized HandlerMapping
instance, be sure to set its order
property to a value
lower than that of the DefaultServletHttpRequestHandler
, which is Integer.MAX_VALUE
.
The following example shows how to enable the feature by using the default setup:
Java
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
Kotlin
@Configuration
@EnableWebMvc
class WebConfig : WebMvcConfigurer {
override fun configureDefaultServletHandling(configurer: DefaultServletHandlerConfigurer) {
configurer.enable()
}
}
The following example shows how to achieve the same configuration in XML:
<mvc:default-servlet-handler/>
The caveat to overriding the /
Servlet mapping is that the RequestDispatcher
for the
default Servlet must be retrieved by name rather than by path. The
DefaultServletHttpRequestHandler
tries to auto-detect the default Servlet for
the container at startup time, using a list of known names for most of the major Servlet
containers (including Tomcat, Jetty, GlassFish, JBoss, Resin, WebLogic, and WebSphere).
If the default Servlet has been custom-configured with a different name, or if a
different Servlet container is being used where the default Servlet name is unknown,
then you must explicitly provide the default Servlet’s name, as the following example shows:
Java
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable("myCustomDefaultServlet");
}
}
Kotlin
@Configuration
@EnableWebMvc
class WebConfig : WebMvcConfigurer {
override fun configureDefaultServletHandling(configurer: DefaultServletHandlerConfigurer) {
configurer.enable("myCustomDefaultServlet")
}
}
The following example shows how to achieve the same configuration in XML:
<mvc:default-servlet-handler default-servlet-name="myCustomDefaultServlet"/>
1.12.12. Path Matching
You can customize options related to path matching and treatment of the URL.
For details on the individual options, see the
PathMatchConfigurer
javadoc.
The following example shows how to customize path matching in Java configuration:
Java
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
configurer.addPathPrefix("/api", HandlerTypePredicate.forAnnotation(RestController.class));
}
private PathPatternParser patternParser() {
// ...
}
}
Kotlin
@Configuration
@EnableWebMvc
class WebConfig : WebMvcConfigurer {
override fun configurePathMatch(configurer: PathMatchConfigurer) {
configurer.addPathPrefix("/api", HandlerTypePredicate.forAnnotation(RestController::class.java))
}
fun patternParser(): PathPatternParser {
//...
}
}
The following example shows how to customize path matching in XML configuration:
<mvc:annotation-driven>
<mvc:path-matching
path-helper="pathHelper"
path-matcher="pathMatcher"/>
</mvc:annotation-driven>
<bean id="pathHelper" class="org.example.app.MyPathHelper"/>
<bean id="pathMatcher" class="org.example.app.MyPathMatcher"/>
1.12.13. Advanced Java Config
@EnableWebMvc
imports DelegatingWebMvcConfiguration
, which:
-
Provides default Spring configuration for Spring MVC applications
-
Detects and delegates to
WebMvcConfigurer
implementations to customize that configuration.
For advanced mode, you can remove @EnableWebMvc
and extend directly from
DelegatingWebMvcConfiguration
instead of implementing WebMvcConfigurer
,
as the following example shows:
Java
@Configuration
public class WebConfig extends DelegatingWebMvcConfiguration {
// ...
}
Kotlin
@Configuration
class WebConfig : DelegatingWebMvcConfiguration() {
// ...
}
You can keep existing methods in WebConfig
, but you can now also override bean declarations
from the base class, and you can still have any number of other WebMvcConfigurer
implementations on
the classpath.
1.12.14. Advanced XML Config
The MVC namespace does not have an advanced mode. If you need to customize a property on
a bean that you cannot change otherwise, you can use the BeanPostProcessor
lifecycle
hook of the Spring ApplicationContext
, as the following example shows:
Java
@Component
public class MyPostProcessor implements BeanPostProcessor {
public Object postProcessBeforeInitialization(Object bean, String name) throws BeansException {
// ...
}
}
Kotlin
@Component
class MyPostProcessor : BeanPostProcessor {
override fun postProcessBeforeInitialization(bean: Any, name: String): Any {
// ...
}
}
Note that you need to declare MyPostProcessor
as a bean, either explicitly in XML or
by letting it be detected through a <component-scan/>
declaration.
1.13. HTTP/2
Servlet 4 containers are required to support HTTP/2, and Spring Framework 5 is compatible
with Servlet API 4. From a programming model perspective, there is nothing specific that
applications need to do. However, there are considerations related to server configuration.
For more details, see the
HTTP/2 wiki page.
The Servlet API does expose one construct related to HTTP/2. You can use the
jakarta.servlet.http.PushBuilder
to proactively push resources to clients, and it
is supported as a method argument to @RequestMapping
methods.
In this article, I will explain how to return custom HTTP errors in Spring Boot. When we make an HTTP request to a resource, it is common that the request has to consider the option of returning an error.
It is the typical case that we made a RESTful request to query for a record, but it does not exist. In this case, you will usually return an HTTP code 404 (Not Found), and with this code, you also return a JSON object that with a a format defined for Spring Boot, like this:
{
"timestamp": "2018-11-20T11:46:10.255+0000",
"status": 404,
"error": "Not Found",
"message": "bean: 8 not Found",
"path": "/get/8"
}
But if we want the output to be something like this:
{
"timestamp": "2018-11-20T12:51:42.699+0000",
"mensaje": "bean: 8 not Found",
"detalles": "uri=/get/8",
"httpCodeMessage": "Not Found"
}
We have to put a series of classes to our project. Here, I explain how.
I have the source code in my repository on GitHub.
Starting from a basic project Spring Boot, where we have a simple object called MiBean
with only two fields: code
and value
.This object will be returned in the requests to the resource /get
so that a request to: http://localhost: 8080/get /1 return a JSON object like this:
{
"codigo": 1,
"valor": "valor uno"
}
If you try to access a higher element three, it will return an error because only three records are available.
This is the class ErrorResource
that process the requests to the resource /get
.
public class ErrorResource {
@Autowired
MiBeanService service;
@GetMapping("/get/{id}")
public MiBean getBean(@PathVariable int id) {
MiBean bean = null;
try
{
bean = service.getBean(id);
} catch (NoSuchElementException k)
{
throw new BeanNotFoundException("bean: "+id+ " not Found" );
}
return bean;
}
}
As seen in thegetBean()
function, we call to function getBean(int id)
of the MiBeanService
object. This is the source of that object.
@Component
public class MiBeanService {
private static List<MiBean> miBeans = new ArrayList<>();
static {
miBeans.add(new MiBean(1, "valor uno"));
miBeans.add(new MiBean(2, "valor dos"));
miBeans.add(new MiBean(3, "valor tres"));
}
public MiBean getBean(int id) {
MiBean miBean =
miBeans.stream()
.filter(t -> t.getCodigo()==id)
.findFirst()
.get();
return miBean;
}
}
The function getBean(int id)
throws an exception of the type NoSuchElementException
if it doesn’t find the value at List miBeans
. This exception will be captured in the controller and it throws a exception of typeBeanNotFoundException
.
ClassBeanNotFoundException
is as follows:
@ResponseStatus(HttpStatus.NOT_FOUND)
public class BeanNotFoundException extends RuntimeException {
public BeanNotFoundException(String message) {
super(message);
}
}
A simple class that extendsRuntimeException
, and this annotated with the tag @ResponseStatus(HttpStatus.NOT_FOUND)
will return a 404 code to the client.
Now if we make a request for a code greater than three, we will receive this response:
But, as we said, we want the error message is customized.
To do this, we will create a new class where our fields define the error message. This class is ExceptionResponse
, which is a simple POJO as you can see in the code attached:
public class ExceptionResponse {
private Date timestamp;
private String mensaje;
private String detalles;
private String httpCodeMessage;
public ExceptionResponse(Date timestamp, String message, String details,String httpCodeMessage) {
super();
this.timestamp = timestamp;
this.mensaje = message;
this.detalles = details;
this.httpCodeMessage=httpCodeMessage;
}
public String getHttpCodeMessage() {
return httpCodeMessage;
}
public Date getTimestamp() {
return timestamp;
}
public String getMensaje() {
return mensaje;
}
public String getDetalles() {
return detalles;
}
}
This is the class to indicate which is the JSON object that it should return if an exception of type BeanNotFoundException
is thrown.
And now, we write the code to configure Spring for throw this JSON object.
This is the write-in: CustomizedResponseEntityExceptionHandler
, which is attached below:
@ControllerAdvice
@RestController
public class CustomizedResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(BeanNotFoundException.class)
public final ResponseEntity<ExceptionResponse> handleNotFoundException(BeanNotFoundException ex, WebRequest request) {
ExceptionResponse exceptionResponse = new ExceptionResponse(new Date(), ex.getMessage(),
request.getDescription(false),HttpStatus.NOT_ACCEPTABLE.getReasonPhrase());
return new ResponseEntity<ExceptionResponse>(exceptionResponse, HttpStatus.NOT_ACCEPTABLE);
}
}
This class must extend the ResponseEntityExceptionHandler
, which handles the most common exceptions.
We annotate it with the labels @ControllerAdvice
and @RestController
.
@ControllerAdvice
is derived from @Component
and will be used for classes that deal with exceptions. And as the class has the @RestContoller
label, it handles only exceptions thrown in REST controllers.
In the handleNotFoundException
function, we have defined that when BeanNotFoundException
exception is thrown, it must return a ExceptionResponse
object. This is done by creating an object ResponseEntity
conveniently initiated.
It is important to note that it defines the HTTP code returned. In this case, we return the code 406 instead of the 404. In fact, in our example, we could remove the label @ResponseStatus(HttpStatus.NOT_FOUND)
to the class BeanNotFoundException
and everything would work the same.
And so, we have a custom output, as shown in the following image:
Opinions expressed by DZone contributors are their own.
TL/DR: Let’s take a look at everything required to build custom error handling logic in both Spring Boot Web and Spring Boot Security
REST applications developed in Spring Boot automatically take advantage of its default error handling logic. Specifically, whenever an error occurs, a default response containing some information is returned. The problem is that this information may be poor or insufficient for the API callers to deal with the error properly. This is why implementing custom error handling logic is such a common and desirable task. Achieving it requires more effort than you might think, and you need to delve into a few essential Spring Boot notions. Let’s see everything required to get started with custom error handling in Spring Boot and Java.
Prerequisites
This is the list of all the prerequisites for following the article:
- Java >= 1.8 (Java >= 13 recommended)
- Spring Boot >= 2.5
- Spring Boot Starter Web >= 2.5
- Spring Security >= 5.5
- Project Lombok >= 1.18
- Gradle >= 4.x or Maven 3.6.x
Default Error Handling in Spring Boot
By default, Spring Boot offers a fallback error-handling page, as well as an error-handling response in case of REST requests. Particularly, Spring Boot looks for a mapping for the /error
endpoint during the start-up. This mapping depends on what is set on a ViewResolver
class. When no valid mappings can be found, Spring Boot automatically configures a default fallback error page. This so-called Whitelabel Error Page is nothing more than a white HTML page containing the HTTP status code and a vague error message. This is what such a page looks like:
<html>
<head></head>
<body data-new-gr-c-s-check-loaded="14.1026.0" data-gr-ext-installed="">
<h1>Whitelabel Error Page</h1>
<p>This application has no explicit mapping for /error, so you are seeing this as a fallback.</p>
<div id="created">Sun Aug 15 14:32:17 UTC 2021</div>
<div>There was an unexpected error (type=Internal Server Error, status=500).</div>
<div></div>
</body>
</html>
This is what the Whitelabel HTML page looks like in your browser:
The Spring Boot Whitelabel HTML Error Page
Similarly, when dealing with REST requests, Spring Boot automatically returns a default JSON response in case of errors. This contains the same information as the aforementioned Whitelabel HTML error page and looks as follows:
{
"timestamp": "2021-15-08T14:32:17.947+0000",
"status": 500,
"error": "Internal Server Error",
"path": "/test"
}
As you can see, the default Spring Boot error handling responses for REST does not provide much information. This can quickly become a problem, especially when trying to debug. It is also problematic for front-end developers, who need detailed information coming from API error response messages to be able to explain to the end users what happened properly.
Let’s see how to replace this default response with custom-defined messages. While this may appear like an easy task, this is actually a tricky one. To achieve it, you first need to know a few Spring Boot fundamentals. Let’s learn more about them.
Custom Error Handling in Spring Boot
You are about to see two different approaches to custom error handling in Spring Boot REST applications. Both are based on a @ControllerAdvice
annotated class handling all exceptions that may occur. So, let’s first see what a @ControllerAdvice
annotated class is, why to use it, how, and when. Then, you will learn how to implement the two different approaches in detail. Finally, the pros and cons of each method will be explained.
Handling Exceptions with @ControllerAdvice
The @ControllerAdvice
annotation was introduced in Spring 3.2 to make exception handling logic easier and entirely definable in one place. In fact, @ControllerAdvice
allows you to address exception handling across the whole application. In other words, a single @ControllerAdvice
annotated class can handle exceptions thrown from any place in your application. Thus, classes annotated with @ControllerAdvice
are powerful and flexible tools. Not only do they allow you to centralize exception-handling logic into a global component, but also give you control over the body response, as well as the HTTP status code. This is especially important when trying to achieve custom error handling. Let’s see @ControllerAdvice
in action.
Now, you are about to see everything required to implement two custom error handling approaches based on @ControllerAdvice
. First, you should clone the GitHub repository supporting this article. By analyzing the codebase, going through this article will become easier. Also, you will be able to immediately see the two approaches in action.
So, clone the repository with the following command:
git clone https://github.com/Tonel/spring-boot-custom-error-handling
Then, run the DemoApplication
main class by following this guide from the Spring Boot official documentation, and reach one of the following 4 endpoints to see the custom error handling responses:
http://localhost:8080/test-custom-data-not-found-exception
http://localhost:8080/test-custom-parameter-constraint-exception?value=12
http://localhost:8080/test-custom-error-exception
http://localhost:8080/test-generic-exception
The first two APIs apply the first approach to error handling you are about to see, while the third API uses the second approach. The fourth and last API shows the fallback error handling logic presented above in action. Now, let’s delve into implementing these two approaches to custom error handling in Spring Boot.
Both of them rely on an ErrorMessage
class representing the custom error body placed in an error
package, containing everything needed to deal with custom error handling logic. This can be implemented as follows:
// src/main/java/com/customerrorhandling/demo/errors/ErrorResponse.java
package com.customerrorhandling.demo.errors;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Getter;
import lombok.Setter;
import org.springframework.http.HttpStatus;
import java.util.Date;
@Getter
@Setter
public class ErrorResponse {
// customizing timestamp serialization format
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy hh:mm:ss")
private Date timestamp;
private int code;
private String status;
private String message;
private String stackTrace;
private Object data;
public ErrorResponse() {
timestamp = new Date();
}
public ErrorResponse(
HttpStatus httpStatus,
String message
) {
this();
this.code = httpStatus.value();
this.status = httpStatus.name();
this.message = message;
}
public ErrorResponse(
HttpStatus httpStatus,
String message,
String stackTrace
) {
this(
httpStatus,
message
);
this.stackTrace = stackTrace;
}
public ErrorResponse(
HttpStatus httpStatus,
String message,
String stackTrace,
Object data
) {
this(
httpStatus,
message,
stackTrace
);
this.data = data;
}
}
The @Getter
and @Setter
annotations used in the code examples above are part of the Project Lombok
. They are used to automatically generate getters and setters. This is not mandatory and is just an additional way to avoid boilerplate code. Read this article to find out more about Lombok.
ErrorResponse
carries information such as an HTTP status code
and name
, a timestamp
indicating when the error occurred, an optional error message
, an optional exception stacktrace
, and an optional object containing any kind of data
. You should try to provide values to the first three fields, while the latter should be used only when required. In particular, the stackTrace
field should be valorized only in staging or development environments, as explained here. Similarly, the data field should be used only when additional data is required. Specifically, to explain in detail what happened or let the front-end better handle the error.
This class can be used to achieve a custom response when handling exceptions with @ControllerAdvice
as below:
// src/main/java/com/customerrorhandling/demo/errors/CustomControllerAdvice.java
package com.customerrorhandling.demo.errors;
import exceptions.CustomDataNotFoundException;
import exceptions.CustomErrorException;
import exceptions.CustomParameterConstraintException;
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 java.io.PrintWriter;
import java.io.StringWriter;
@ControllerAdvice
class CustomControllerAdvice {
@ExceptionHandler(NullPointerException.class) // exception handled
public ResponseEntity<ErrorResponse> handleNullPointerExceptions(
Exception e
) {
// ... potential custom logic
HttpStatus status = HttpStatus.NOT_FOUND; // 404
return new ResponseEntity<>(
new ErrorResponse(
status,
e.getMessage()
),
status
);
}
// fallback method
@ExceptionHandler(Exception.class) // exception handled
public ResponseEntity<ErrorResponse> handleExceptions(
Exception e
) {
// ... potential custom logic
HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR; // 500
// converting the stack trace to String
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
e.printStackTrace(printWriter);
String stackTrace = stringWriter.toString();
return new ResponseEntity<>(
new ErrorResponse(
status,
e.getMessage(),
stackTrace // specifying the stack trace in case of 500s
),
status
);
}
}
As you can see, @ControllerAdvice
works by employing the @ExceptionHandler
method-level annotation. This annotation allows you to define which method should be called in case of an error. Specifically, the exception thrown is compared to the exceptions passed as parameters to @ExceptionHandler
based on type. The first method where there is a match is called. If none matched, then the exception’s parent class is tested, and so on. This is also why you should implement a fallback method to cover all remaining cases. You can achieve this by passing the Exception
class to the @ExceptionHandler
annotation, just like in the handleExceptions
method. In fact, any exception in Java must have Exception
as one of its ancestors in their inheritance chain. So, they all extend directly — or as subclasses — the Exception
superclass.
Then, each method handles the error and might even implement custom logic, such as logging. In this example, each exception is handled by returning a ResponseEntity
having the desired HttpStatus
. This will be used as an HTTP status code associated with the error response. Similarly, the ErrorResponse
instance passed to the ResponseEntity
constructor will be automatically serialized in JSON and used as the message body. This way, custom error handling has just been achieved.
Now, you will dive into how to use @ConfrollerAdvice
to implement two different approaches to custom error handling for REST in Spring Boot Web. The first one involves boilerplate code, but it is clean and best-practice based. In contrast, the second represents a good solution in terms of convenience, although it is a bit dirty.
Defining Many Custom Exceptions
This approach involves having as many methods in your @ControllerAdvice
as many HTTP error status codes you want to handle. These methods will be related to one or more exceptions and return an error message with a particular HTTP status code. Implementing such an approach required three steps. First, you have to think about all the HTTP error status codes you want your application to return. Then, you have to define a method for each of them in your @ControllerAdvice
annotated class. Lastly, you have to associate these methods with their exceptions with the @ExceptionHandler
annotation.
This means that all exceptions of a particular type will be traced back to their relative method in the @ControllerAdvice
annotated class. This may represent a problem, especially considering some exceptions are more common than others, such as NullPointerException
. Since these exceptions can be thrown in many parts of your logic, they might have different meanings. Thus, they represent various errors and, therefore, other HTTP status codes.
The solution is to introduce new custom exceptions wrapping these frequent exceptions. For example, a NullPointerException
can become a CustomParameterConstraintException
exception at the controller layer, and a CustomDataNotFoundException
at the DAO (Data Access Object) layer. In this case, the first one can be associated with a 400 Bad Request, and the second with a 404 Not Found HTTP status. The idea behind these exceptions is to give the error that occurred a more specific meaning. This better characterizes the error and makes it more handleable in the @ControllerAdvice
annotated class accordingly. So, you should define a custom exception for each particular error you want to handle. Also, using custom exception classes represents undoubtedly a clean code principle. Thus, by adopting it, you are going to have more than one benefit.
So, let’s see this approach in action through an example. Firstly, you have to define custom exceptions, as shown here:
// src/main/java/exceptions/CustomParameterConstraintException.java
package exceptions;
public class CustomParameterConstraintException extends RuntimeException {
public CustomParameterConstraintException() {
super();
}
public CustomParameterConstraintException(String message) {
super(message);
}
}
// src/main/java/exceptions/CustomDataNotFoundException.java
package exceptions;
public class CustomDataNotFoundException extends RuntimeException {
public CustomDataNotFoundException() {
super();
}
public CustomDataNotFoundException(String message) {
super(message);
}
}
Then, use them to wrap frequent exceptions, or to throw them in case of particular circumstances representing errors in your business logic. Let’s see how with two examples:
// DAO-level method
public Foo retrieveFooById(
int id
) {
try {
// data retrieving logic
} catch (NullPointerException e) {
throw new CustomDataNotFoundException(e.getMessage());
}
}
As shown above, a generic NullPointerException
is turned into a more meaningful CustomDataNotFoundException
.
// controller-level method method
public ResponseEntity<Void> performOperation(
int numberOfAttempts
) {
if (numberOfAttempts <= 0 || numberOfAttempts >= 5)
throw new CustomParameterConstraintException("numberOfAttempts must be >= 0 and <= 5!");
// business logic
}
Here, a particular behavior that should not happen is intercepted. Then, the custom CustomParameterConstraintException
exception describing it is thrown.
Finally, all you have to do is add two particular methods to your @ControllerAdvice
annotated class, one for each specific error.
// src/main/java/com/customerrorhandling/demo/errors/CustomControllerAdvice.java
package com.customerrorhandling.demo.errors;
import exceptions.CustomDataNotFoundException;
import exceptions.CustomErrorException;
import exceptions.CustomParameterConstraintException;
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 java.io.PrintWriter;
import java.io.StringWriter;
@ControllerAdvice
class CustomControllerAdvice {
// ...
@ExceptionHandler(CustomDataNotFoundException.class)
public ResponseEntity<ErrorResponse> handleCustomDataNotFoundExceptions(
Exception e
) {
HttpStatus status = HttpStatus.NOT_FOUND; // 404
// converting the stack trace to String
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
e.printStackTrace(printWriter);
String stackTrace = stringWriter.toString();
return new ResponseEntity<>(
new ErrorResponse(
status,
e.getMessage(),
stackTrace, // assuming to be in staging environment, otherwise stackTrace should not be valorized
),
status
);
}
@ExceptionHandler(CustomParameterConstraintException.class)
public ResponseEntity<ErrorResponse> handleCustomParameterConstraintExceptions(
Exception e
) {
HttpStatus status = HttpStatus.BAD_REQUEST; // 400
return new ResponseEntity<>(
new ErrorResponse(
status,
e.getMessage()
),
status
);
}
// ...
}
Et voilà! Both errors originally related to the same exception were first characterized and then handled accordingly.
Now, let’s see the difference. This is what the default error response would look like on a 404 error:
{
"timestamp": "2021-15-08T14:32:17.947+0000",
"status": 404,
"error": "Not Found",
"path": "/test404"
}
And this is what the custom error response just implemented looks like:
{
"timestamp": "2021-15-08 14:32:17",
"code": 404,
"status": "NOT_FOUND",
"message": "Resource not found",
"stackTrace": "Exception in thread "main" com.example.demo.exceptions.CustomDataNotFoundException
at com.example.demo.AuthorController.getAuthor(AuthorController.java:16)
at com.example.demo.AuthorService.getAuthor(AuthorService.java:37)
at com.example.demo.AuthorDao.getById(AuthorDao.java:24)"
}
Defining a Single Custom Exception Carrying All Data
This approach involves defining a custom exception carrying the HTTP status to use, and all the data required to describe the error that occurred. The idea is to turn every exception you want to handle, or you would like to throw under special circumstances, into an instance of this particular exception. This way, you are spreading the error characterization logic into all your code. So, you will only have to add a new method in your @ControllerAdvice
annotated class to handle this custom exception accordingly.
First, you have to define a custom error handling exception. This can be achieved as follows:
// src/main/java/exceptions/CustomErrorException.java
package exceptions;
import lombok.Getter;
import lombok.Setter;
import org.springframework.http.HttpStatus;
@Getter
@Setter
public class CustomErrorException extends RuntimeException {
private HttpStatus status = null;
private Object data = null;
public CustomErrorException() {
super();
}
public CustomErrorException(
String message
) {
super(message);
}
public CustomErrorException(
HttpStatus status,
String message
) {
this(message);
this.status = status;
}
public CustomErrorException(
HttpStatus status,
String message,
Object data
) {
this(
status,
message
);
this.data = data;
}
}
Again, the @Getter
and @Setter
annotations were used to avoid boilerplate code and are not mandatory. As you can see, the CustomErrorException
class carries the same data used in the ErrorResponse
class to better describe what happened and present the errors to the end-users.
So, you can use this exception to wrap other exceptions, or you can throw it in case of particular circumstances constituting errors in your business logic. Now, let’s see how with two examples:
// DAO-level method
public Foo retrieveFooById(
int id
) {
try {
// data retrieving logic
} catch (NullPointerException e) {
throw new CustomErrorException(
HttpStatus.NOT_FOUND,
e.getMessage(),
(Integer) id
);
}
}
Here, an insufficiently significant NullPointerException
is turned into a more detailed CustomErrorException
containing all the data to describe why the error occurred.
// controller-level method method
public ResponseEntity<Void> performOperation(
int numberOfAttempts
) {
if (numberOfAttempts <= 0 || numberOfAttempts >= 5) {
throw new CustomErrorException(
HttpStatus.BAD_REQUEST,
"numberOfAttempts must be >= 0 and <= 5!",
(Integer) numberOfAttempts
);
}
// business logic
}
Similarly, a particular behavior that is not supposed to happen is intercepted. Consequently, a CustomErrorException
exception containing all the useful data to represent the error is thrown.
Lastly, add one method to handle CustomErrorException
exception instances to your @ControllerAdvice
annotated class, as below:
// src/main/java/com/customerrorhandling/demo/errors/CustomControllerAdvice.java
package com.customerrorhandling.demo.errors;
import exceptions.CustomDataNotFoundException;
import exceptions.CustomErrorException;
import exceptions.CustomParameterConstraintException;
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 java.io.PrintWriter;
import java.io.StringWriter;
@ControllerAdvice
class CustomControllerAdvice {
// ...
@ExceptionHandler(CustomErrorException.class)
public ResponseEntity<ErrorResponse> handleCustomErrorExceptions(
Exception e
) {
// casting the generic Exception e to CustomErrorException
CustomErrorException customErrorException = (CustomErrorException) e;
HttpStatus status = customErrorException.getStatus();
// converting the stack trace to String
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
customErrorException.printStackTrace(printWriter);
String stackTrace = stringWriter.toString();
return new ResponseEntity<>(
new ErrorResponse(
status,
customErrorException.getMessage(),
stackTrace,
customErrorException.getData()
),
status
);
}
// ...
}
Note that @ExceptionHandler
can accept more than one exception type. This means that the parameter of the method representing the exception must be downcasted. Otherwise, a ClassCastException
will be throw. So, upcast the exception e
to CustomErrorException
inside the method. Then, you will be able to access its particular fields and define a valid ErrorResponse
instance.
Done! This way each error that occurs is encapsulated into an exception containing everything required to describe it.
Now, let’s see the difference. This is what the default error response on a 404 error would look like:
{
"timestamp": "2021-15-08T14:32:17.947+0000",
"status": 404,
"error": "Not Found",
"message": "",
"path": "/test404"
}
And this is what the custom error response just implemented looks like:
{
"timestamp": "2021-15-08 14:32:17",
"code": 404,
"status": "NOT_FOUND",
"message": "Resource not found",
"stackTrace": "Exception in thread "main" com.example.demo.exceptions.CustomErrorException
at com.example.demo.AuthorController.getAuthor(AuthorController.java:16)
at com.example.demo.AuthorService.getAuthor(AuthorService.java:37)
at com.example.demo.AuthorDao.getById(AuthorDao.java:24)"
}
Pros and Cons of Each Approach
The first approach should be used when you do not want to spread error handling logic all over your codebase. In fact, the HTTP status code is only associated with errors in your @ControllerAdvice
annotated class. This means that no layer knows how the error will be handled and presented to users. Although this should be the desired behavior because it respects the principle of least privilege, it does involve boilerplate code. In fact, you may easily end up with dozens of custom exceptions, and define them is a tedious and not-scalable approach.
So, you may want a less restricting approach, and this is why the second approach was presented. Unfortunately, this one is definitely dirtier. In fact, it requires you to spread detail about error handling logic in many different points of your code. In contrast, it is scalable and quicker to be implemented. So, despite not being the cleanest approach, it allows you to achieve the desired result with little effort. Plus, it is more maintainable than the first approach because it involves only a custom exception.
Custom Error Handling in Spring Security
Spring Security is a powerful and highly customizable framework that provides both authentication and authorization. It is one of the most widely used Spring dependencies and represents the de-facto standard for securing a Spring Boot application.
In case of authentication and authorization failures, AuthenticationException
and AccessDeniedException
are thrown respectively. Then, Spring Security takes care of encapsulating them in default error handling responses. If you want to customize them, the two approaches presented above are of no use. This is because @ControllerAdvice
can handle only exceptions thrown by controllers, but AuthenticationException
and AccessDeniedException
are thrown by the Spring Security AbstractSecurityInterceptor
component — which is not a controller. In other words, a @ControllerAdvice
annotated class cannot catch them. Achieving this requires custom logic.
Implementing Custom Error Handling Logic in Spring Security
Let’s take a look at how to implement custom error handling in Spring Security. Luckily, this is not too complex since you can easily provide Spring Security with two components to handle authentication and authorization errors, respectively. What you need to do is to provide the AuthenticationFailureHandler
interface with implementation, as follows:
// src/main/java/com/auth0/hotsauces/security/CustomAuthenticationFailureHandler.java
package com.auth0.hotsauces.security;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {
// Jackson JSON serializer instance
private ObjectMapper objectMapper = new ObjectMapper();
@Override
public void onAuthenticationFailure(
HttpServletRequest request,
HttpServletResponse response,
AuthenticationException exception
) throws IOException, ServletException {
HttpStatus httpStatus = HttpStatus.UNAUTHORIZED; // 401
Map<String, Object> data = new HashMap<>();
data.put(
"timestamp",
new Date()
);
data.put(
"code",
httpStatus.value();
);
data.put(
"status",
httpStatus.name();
);
data.put(
"message",
exception.getMessage()
);
// setting the response HTTP status code
response.setStatus(httpStatus.value());
// serializing the response body in JSON
response
.getOutputStream()
.println(
objectMapper.writeValueAsString(data)
);
}
}
This will be used to handle AuthenticationExceptions
.
Similarly, you can provide the AccessDeniedHandler
interface with implementation to handle AccessDeniedExceptions
.
// src/main/java/com/auth0/hotsauces/security/CustomAccessDeniedHandler.java
package com.auth0.hotsauces.security;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
public class CustomAccessDeniedHandler implements AccessDeniedHandler {
// Jackson JSON serializer instance
private ObjectMapper objectMapper = new ObjectMapper();
@Override
public void handle(
HttpServletRequest request,
HttpServletResponse response,
AccessDeniedException exception
) throws IOException, ServletException {
HttpStatus httpStatus = HttpStatus.FORBIDDEN; // 403
Map<String, Object> data = new HashMap<>();
data.put(
"timestamp",
new Date()
);
data.put(
"code",
httpStatus.value();
);
data.put(
"status",
httpStatus.name();
);
data.put(
"message",
exception.getMessage()
);
// setting the response HTTP status code
response.setStatus(httpStatus.value());
// serializing the response body in JSON
response
.getOutputStream()
.println(
objectMapper.writeValueAsString(data)
);
}
}
Now, you just need to register these two custom implementations as authentication and authorization error handlers. You can do this as below:
// src/main/java/com/auth0/hotsauces/security/SecurityConfig.java
package com.auth0.hotsauces.security;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.oauth2.core.DelegatingOAuth2TokenValidator;
import org.springframework.security.oauth2.core.OAuth2TokenValidator;
import org.springframework.security.oauth2.jwt.*;
import org.springframework.security.oauth2.server.resource.web.BearerTokenAuthenticationFilter;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
// ...
@Override
protected void configure(HttpSecurity http)
throws Exception {
http
.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.formLogin()
.failureHandler(authenticationFailureHandler())
.and()
.exceptionHandling()
.accessDeniedHandler(accessDeniedHandler());
}
@Bean
public AuthenticationFailureHandler authenticationFailureHandler() {
return new CustomAuthenticationFailureHandler();
}
@Bean
public AccessDeniedHandler accessDeniedHandler() {
return new CustomAccessDeniedHandler();
}
}
Et voilà! Custom error handling in Spring Boot has just been achieved thanks to the failureHandler
and accessDeniedHandler
methods, which allows you to register a custom authentication error handler and a custom authorization error handler.
Spring Security Custom Error Handling in Action
Now, let’s see how to implement it in a real-world example. First, read this article on how to protect APIs with Spring Security and Auth0. In the demo application produced in that article, no custom error handling is implemented. So, by making a request to a protected API including a wrong access token, the default Spring Boot error handling logic is applied. Let’s test it out.
If you are a macOS or Linux user, enter this command into the terminal:
curl -i --request GET
--url http://localhost:8080/api/hotsauces/
-H "Content-Type: application/json"
-H "authorization: Bearer wrong-token"
Otherwise, if you are a Windows user, enter this command into PowerShell:
$accessToken = "wrong-token"
$headers = @{
Authorization = "Bearer $accessToken"
}
$response = Invoke-RestMethod "http://localhost:8080/api/hotsauces/" `
-Headers $headers
$response | ConvertTo-Json
Then, the following response will be returned:
Invoke-WebRequest: The remote server returned an error: (401) Unauthorized.
At line:1 char:1
+ Invoke-WebRequest "http://localhost:8080/api/hotsauces/"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebExc
eption
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
As you can see, a 401 error status code is returned, but with no details on what happened.
Now, let’s test the demo application extended with custom error handling logic. You can find it in this GitHub repository. The application is exactly the same as the previous one, except for the error handling logic. In particular, the aforementioned presented logic was implemented.
In this case, by launching the commands above, this message will be returned:
Invoke-RestMethod : {"code":401,"message":"An error occurred while attempting to decode the Jwt: Invalid JWT serialization: Missing dot delimiter(s)","timestamp":1629880611013,"status":"UNAUTHORIZED"}
At line:1 char:1
+ $response = Invoke-RestMethod "http://localhost:8080/api/hotsauces/" ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebExc
eption
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
As you can see, a JSON message representing the custom error handling logic was returned as expected. This contains the status code, the exception message, a timestamp, and the HTTP status code name, as follows:
{
"code": 401,
"message": "An error occurred while attempting to decode the Jwt: Invalid JWT serialization: Missing dot delimiter(s)",
"timestamp": 1629880611013,
"status": "UNAUTHORIZED"
}
Conclusion
In this article, we looked at how to implement custom error handling logic when dealing with REST applications in Spring Boot. This is not as easy a task as it may seem, and it requires knowing a few Spring Boot fundamentals. First, we delved into default error handling in Spring Boot and saw how poor the responses are. Then, we looked at @ControllerAdvice
and learn everything required to implement custom error handling logic. In particular, two different approaches were shown. Both allow you to define custom error handling responses but have specific pros and cons. Finally, we learned how to achieve the same result when dealing with Spring Boot Security errors, which requires specific logic. As shown, achieving custom error handling in Spring Boot is not easy but definitely possible, and explaining when, why, and how to do it was what this article was aimed at.
Thanks for reading! I hope that you found this article helpful. Feel free to reach out to me with any questions, comments, or suggestions.