标签: spring-hateoas

如何从 HAL 响应获取我的资源数据?

我正在使用 Spring Boot 2 构建一个 API,而 Angular 6 客户端必须处理如下响应:

{
  "_embedded" : {
    "userResourceList" : [ {
      "firstname" : "Stephane",
      "lastname" : "Toto",
      "email" : "toto@yahoo.se",
      "confirmedEmail" : false,
      "password" : "bWl0dGlwcm92ZW5jZUB5YWhvby5zZTptaWduZXRjNWRlMDJkZS1iMzIwLTQ4Y2YtOGYyMS0wMmFkZTQ=",
      "userRoles" : [ {
        "role" : "ROLE_ADMIN",
        "id" : 1
      } ],
      "_links" : {
        "self" : {
          "href" : "http://localhost:8080/api/users/1"
        },
        "roles" : {
          "href" : "http://localhost:8080/api/users/1/roles"
        }
      },
      "id" : 1
    } ]
  },
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/api/users"
    }
  },
  "page" …
Run Code Online (Sandbox Code Playgroud)

spring-hateoas spring-boot angular

4
推荐指数
1
解决办法
2400
查看次数

Spring HATEOAS 中的 Resource 是否取代了 DTO?

我正在 Spring 中构建 REST API。所以直到现在我只有阅读服务(GET)。为此,我使用 Spring HATEOAS 添加引用子元素的链接。

现在我想添加一些写作 REST-Services。通常在 REST 服务中使用 DTO,然后将它们映射到域模型。

所以我的问题是:我们可以像下面的例子一样使用 Spring HATEOAS 的资源而不使用 DTO 吗?或者资源是否用于其他用途而我仍然需要 DTO?

@PostMapping
public ResponseEntity<String> saveProduct(@RequestBody ProductResource product) {
  ...
}
Run Code Online (Sandbox Code Playgroud)

java spring spring-hateoas

4
推荐指数
1
解决办法
1746
查看次数

将Spring HATEOAS链接转换为对象的正确方法

我有一个非常简单的控制器,可以发出HTTP请求并以HATEOAS格式接收一些资源。

package com.provider.spring.controller;

import java.util.List;

import org.springframework.hateoas.Link;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.client.RestTemplate;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.provider.employee.EmployeeDTO;
import com.provider.http.HttpComponentsClientHttpRequestFactoryBasicAuth;
import com.provider.spring.rest.Resource;

@Controller
public class EmployeeController {

    private static final String REL_SELF = "self";
    private static final String REL_SEARCH = "search";
    private static final String REL_EMPLOYEE = "employee";
    private static final String RESOURCE_URI = "http://localhost:8080/employees";

    private RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactoryBasicAuth("user", "password"));
    private List<EmployeeDTO> employees;


    @RequestMapping("/employees")
    public String getAllEmployees() {

        String result = null;
        try {
            String resultBody = restTemplate.getForObject(RESOURCE_URI, …
Run Code Online (Sandbox Code Playgroud)

spring hateoas spring-hateoas

3
推荐指数
1
解决办法
3034
查看次数

使用Traverson的Spring-Hateoas客户

我想使用Traverson的Spring-Hateoas提供的休息服务,但是遇到以下问题,我在网络上找不到任何东西。我正在使用Spring-Boot 1.1.10.RELEASE

我的客户呼叫如下所示:

... 

final Traverson traverson = new Traverson(new URI("http://localhost:8080/bbsng-app-rest"), MediaTypes.HAL_JSON);

...
Run Code Online (Sandbox Code Playgroud)

我得到以下问题:

java.lang.NoClassDefFoundError: Could not initialize class org.springframework.hateoas.client.Traverson
at at.compax.bbsng.client.mvc.client.service.BerufServiceImpl.findeAlleBerufe(BerufServiceImpl.java:41)
at at.compax.bbsng.client.mvc.rest.controller.BerufController$1.call(BerufController.java:25)
at at.compax.bbsng.client.mvc.rest.controller.BerufController$1.call(BerufController.java:1)
at org.springframework.web.context.request.async.WebAsyncManager$4.run(WebAsyncManager.java:316)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.lang.Thread.run(Thread.java:745)
Run Code Online (Sandbox Code Playgroud)

=====

相关配置:

POM:

...

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.hateoas</groupId>
        <artifactId>spring-hateoas</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.plugin</groupId>
        <artifactId>spring-plugin-core</artifactId>
        <version>1.1.0.RELEASE</version>
    </dependency>

...
Run Code Online (Sandbox Code Playgroud)

应用类别:

@Configuration
@EnableHypermediaSupport(type = HAL)
@EnableAutoConfiguration
public class ApplicationClientMvc {

    public static void main(final String[] args) {
        SpringApplication.run(ApplicationClientMvc.class, …
Run Code Online (Sandbox Code Playgroud)

client resttemplate spring-hateoas hal-json

3
推荐指数
1
解决办法
2213
查看次数

通过traverson到java对象查找Spring引导数据

我的URI是 http:// localhost:8080/context/my-objects/search/findByCode?code = foo

JSON响应:

{
  "_embedded" : {
    "my-objects" : [ {
      "code" : "foo",
      "description" : "foo description",
      "_links" : {
        "self" : {
          "href" : "http://localhost:8080/context/my-objects/34"
        }
      }
    } ]
  }
}
Run Code Online (Sandbox Code Playgroud)

如何使用Traverson或RestTemplate获取java MyObject?

import org.springframework.hateoas.ResourceSupport;

public class MyObject extends ResourceSupport{

    private String code;

    private String description;

    public String getDescription() {
        return description;
    }

    public void setDescription(final String description) {
        this.description = description;
    }

    public String getCode() {
        return code;
    }

    public void setCode(final String code) …
Run Code Online (Sandbox Code Playgroud)

rest findby resttemplate spring-hateoas spring-boot

3
推荐指数
1
解决办法
2938
查看次数

在Spring Data REST + HATEOAS中删除REST上的关联

我想知道如何通过REST调用删除多对多关联.我能够创建记录并关联它们,但不了解如何删除.

我有一个Spring Boot项目,我使用REST和HATEOAS来传递服务和控制器并直接公开我的存储库.

我有一个用户模型/域类

@Entity
@Table(name = "usr")
public class User implements Serializable {

private static final long serialVersionUID = 1L;

@Version
private long version = 0;

@Id
@GeneratedValue(generator="optimized-sequence")
private Long id;

@Column(nullable = false, unique = true, length = 500)
@Size(max = 500)
private String userName;

@Column(nullable = false, length = 500)
@Size(max = 500)
private String firstName;

@Column(nullable = false, length = 500)
@Size(max = 500)
private String lastName;

@ManyToMany(    fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinTable( name="user_role", …
Run Code Online (Sandbox Code Playgroud)

rest spring spring-data-rest spring-hateoas

3
推荐指数
2
解决办法
3683
查看次数

使用MockServletContext进行单元测试

我已经使用Gradle 设置了spring boot应用程序.现在我明白@EnableAutoConnfiguration根据类路径中的依赖关系配置应用程序.我很高兴避免所有的管道,但事情开始发生,我希望不会.

这是我的依赖项:

dependencies {
        compile('org.springframework.boot:spring-boot-starter-web:1.2.3.RELEASE')
        compile 'org.springframework.hateoas:spring-hateoas:0.17.0.RELEASE'
        compile 'org.springframework.plugin:spring-plugin-core:1.2.0.RELEASE'
        compile 'org.springframework.boot:spring-boot-starter-data-jpa'

        compile 'com.google.guava:guava:18.0'
        compile 'com.fasterxml.jackson.datatype:jackson-datatype-jsr310'
        compile 'commons-beanutils:commons-beanutils:1.9.2'
        runtime 'org.hsqldb:hsqldb:2.3.2'

        testCompile 'org.springframework.boot:spring-boot-starter-test'
        testCompile 'com.jayway.jsonpath:json-path:2.0.0'
    }
Run Code Online (Sandbox Code Playgroud)

我的应用类:

@ComponentScan("org.home.project")
@SpringBootApplication
//@EnableHypermediaSupport(type = EnableHypermediaSupport.HypermediaType.HAL)
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
Run Code Online (Sandbox Code Playgroud)

UserController的一个片段:

@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public HttpEntity<ResourceSupport> create(@Valid @RequestBody UserCreateRequest ucr, BindingResult bindingResult) {
    if (bindingResult.hasErrors()) throw new InvalidRequestException("Bad Request", bindingResult);

    Long userId = userService.create(ucr);

    ResourceSupport resource = …
Run Code Online (Sandbox Code Playgroud)

java spring spring-hateoas spring-boot

3
推荐指数
1
解决办法
5288
查看次数

如何在Spring Hateos中更改embbed集合的属性名称

我正在使用Spring hateoas来生成HAL接口.我的代码看起来像这样:

@RequestMapping(method = RequestMethod.GET)
public Resources<Resource<Type>> all() {
    List<Resource<Type>> sdf = typeRepository.all().stream().map(type -> {
        return new Resource<Type>(type, ControllerLinkBuilder.linkTo(this.getClass()).slash(type.getId()).withSelfRel());
    }).collect(Collectors.toList());

    Resources<Resource<Type>> resourcesType = new Resources<>(sdf);
    resourcesType.add(ControllerLinkBuilder.linkTo(ControllerLinkBuilder.methodOn(this.getClass()).all()).withSelfRel());
    return resourcesType;
}
Run Code Online (Sandbox Code Playgroud)

生成的json看起来像这样:

{
  "_links": {
    "self": {
      "href": "http://localhost:8080/type"
    }
  },
  "_embedded": {
    "typeEntityList": [
      {
        "id": "4f7fa2da-20e2-4b42-9b45-2d1749825785",
        "version": 0,
        "name": "name1",
        "_links": {
          "self": {
            "href": "http://localhost:8080/type/4f7fa2da-20e2-4b42-9b45-2d1749825785"
          }
        }
      }
    ]
  }
}
Run Code Online (Sandbox Code Playgroud)

我想更改"typeEntityList"的名称,但我无法找到它的来源或来源.谁知道怎么样?

spring spring-hateoas

3
推荐指数
1
解决办法
1912
查看次数

Spring HATEOAS ControllerLinkBuilder方法显着增加响应时间

设置:所以我有一个问题的REST API用Java编写的,使用spring-bootspring-hates添加链接到资源(超媒体驱动的RESTful Web服务).我拥有的一切都是标准的,没有进行任何额外的设置或更改

问题

  1. 案例:没有关于资源的链接 - Chrome TTFB avg.(10次运行)400个项目,1000个项目
  2. 案例:资源上的1个自我参考链接 - Chrome TTFB avg.(10次运行)1000个项目1500毫秒

我正在使用这个官方指南

这个问题

为什么只添加1个链接到我的资源,为处理请求增加了1秒.每个资源需要大约5-7个链接,每个资源都有其他嵌入的链接?

为9000总项与每个项目只1链路(包括嵌套的),我必须等待30秒的响应和无链接〜400毫秒.

PS附加代码无关紧要,因为我只是在教程中添加了一个能够显着影响性能的代码.

编辑1

正如建议我从我的TextItem构造函数中添加示例代码

add(linkTo(methodOn(TestController.class).getTestItems()).withRel("testLink"));
Run Code Online (Sandbox Code Playgroud)

编辑2

所以@Mathias Dpunkt提出的以下示例非常完美

private Method method = ReflectionUtils.findMethod(TestController.class, "getOne", Integer.class);

@Override
public Resource<Item> process(Resource<Item> resource) {
  resource.add(linkTo(method, resource.getContent().getId()).withSelfRel());
  return resource;
}
Run Code Online (Sandbox Code Playgroud)

新问题

控制器:

@RestController
@RequestMapping("items")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class TestController {

    private final ItemResourceProcessor resourceProcessor;

    @RequestMapping(method = GET)
    public ResponseEntity<List<Resource<Item>>> getAll() {
        List<Resource<Item>> items = …
Run Code Online (Sandbox Code Playgroud)

java spring spring-hateoas

3
推荐指数
1
解决办法
5926
查看次数

扩展Spring Data Rest索引资源链接

我将所有api端点映射到基本URL下/api/.现在,我希望通过HATEOAS使用spring-data-rest来公开所有可用的端点,以便客户端应用程序可以处理这些信息.默认情况下,这似乎开箱即用,因为GET /api/返回所有找到的Spring存储库及其各自的URL如下:

{
  "_links" : {
    "news" : {
      "href" : "http://localhost:8080/api/news{?page,size,sort,projection}",
      "templated" : true
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

但是,我想添加一些自定义链接到其他资源.我试过这个:

@RequestMapping("/api")
public class AppController {

  @RequestMapping("/")
  public ResponseEntity<ResourceSupport> getEndpoints () {
      ResourceSupport resource = new ResourceSupport();

      resource.add(linkTo(UserController.class).withRel("users"));

      return new ResponseEntity<>(resource, HttpStatus.OK);
  }
}
Run Code Online (Sandbox Code Playgroud)

但这实际上会覆盖一切.所以我的问题是如何使用一些自定义链接扩展基本资源的spring-data-rest的标准输出?

spring spring-data-rest spring-hateoas

3
推荐指数
1
解决办法
302
查看次数