有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java实现Spring HATEOAS链接构建

我不明白我需要添加什么才能使我的程序成为HATEOAS。我有帐户。java,Post。java、控制器存储库。从一些指南中,他们添加了AccountResource和PostResource,在这些类中构建链接。AccountResource和Account之间的区别是什么?我两者都需要吗?如果是,我是否为每个普通类创建一个资源类?我试着这样做,但根本不起作用。我不知道我在做什么:(。我需要一些帮助来理解如何从普通REST迁移到HATEOAS。我需要添加哪些类

public class Account {

//Account ID
@Id private String userId;

//General info
protected String firstName;
protected String lastName;
protected String username;
protected String email;
protected String password;
protected String birthDate;
protected String activities;
protected String uri;
private Set<Post> posts = new HashSet<>();
List<Account> friends = new ArrayList<Account>();

//Getter, constructor...



@RestController
public class AccountController {    

@Autowired
private AccountRepository accountRepository;

//Create account 
@RequestMapping(value="/accounts", method = RequestMethod.POST) 
public ResponseEntity<?> accountInsert(@RequestBody Account account) {

    account = new Account(account.getUri(), account.getUsername(), account.getFirstName(), account.getLastName(), account.getEmail(), account.getPassword(), account.getBirthDate(), account.getActivities(), account.getFriends());
    accountRepository.save(account);
    HttpHeaders httpHeaders = new HttpHeaders();
    Link forOneAccount = new AccountResource(account).getLink("self");
    httpHeaders.setLocation(URI.create(forOneAccount.getHref()));

    return new ResponseEntity<>(null, httpHeaders, HttpStatus.CREATED);
}



public class AccountResource extends ResourceSupport {

private Account account;

public AccountResource(Account account) {
    String username = account.getUsername();
    this.account = account;
    this.add(new Link(account.getUri(), "account-uri"));
    this.add(linkTo(AccountController.class, username).withRel("accounts"));
    this.add(linkTo(methodOn(AccountController.class, username).getUniqueAccount(account.getUserId())).withSelfRel());
}

public AccountResource() {

}

public Account getAccount() {
    return account;
}
}

共 (1) 个答案

  1. # 1 楼答案

    AccountPost等是您的域实体,而*Resource是API向外部世界公开的它们的表示

    域实体可能是,例如,JPA实体,包含其持久性以及与其他实体的关系所需的所有元数据。 即使它们不是JPA实体,它们也是应用程序业务逻辑使用的内部表示

    参考资料包含JSON序列化/反序列化的信息,不直接引用其他资源

    看看这个示例项目https://github.com/opencredo/spring-hateoas-sample和相关的博客帖子:Implementing HAL hypermedia REST API using Spring HATEOAS

    它实现了一个简单但不那么琐碎的库API,带有一个Book-Author-Publisher域