在使用下面这行代码生成链接时:
indexResource.add(linkTo(IndexController.class).withSelfRel());这个JSON是这样产生的:
{
"links" : [ {
"rel" : "self",
"href" : "http://localhost:8080"
} ]
}但是,Spring Data Rest生成的资源链接会生成以下JSON:
{
"_links" : {
"self" : {
"href" : "http://localhost:8080/persons{?page,size,sort}",
"templated" : true
}
}
}特别是,我想模仿一下Spring Data Rest生成的那个。我该怎么做呢?
我使用Spring Boot,配置如下:
@Configuration
@Import(RepositoryRestMvcConfiguration.class)
@EnableAutoConfiguration
@EnableJpaRepositories(repositoryFactoryBeanClass = EnversRevisionRepositoryFactoryBean.class)
@EnableHypermediaSupport(type = EnableHypermediaSupport.HypermediaType.HAL)
@ComponentScan
public class Application { ... }保留或删除@EnableHypermediaSupport(type = EnableHypermediaSupport.HypermediaType.HAL)似乎不会改变任何事情。
我还有以下gradle依赖项:
compile "org.springframework.boot:spring-boot-starter-data-rest"
compile "org.springframework.boot:spring-boot-starter-data-jpa"
compile "org.springframework.boot:spring-boot-starter-actuator"
compile "org.springframework.boot:spring-boot-starter-jetty"
compile "org.springframework.data:spring-data-envers:0.2.0.RELEASE"
compile "org.hibernate:hibernate-envers:4.3.6.Final"
runtime "mysql:mysql-connector-java:5.1.32"
testCompile "junit:junit"发布于 2014-09-19 19:19:39
Spring Data Rest使用HAL格式。对于较新版本的Spring HATEOAS,它应该是默认的。您可以使用配置类上的注释来激活它:
@EnableHypermediaSupport(type= {HypermediaType.HAL})更新
我在Spring Boot上也遇到了类似的问题。我不得不将以下内容添加到我的pom.xml中
<dependency>
<groupId>org.springframework.plugin</groupId>
<artifactId>spring-plugin-core</artifactId>
<version>1.1.0.RELEASE</version>
</dependency>发布于 2015-07-02 23:55:19
为了生成HAL格式的JSON,您的HTTP请求必须接受application/hal+json (即,accept标头是application/hal+json)。
应用程序的默认内容类型也可以是application/json。您可以通过以下配置类将默认内容类型更改为application/hal+json:
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer c) {
c.defaultContentType(MediaTypes.HAL_JSON);
}
}发布于 2014-09-19 12:51:22
我建议创建两个类,如Link和Self.Link has Self。Self有href和模板。创建一个将链接形成为Java对象的类。然后使用像GSON这样的Java to Json库来获得与上面类似的输出
https://stackoverflow.com/questions/25926286
复制相似问题