【发布时间】:2016-04-27 11:52:12
【问题描述】:
我不明白我需要添加什么才能使我的程序成为 HATEOAS。我有 Account.java、Post.java、Controllers 和 repositories。从一些指南中,他们添加了 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;
}
}
【问题讨论】: