【发布时间】:2018-07-05 01:47:47
【问题描述】:
我不是专业的 Spring Boot 开发人员。我在教程的帮助下编写程序,我正在使用 Hateoas 和 Rest,当我从请求返回响应时,我得到一个白标签错误页面。
当我尝试使用 System.out.println() 写入值时,资源对象本身看起来是正确的。
这是 RestController 方法。
@RequestMapping(method = RequestMethod.GET ,produces = {MediaType.APPLICATION_JSON_VALUE, "application/hal+json"})
Resources<SubjectResource> readSubject(@PathVariable String userId) {
this.validateUser(userId);
List<SubjectResource>subjectResource=subjectRepository.findByTeacherUsername(userId).stream().map(SubjectResource:: new).collect(Collectors.toList());
Resources <SubjectResource>r=new Resources<>(subjectResource);
return new Resources<>(subjectResource);
}
这是我在 RestController 类中使用的导入
import java.net.URI;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.hateoas.Link;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.hateoas.Resources;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
这是资源文件
import org.springframework.hateoas.Link;
导入 org.springframework.hateoas.ResourceSupport; 导入静态 org.springframework.hateoas.mvc.ControllerLinkBuilder.*;
class SubjectResource extends ResourceSupport {
private final Subject subject;
public SubjectResource(Subject subject) {
String username = subject.getTeacher().getUsername();
this.subject = subject;
this.add(new Link(subject.uri, "subject-uri"));
this.add(linkTo(SubjectRestController.class, username).withRel("subjects"));
this.add(linkTo(
methodOn(SubjectRestController.class, username).readSubject(username,
subject.getId())).withSelfRel());
}
public Subject getSubject() {
return subject;
}
}
然后在我的浏览器中输入
有人知道我做错了什么吗?谢谢/米克
【问题讨论】:
-
从你的代码来看,我想说你应该构建一个
Resources<Subject>,而不是Resources<SubjectResource>。但首先,您需要更好地说明您的问题:向我们展示Subject课程,告诉我们您致电/anna_n/subjects时会得到什么。您还可以通过删除不必要的空行和导入语句来清理代码示例(您使用的是标准 Java 和 Spring 类,因此导入不会在此处带来相关信息)。这将使我们更容易为您提供帮助。 -
谢谢。我回家后会检查并添加额外的代码
标签: java spring-boot spring-hateoas