Skip to content

Commit

Permalink
Support for simplified rendering of Page instances via PagedModel.
Browse files Browse the repository at this point in the history
This commits all necessary infrastructure to produce simplified JSON representation rendering for Page instances to make sure the representations stay stable and do not expose unnecessary implementation details. The support consists of the following elements:

- PagedModel, a stripped down variant of the Spring HATEOAS counterpart to produce an equivalent JSON representation but without the hypermedia elements. This allows a gradual migration to Spring HATEOAS if needed. Page instances can be wrapped into PagedModel once and returned from controller methods to create the new, simplified JSON representation.

- @EnableSpringDataWeb support now contains a pageSerializationMode attribute set to an enum with two possible values: DIRECT, which is the default for backwards compatibility reasons. It serializes Page instances directly but issues a warning that either the newly introduced support here or the Spring HATEOAS support should be used to avoid accidentally breaking representations. The other value, VIA_DTO causes all PageImpl instances to be rendered being wrapped in a PagedModel automatically by registering a Jackson StdConverter applying the wrapping transparently.

Internally, the configuration of @EnableSpringDataWebSupport is translated into a bean definition of a newly introduced type SpringDataWebSettings and wired into the web configuration for consideration within a Jackson module, customizing the serialization for PageImpl.

Fixes GH-3024.
  • Loading branch information
odrotbohm committed Jan 12, 2024
1 parent 4ebe936 commit 5dd7b32
Show file tree
Hide file tree
Showing 7 changed files with 359 additions and 13 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -189,8 +189,92 @@ You have to populate `thing1_page`, `thing2_page`, and so on.

The default `Pageable` passed into the method is equivalent to a `PageRequest.of(0, 20)`, but you can customize it by using the `@PageableDefault` annotation on the `Pageable` parameter.

[[core.web.page]]
=== Creating JSON representations for `Page`

It's common for Spring MVC controllers to try to ultimately render a representation of a Spring Data page to clients.
While one could simply return `Page` instances from handler methods to let Jackson render them as is, we strongly recommend against this as the underlying implementation class `PageImpl` is a domain type.
This means we might want or have to change its API for unrelated reasons, and such changes might alter the resulting JSON representation in a breaking way.

With Spring Data 3.1, we started hinting at the problem by issuing a warning log describing the problem.
We still ultimately recommend to leverage xref:repositories/core-extensions.adoc#core.web.pageables[the integration with Spring HATEOAS] for a fully stable and hypermedia-enabled way of rendering pages that easily allow clients to navigate them.
But as of version 3.3 Spring Data ships a page rendering mechanism that is convenient to use but does not require the inclusion of Spring HATEOAS.

[[core.web.page.paged-model]]
==== Using Spring Data' `PagedModel`

At its core, the support consists of a simplified version of Spring HATEOAS' `PagedModel` (the Spring Data one located in the `org.springframework.data.web` package).
It can be used to wrap `Page` instances and result in a simplified representation that reflects the structure established by Spring HATEOAS but omits the navigation links.

[source, java]
----
import org.springframework.data.web.PagedModel;
@Controller
class MyController {
private final MyRepository repository;
// Constructor ommitted
@GetMapping("/page")
PagedModel<?> page(Pageable pageable) {
return new PagedModel<>(repository.findAll(pageable)); // <1>
}
}
----
<1> Wraps the `Page` instance into a `PagedModel`.

This will result in a JSON structure looking like this:

[source, javascript]
----
{
"content" : [
… // Page content rendered here
],
"page" : {
"size" : 20,
"totalElements" : 30,
"totalPages" : 2,
"number" : 0
}
}
----

Note how the document contains a `page` field exposing the essential pagination metadata.

[[core.web.page.config]]
==== Globally enabling simplified `Page` rendering

If you don't want to change all your existing controllers to add the mapping step to return `PagedModel` instead of `Page` you can enable the automatic translation of `PageImpl` instances into `PagedModel` by tweaking `@EnableSpringDataWebSupport` as follows:

[source, java]
----
@EnableSpringDataWebSupport(pageSerializationMode = VIA_DTO)
class MyConfiguration { }
----

This will allow your controller to still return `Page` instances and they will automatically be rendered into the simplified representation:

[source, java]
----
@Controller
class MyController {
private final MyRepository repository;
// Constructor ommitted
@GetMapping("/page")
Page<?> page(Pageable pageable) {
return repository.findAll(pageable);
}
}
----

[[core.web.pageables]]
=== Hypermedia Support for `Page` and `Slice`
==== Hypermedia Support for `Page` and `Slice`

Spring HATEOAS ships with a representation model class (`PagedModel`/`SlicedModel`) that allows enriching the content of a `Page` or `Slice` instance with the necessary `Page`/`Slice` metadata as well as links to let the clients easily navigate the pages.
The conversion of a `Page` to a `PagedModel` is done by an implementation of the Spring HATEOAS `RepresentationModelAssembler` interface, called the `PagedResourcesAssembler`.
Expand Down Expand Up @@ -237,7 +321,7 @@ You can now trigger a request (`GET http://localhost:8080/people`) and see outpu
"content" : [
… // 20 Person instances rendered here
],
"pageMetadata" : {
"page" : {
"size" : 20,
"totalElements" : 30,
"totalPages" : 2,
Expand Down
94 changes: 94 additions & 0 deletions src/main/java/org/springframework/data/web/PagedModel.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
/*
* Copyright 2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.web;

import java.util.List;
import java.util.Objects;

import org.springframework.data.domain.Page;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;

import com.fasterxml.jackson.annotation.JsonProperty;

/**
* DTO to build stable JSON representations of a Spring Data {@link Page}. It can either be selectively used in
* controller methods by calling {@code new PagedModel<>(page)} or generally activated as representation model for
* {@link org.springframework.data.domain.PageImpl} instances by setting
* {@link org.springframework.data.web.config.EnableSpringDataWebSupport}'s {@code pageSerializationMode} to
* {@link org.springframework.data.web.config.EnableSpringDataWebSupport.PageSerializationMode#VIA_DTO}.
*
* @author Oliver Drotbohm
* @author Greg Turnquist
* @since 3.3
*/
public class PagedModel<T> {

private final Page<T> page;

/**
* Creates a new {@link PagedModel} for the given {@link Page}.
*
* @param page must not be {@literal null}.
*/
public PagedModel(Page<T> page) {

Assert.notNull(page, "Page must not be null");

this.page = page;
}

@JsonProperty
public List<T> getContent() {
return page.getContent();
}

@Nullable
@JsonProperty("page")
public PageMetadata getMetadata() {
return new PageMetadata(page.getSize(), page.getNumber(), page.getTotalElements(),
page.getTotalPages());
}

@Override
public boolean equals(@Nullable Object obj) {

if (this == obj) {
return true;
}

if (!(obj instanceof PagedModel<?> that)) {
return false;
}

return Objects.equals(this.page, that.page);
}

@Override
public int hashCode() {
return Objects.hash(page);
}

public static record PageMetadata(long size, long number, long totalElements, long totalPages) {

public PageMetadata {
Assert.isTrue(size > -1, "Size must not be negative!");
Assert.isTrue(number > -1, "Number must not be negative!");
Assert.isTrue(totalElements > -1, "Total elements must not be negative!");
Assert.isTrue(totalPages > -1, "Total pages must not be negative!");
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,16 +22,21 @@
import java.lang.annotation.Target;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanNameGenerator;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.context.annotation.ImportSelector;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.SpringFactoriesLoader;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.data.querydsl.QuerydslUtils;
import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
import org.springframework.util.ClassUtils;

/**
Expand Down Expand Up @@ -68,10 +73,42 @@
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.ANNOTATION_TYPE })
@Inherited
@Import({ EnableSpringDataWebSupport.SpringDataWebConfigurationImportSelector.class,
EnableSpringDataWebSupport.QuerydslActivator.class })
@Import({
EnableSpringDataWebSupport.SpringDataWebConfigurationImportSelector.class,
EnableSpringDataWebSupport.QuerydslActivator.class,
EnableSpringDataWebSupport.SpringDataWebSettingsRegistar.class
})
public @interface EnableSpringDataWebSupport {

/**
* Configures how to render {@link org.springframework.data.domain.PageImpl} instances. Defaults to
* {@link PageSerializationMode#DIRECT} for backward compatibility reasons. Prefer explicitly setting this to
* {@link PageSerializationMode#VIA_DTO}, or manually convert {@link org.springframework.data.domain.PageImpl}
* instances before handing them out of a controller method, either by manually calling {@code new PagedModel<>(page)}
* or using Spring HATEOAS {@link org.springframework.hateoas.PagedModel} abstraction.
*
* @return will never be {@literal null}.
* @since 3.3
*/
PageSerializationMode pageSerializationMode() default PageSerializationMode.DIRECT;

enum PageSerializationMode {

/**
* {@link org.springframework.data.domain.PageImpl} instances will be rendered as is (discouraged, as there's no
* guarantee on the stability of the serialization result as we might need to change the type's API for unrelated
* reasons).
*/
DIRECT,

/**
* Causes {@link org.springframework.data.domain.PageImpl} instances to be wrapped into
* {@link org.springframework.data.web.PagedModel} instances before rendering them as JSON to make sure the
* representation stays stable even if {@link org.springframework.data.domain.PageImpl} is changed.
*/
VIA_DTO;
}

/**
* Import selector to import the appropriate configuration class depending on whether Spring HATEOAS is present on the
* classpath. We need to register the HATEOAS specific class first as apparently only the first class implementing
Expand Down Expand Up @@ -127,4 +164,39 @@ public String[] selectImports(AnnotationMetadata importingClassMetadata) {
: new String[0];
}
}

/**
* Registers a bean definition for {@link SpringDataWebSettings} carrying the configuration values of
* {@link EnableSpringDataWebSupport}.
*
* @author Oliver Drotbohm
* @soundtrack Norah Jones - Chasing Pirates
* @since 3.3
*/
static class SpringDataWebSettingsRegistar implements ImportBeanDefinitionRegistrar {

/*
* (non-Javadoc)
* @see org.springframework.context.annotation.ImportBeanDefinitionRegistrar#registerBeanDefinitions(org.springframework.core.type.AnnotationMetadata, org.springframework.beans.factory.support.BeanDefinitionRegistry, org.springframework.beans.factory.support.BeanNameGenerator)
*/
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry,
BeanNameGenerator importBeanNameGenerator) {

Map<String, Object> attributes = importingClassMetadata
.getAnnotationAttributes(EnableSpringDataWebSupport.class.getName());

if (attributes == null) {
return;
}

AbstractBeanDefinition definition = BeanDefinitionBuilder.rootBeanDefinition(SpringDataWebSettings.class)
.addConstructorArgValue(attributes.get("pageSerializationMode"))
.getBeanDefinition();

String beanName = importBeanNameGenerator.generateBeanName(definition, registry);

registry.registerBeanDefinition(beanName, definition);
}
}
}
Loading

0 comments on commit 5dd7b32

Please sign in to comment.