首页 > 解决方案 > Spring Boot Controller:以与 PagingAndSortingRepository 相同的样式返回资源

问题描述

我是 Spring Boot 的新手,如果这是一个愚蠢的问题,请原谅我。

我目前正在使用PagingAndSortingRepository来提供我的 REST API 的资源。但是出于某些安全原因,我需要自定义GET请求的结果。因此,我正在为方法实现一个控制器。

这是控制器:

@RestController
@RequestMapping("/dimensionAttributeValues")
public class DimensionAttributeValueController {

    @Autowired
    DimensionAttribueValueService dimensionAttribueValueService;

    @RequestMapping(method = RequestMethod.GET)
    @ResponseBody
    public PageImpl<DimensionAttributeValue> getDimensionAttributeValues(Pageable pageable) {
        Authentication user = SecurityContextHolder.getContext().getAuthentication();

        List<DimensionAttributeValue> result = new ArrayList<>();

        if (user.getAuthorities().contains("ADMIN")) {
            result = dimensionAttribueValueService.getAllDimensionAttributeValue();
        } else {
            result = dimensionAttribueValueService.getUserDimensionAttributeValue(user.getName());
        }

        return new PageImpl<DimensionAttributeValue>(result, pageable, result.size());
    } 
}

问题是,控制器不会以与存储库相同的样式返回资源。

结果与此类似:

{
   "content":[ {..}],
   "size":20,
   "totalElements":27,
   "totalPages":2   "number":0
}

我喜欢拥有的:

{
  "_embedded" : {
    "dimensionAttributeValue" : [ {..}, ]
  },
  "_links" : {
    "first" : {
      "href" : "http://localhost:8080/dimensionAttributes?page=0&size=20"
    },
    "self" : {
      "href" : "http://localhost:8080/dimensionAttributes{?page,size,sort}",
      "templated" : true
    },
    "next" : {
      "href" : "http://localhost:8080/dimensionAttributes?page=1&size=20"
    },
    "last" : {
      "href" : "http://localhost:8080/dimensionAttributes?page=1&size=20"
    },
    "profile" : {
      "href" : "http://localhost:8080/profile/dimensionAttributes"
    },
    "search" : {
      "href" : "http://localhost:8080/dimensionAttributes/search"
    }
  },
  "page" : {
    "size" : 20,
    "totalElements" : 37,
    "totalPages" : 2,
    "number" : 0
  }
}

谢谢你的帮助!


感谢@Adi,这个问题似乎是重复的。

我可以让自定义控制器镜像 Spring-Data-Rest / Spring-Hateoas 生成的类的格式吗?


标签: javaspringrestspring-boot

解决方案


推荐阅读