代码之家  ›  专栏  ›  技术社区  ›  dierre

使用弹簧数据静止设置X-Total-Count

  •  1
  • dierre  · 技术社区  · 7 年前

    我正在测试Spring数据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

    {
      "_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。

    1 回复  |  直到 7 年前
        1
  •  0
  •   dierre    7 年前

    最后,我添加了一个控制器,用于添加请求的标头:

    @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)
        }
    }