Spring MVC 3:将Spring-Data Page作为JSON返回 [英] Spring MVC 3: return a Spring-Data Page as JSON

查看:173
本文介绍了Spring MVC 3:将Spring-Data Page作为JSON返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用Spring-Data制成的数据访问层.我现在正在其上创建一个Web应用程序.这个控制器方法应返回 Spring-Data Page 格式为JSON.

I have a data access layer made with Spring-Data. I'm now creating a web application on top of it. This one controller method should return a Spring-Data Page formatted as JSON.

此类页面"是具有其他分页信息(例如记录总数等)的列表.

Such a Page is a List with additional Paging info like total amount of records and so forth.

有可能吗?如果可以,怎么办?

Is that possible and if yes how?

与之直接相关的是,我可以定义属性名称的映射吗?例如.这意味着我需要定义如何在JSON中(与页面中不同)命名页面信息属性.这有可能吗?

And directly related to that can I define the mapping of property names? Eg. meaning I would need define how the paging info properties are named in JSON (differently than in page). Is this possible and how?

推荐答案

Spring HATEOAS和Spring Data Commons中将支持这种情况. Spring HATEOAS附带了一个PageMetadata对象,该对象本质上包含与Page相同的数据,但执行方式较少,因此可以更轻松地将其编组和取消编组.

There's support for a scenario like this upcoming in Spring HATEOAS and Spring Data Commons. Spring HATEOAS comes with a PageMetadata object that essentially contains the same data as a Page but in a less enforcing manner, so that it can be more easily marshaled and unmarshaled.

我们将其与Spring HATEOAS和Spring Data commons结合实现的原因的另一方面是,仅封送页面,其内容和元数据只是毫无意义,而且还希望生成指向可能存在的下一个或上一个页面的链接,这样客户端就不必构造URI来遍历这些页面本身.

Another aspect of the reason we implement this in combination with Spring HATEOAS and Spring Data commons is that there's little value in simply marshaling the page, it's content and the metadata but also want to generate the links to maybe existing next or previous pages, so that the client doesn't have to construct URIs to traverse these pages itself.

假定域类Person:

class Person {

  Long id;
  String firstname, lastname;
}

以及相应的存储库:

interface PersonRepository extends PagingAndSortingRepository<Person, Long> { }

您现在可以按以下方式公开Spring MVC控制器:

You can now expose a Spring MVC controller as follows:

@Controller
class PersonController {

  @Autowired PersonRepository repository;

  @RequestMapping(value = "/persons", method = RequestMethod.GET)
  HttpEntity<PagedResources<Person>> persons(Pageable pageable, 
    PagedResourcesAssembler assembler) {

    Page<Person> persons = repository.findAll(pageable);
    return new ResponseEntity<>(assembler.toResources(persons), HttpStatus.OK);
  }
}

这里可能有很多解释.让我们逐步进行:

There's probably quite a bit to explain here. Let's take it step by step:

  1. 我们有一个Spring MVC控制器,用于将存储库连接到其中.这需要设置Spring Data(通过@Enable(Jpa|Mongo|Neo4j|Gemfire)Repositories或XML等效项).控制器方法已映射到/persons,这意味着它将接受对该方法的所有GET请求.
  2. 从该方法返回的核心类型是
  1. We have a Spring MVC controller getting the repository wired into it. This requires Spring Data being set up (either through @Enable(Jpa|Mongo|Neo4j|Gemfire)Repositories or the XML equivalents). The controller method is mapped to /persons, which means it will accept all GET requests to that method.
  2. The core type returned from the method is a PagedResources - a type from Spring HATEOAS that represents some content enriched with Links plus a PageMetadata.
  3. When the method is invoked, Spring MVC will have to create instances for Pageable and PagedResourcesAssembler. To get this working you need to enable the Spring Data web support either through the @EnableSpringDataWebSupport annotation about to be introduced in the upcoming milestone of Spring Data Commons or via standalone bean definitions (documented here).

Pageable将使用请求中的信息填充.默认配置会将?page=0&size=10变为Pageable,以页面大小10来请求第一页.

The Pageable will be populated with information from the request. The default configuration will turn ?page=0&size=10 into a Pageable requesting the first page by a page size of 10.

通过PageableResourcesAssembler,您可以轻松地将Page转换为PagedResources实例.它将不仅将页面元数据添加到响应中,还将根据您访问的页面以及Pageable分辨率的配置方式将适当的链接添加到表示形式.

The PageableResourcesAssembler allows you to easily turn a Page into a PagedResources instances. It will not only add the page metadata to the response but also add the appropriate links to the representation based on what page you access and how your Pageable resolution is configured.

为JPA启用此功能的示例JavaConfig配置如下所示:

A sample JavaConfig configuration to enable this for JPA would look like this:

@Configuration
@EnableWebMvc
@EnableSpringDataWebSupport
@EnableJpaRepositories
class ApplicationConfig {

  // declare infrastructure components like EntityManagerFactory etc. here
}

示例请求和响应

假设数据库中有30个Persons.现在,您可以触发请求GET http://localhost:8080/persons,您将看到类似以下内容的内容:

A sample request and response

Assume we have 30 Persons in the database. You can now trigger a request GET http://localhost:8080/persons and you'll see something similar to this:

{ "links" : [
    { "rel" : "next", "href" : "http://localhost:8080/persons?page=1&size=20 }
  ],
  "content" : [
    … // 20 Person instances rendered here
  ],
  "pageMetadata" : {
    "size" : 20,
    "totalElements" : 30,
    "totalPages" : 2,
    "number" : 0
  }
}

请注意,汇编器生成了正确的URI,并且还采用了当前的默认配置以将参数解析为Pageable,以应对即将到来的请求.这意味着,如果您更改该配置,则链接将自动遵循更改.默认情况下,汇编器指向调用它的控制器方法,但可以通过提交自定义Link进行自定义,以用作建立PagedResourcesAssembler.toResource(…)方法重载的分页链接的基础.

Note that the assembler produced the correct URI and also picks up the default configuration present to resolve the parameters into a Pageable for an upcoming request. This means, if you change that configuration, the links will automatically adhere to the change. By default the assembler points to the controller method it was invoked in but that can be customized by handing in a custom Link to be used as base to build the pagination links to overloads of the PagedResourcesAssembler.toResource(…) method.

PagedResourcesAssembler位将在Spring Data Babbage即将发布的里程碑版本中提供发布火车.当前快照中已提供该功能.您可以在我的Spring RESTBucks 示例应用程序中看到一个有效的示例.只需克隆它,运行mvn jetty:run并卷曲http://localhost:8080/pages.

The PagedResourcesAssembler bits will be available in the upcoming milestone release of the Spring Data Babbage release train. It's already available in the current snapshots. You can see a working example of this in my Spring RESTBucks sample application. Simply clone it, run mvn jetty:run and curl http://localhost:8080/pages.

这篇关于Spring MVC 3:将Spring-Data Page作为JSON返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆