java - spring-hateoas,如何使用 onMethod 构建超媒体链接时设置占位符值

标签 java rest spring-mvc spring-hateoas

我正在做一个安静的应用程序。我一直在尝试为具有路径变量teacherId的方法构建超媒体链接,如下面的代码所示。我使用 methodOngetAllToturialByTeacher 方法构建链接,例如 http://localhost:8080/springexample/teachers/2/toturials

@RestController
@RequestMapping( value = "/teachers", produces = { MediaType.APPLICATION_JSON_VALUE } )
public class ToturialController {

    ......  

    @RequestMapping( value = "/{teacherId}/toturials",method = RequestMethod.GET )
    public ResponseEntity<Resources<Resource<Toturial>>> getAllToturialByTeacher(int teacherId){

        ......

        resource.add(linkTo(ToturialController.class)
                .slash(linkTo(methodOn(ToturialController.class).getAllToturialByTeacher(teacherId)))               
                .withRel("subjectsByTeacher"));
        ....
        return new ResponseEntity<Resources<Resource<Toturial>>>(resource, HttpStatus.OK);
    }
}

我遇到了异常错误

java.lang.IllegalArgumentException: Map has no value for 'teacherId'
    at org.springframework.web.util.UriComponents$MapTemplateVariables.getValue(UriComponents.java:306)
    at org.springframework.web.util.UriComponents.expandUriComponent(UriComponents.java:230)
    at org.springframework.web.util.HierarchicalUriComponents$FullPathComponent.expand(HierarchicalUriComponents.java:685)
    at org.springframework.web.util.HierarchicalUriComponents.expandInternal(HierarchicalUriComponents.java:328)
    at org.springframework.web.util.HierarchicalUriComponents.expandInternal(HierarchicalUriComponents.java:47)
    at org.springframework.web.util.UriComponents.expand(UriComponents.java:152)
    at org.springframework.web.util.UriComponentsBuilder.buildAndExpand(UriComponentsBuilder.java:398)
    at org.springframework.hateoas.mvc.ControllerLinkBuilderFactory.linkTo(ControllerLinkBuilderFactory.java:139)
    at org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo(ControllerLinkBuilder.java:138)

我无法设置占位符{teacherId} 的值。谁能给我一个解决方案或最好的方法来处理这个问题。

最佳答案

在您的 Controller 中,teacherId 未注释为 @PathVariable

此外,您的链接创建看起来已损坏 - 试试这个:

resource.add(linkTo(methodOn(ToturialController.class).getAllToturialByTeacher(teacherId)).withRel("subjectsByTeacher"))

关于java - spring-hateoas,如何使用 onMethod 构建超媒体链接时设置占位符值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33602885/

相关文章:

node.js - Socket.IO 与 HapiJS 的连接

java - Spring 请求未传递给休息 Controller

java - 写入现有的 .txt 文件

java - 在servlet中更新sql语句而不是在servlet中

java - String foo = "bar"与 String foo = new String ("bar") 在 Android 中?

actionscript-3 - 使用BlazeDS和AS3的URLLoader将AMF作为REST格式

java - 是否有可用的 Java 库完全支持 Excel 的格式字符串?

java - 在 java REST/Spring/Hibernate 中返回动态值

java - 如何在 mybatis 和 spring boot 中使用一对一映射?

java - Spring 从哪个目录提供 View ?