我正在尝试为基于 Spring HATEOAS 的应用程序支持 XML 响应。JSON 响应和 XML 一样适用于单个资源。问题从资源列表开始。Spring MVC 控制器无法序列化借助 ResourceAssemblerSupport 派生类构建的列表。控制器为 curl 命令抛出“org.springframework.web.HttpMediaTypeNotAcceptableException:找不到可接受的表示”
curl -k -i -H "Accept:application/xml" -H "Media-Type:application/xml" -X GET http://127.0.0.1:8080/admin/roles*
我的 HATEOAS 资源是实体类的包装器:
@XmlRootElement
@XmlSeeAlso(RoleModel.class)
public class RoleResource extends ResourceSupport {
public RoleModel role;
}
控制器很简单:
@RequestMapping(method = RequestMethod.GET)
public @ResponseBody HttpEntity<List<RoleResource>> getAllRoles()
throws ObjectAccessException, ObjectNotFoundException {
List<RoleModel> resp = rolesManagement.getRoles();
return new ResponseEntity<List<RoleResource>>(roleResourceAssembler.toResources(resp),
HttpStatus.OK);
}
资源汇编类:
@Configuration
public class RoleResourceAssembler extends ResourceAssemblerSupport<RoleModel, RoleResource> {
public RoleResourceAssembler() {
super(RolesRestController.class, RoleResource.class);
}
@Bean
public RoleResourceAssembler roleResourceAssembler(){
return new RoleResourceAssembler();
}
@Override
public RoleResource toResource(RoleModel role) {
RoleResource res = instantiateResource(role);
res.role = role;
try {
res.add(linkTo(methodOn(RolesRestController.class).getRole(role.getRoleId())).withSelfRel());
} catch (ObjectAccessException | ObjectNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return res;
}
}
当我避免 ResourceAssemblerSupport 并像这样手动构建我的资源时:
@XmlRootElement
@XmlSeeAlso(RoleModel.class)
public class RolesList {
private List<Resource<RoleModel>> roles;
...
}
@RequestMapping(method = RequestMethod.GET)
public @ResponseBody HttpEntity<RolesList> getAllRoles()
throws ObjectAccessException, ObjectNotFoundException {
List<RoleModel> resp = rolesManagement.getRoles();
List<Resource<RoleModel>> roles =new ArrayList<>();
for (RoleModel model: resp) {
Resource<RoleModel> res = new Resource<RoleModel>(model);
res.add(linkTo(methodOn(RolesRestController.class).getRole(model.getRoleId())).withSelfRel());
roles.add(res);
}
RolesList list = new RolesList();
list.setRoles(roles);
return new ResponseEntity<RolesList>(list,
HttpStatus.OK);
}
XML 序列化有效。我想我可以避免使用资源汇编器并手动构建我的资源,但这会使代码不那么干净和模块化。我想知道是否仍然可以使用 ResourceAssemblerSupport 作为资源构建器并将资源列表作为 XML 返回