【问题标题】:Setup X-Total-Count with Spring Data REST使用 Spring Data REST 设置 X-Total-Count
【发布时间】:2018-02-17 16:01:12
【问题描述】:

我正在测试 Spring Data REST。 我关注了this tutorial 以了解它是如何工作的。

到目前为止的代码很简单:

@Entity
@SequenceGenerator(name="my_seq", sequenceName="user_id_seq")
@Table(name = "employees")
data class Employee (@Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "my_seq") val id: Long? = null,
                     val name: String = "defConstructorHell")

当我用 GET 询问时,我得到以下 json:

{
  "_embedded" : {
    "employees" : [ {
      "name" : "ciao",
      "_links" : {
        "self" : {
          "href" : "http://localhost:5000/api/employees/1"
        },
        "employee" : {
          "href" : "http://localhost:5000/api/employees/1"
        }
      }
    } ]
  },
  "_links" : {
    "self" : {
      "href" : "http://localhost:5000/api/employees{?page,size,sort}",
      "templated" : true
    },
    "profile" : {
      "href" : "http://localhost:5000/api/profile/employees"
    }
  },
  "page" : {
    "size" : 20,
    "totalElements" : 1,
    "totalPages" : 1,
    "number" : 0
  }
}

这完全没问题,但我使用的 js 框架需要标头 X-Total-Count。

您知道是否有使用 Spring Data REST 的方法吗?

【问题讨论】:

标签: spring rest spring-data-rest


【解决方案1】:

最终我添加了一个控制器来添加请求的标头:

@RepositoryRestController
class EmployeeController @Autowired constructor(val repo: EmployeeRepository) {

    @RequestMapping(method = arrayOf(GET),
            path = arrayOf("employees"))
    @ResponseBody
    fun getEmployees(@RequestParam("_sort", required = false, defaultValue = "id") _sort: String,
                     @RequestParam("_order", required = false, defaultValue = "DESC") _order: String,
                     @RequestParam("_start", required = false, defaultValue = "0") _start: Int,
                     @RequestParam("_end", required = false, defaultValue = "20") _end: Int): ResponseEntity<MutableIterable<Employee>> {
        val pr = PageRequest(_start, 20, Sort.Direction.valueOf(_order), _sort)
        val result = repo.findAll(pr)
        val headers = HttpHeaders()
        headers.add("X-Total-Count", result.count().toString())
        return ResponseEntity(result.content, headers, OK)
    }
}

【讨论】:

    猜你喜欢
    • 2019-12-14
    • 1970-01-01
    • 2021-07-04
    • 2020-07-02
    • 2022-12-22
    • 1970-01-01
    • 2016-10-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多