首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Spring中生成一致的资源链接

在Spring中生成一致的资源链接
EN

Stack Overflow用户
提问于 2014-09-19 12:16:51
回答 3查看 1.1K关注 0票数 2

在使用下面这行代码生成链接时:

代码语言:javascript
复制
indexResource.add(linkTo(IndexController.class).withSelfRel());

这个JSON是这样产生的:

代码语言:javascript
复制
{
  "links" : [ {
    "rel" : "self",
    "href" : "http://localhost:8080"
  } ]
}

但是,Spring Data Rest生成的资源链接会生成以下JSON:

代码语言:javascript
复制
{
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/persons{?page,size,sort}",
      "templated" : true
    }
  }
}

特别是,我想模仿一下Spring Data Rest生成的那个。我该怎么做呢?

我使用Spring Boot,配置如下:

代码语言:javascript
复制
@Configuration
@Import(RepositoryRestMvcConfiguration.class)
@EnableAutoConfiguration
@EnableJpaRepositories(repositoryFactoryBeanClass = EnversRevisionRepositoryFactoryBean.class)
@EnableHypermediaSupport(type = EnableHypermediaSupport.HypermediaType.HAL)
@ComponentScan
public class Application { ... }

保留或删除@EnableHypermediaSupport(type = EnableHypermediaSupport.HypermediaType.HAL)似乎不会改变任何事情。

我还有以下gradle依赖项:

代码语言:javascript
复制
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"
EN

回答 3

Stack Overflow用户

发布于 2014-09-19 19:19:39

Spring Data Rest使用HAL格式。对于较新版本的Spring HATEOAS,它应该是默认的。您可以使用配置类上的注释来激活它:

代码语言:javascript
复制
@EnableHypermediaSupport(type= {HypermediaType.HAL})

更新

我在Spring Boot上也遇到了类似的问题。我不得不将以下内容添加到我的pom.xml

代码语言:javascript
复制
<dependency>
  <groupId>org.springframework.plugin</groupId>
  <artifactId>spring-plugin-core</artifactId>
  <version>1.1.0.RELEASE</version>
</dependency>
票数 1
EN

Stack Overflow用户

发布于 2015-07-02 23:55:19

为了生成HAL格式的JSON,您的HTTP请求必须接受application/hal+json (即,accept标头是application/hal+json)。

应用程序的默认内容类型也可以是application/json。您可以通过以下配置类将默认内容类型更改为application/hal+json:

代码语言:javascript
复制
public class WebConfig extends WebMvcConfigurerAdapter {
    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer c) {
        c.defaultContentType(MediaTypes.HAL_JSON);
    }
}
票数 1
EN

Stack Overflow用户

发布于 2014-09-19 12:51:22

我建议创建两个类,如Link和Self.Link has Self。Self有href和模板。创建一个将链接形成为Java对象的类。然后使用像GSON这样的Java to Json库来获得与上面类似的输出

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25926286

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档