Spring Boot Controller:以与PagingAndSortingRepository相同的样式返回资源

时间:2018-10-15 12:09:00

标签: java spring rest spring-boot

我是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,这个问题似乎重复了。

Can I make a custom controller mirror the formatting of Spring-Data-Rest / Spring-Hateoas generated classes?


0 个答案:

没有答案