我正在做一个安静的应用程序。我一直在尝试为具有路径变量teacherId
的方法构建超媒体链接,如下面的代码所示。我使用 methodOn
为 getAllToturialByTeacher
方法构建链接,例如 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/