首页 > 解决方案 > 如何使用 Spring EntityLinks 创建指向 /profiles/{user-id}/job URI 的 REST 链接?

问题描述

我有一个控制器方法,它负责返回一些数据以及客户端应用程序的有用链接。

@GetMapping(value = "/{uniqueId}")
@ResponseStatus(value = HttpStatus.OK)
public HttpEntity<UserProfileMinimalDto> getUserMinimal(@PathVariable String uniqueId) {
    UserProfileMinimalDto userDto = userProfileService.getProfileMinimal(uniqueId);
    userDto.add(
            entityLinks.linkToSingleResource(UserProfileController.class, uniqueId),
            linkTo(methodOn(UserJobController.class).getUserJobs(uniqueId)).withRel(REL_EXPERIENCES)
    );

另一个控制器

@RestController
@RequestMapping(PROFILES)
@ExposesResourceFor(UserJob.class)
public class UserJobController {

    @PostMapping(value = "/{uniqueId}"+"/job" )
    @ResponseStatus(value = HttpStatus.CREATED)
    public HttpEntity<UserJob> getUserJobs(@PathVariable String uniqueId) {
        System.out.println("user jobs");
        return new ResponseEntity<UserJob>(new UserJob(), HttpStatus.OK);
    }

}

这将链接返回给我:

"_links": {
    "self": {
        "href": "http://localhost:8085/api/v1/profiles/theCoder"
    },
    "experiences": {
        "href": "http://localhost:8085/api/v1/profiles/theCoder/job"
    }
}

但我想使用EntityLinks. 正如人们所看到的,我已将UserJobController其作为一种UserJob资源公开,以便我可以使用它EntityLinks 所以我尝试了以下方法,但它们都没有奏效。

entityLinks.linkFor(UserJob.class, uniqueId).withRel(REL_EXPERIENCES),
entityLinks.linkFor(UserJob.class, uniqueId, "/job").withRel(REL_EXPERIENCES)

但两人都回来了

"experiences": {
            "href": "http://localhost:8085/api/v1/profiles"
        }

我在这里做错了什么?或者EntityLinks不打算以这种方式使用?

标签: spring-bootspring-data-rest

解决方案


I found the right API to use. Here is one possible solution.

entityLinks.linkFor(UserJob.class, uniqueId).slash("/job").withRel(REL_EXPERIENCES)

Note: I don't want to use controller methods.


推荐阅读