我有一个非常简单的控制器,它发出 HTTP 请求并以 HATEOAS 格式接收一些资源。
package com.provider.spring.controller;
import java.util.List;
import org.springframework.hateoas.Link;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.client.RestTemplate;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.provider.employee.EmployeeDTO;
import com.provider.http.HttpComponentsClientHttpRequestFactoryBasicAuth;
import com.provider.spring.rest.Resource;
@Controller
public class EmployeeController {
private static final String REL_SELF = "self";
private static final String REL_SEARCH = "search";
private static final String REL_EMPLOYEE = "employee";
private static final String RESOURCE_URI = "http://localhost:8080/employees";
private RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactoryBasicAuth("user", "password"));
private List<EmployeeDTO> employees;
@RequestMapping("/employees")
public String getAllEmployees() {
String result = null;
try {
String resultBody = restTemplate.getForObject(RESOURCE_URI, String.class);
ObjectMapper objectMapper = new ObjectMapper();
Resource<EmployeeDTO> resource = objectMapper.readValue(resultBody, Resource.class);
// Get objects with relation "employee"
for(Link l : resource.getLinks()) {
if(l.getRel().equals(REL_EMPLOYEE)) {
// TODO: Construct EmployeeDTO from Link.
// TODO: Add EmployeeDTO to list.
}
}
}
catch(Exception e) {
e.printStackTrace();
result = "error";
return result;
}
return result;
}
}
是否存在将链接转换为对象的现有首选或标准方法?
有关 EmployeeDTO 的详细信息,请参见此处:https ://gist.github.com/Xerosigma/64469a30355f5de0228a