好的,下面是一个完整的示例代码,包括 `EmployeeController` 控制器类、分页方法以及统一结果返回的实现。 ### 1. 创建 `EmployeeController` 控制器类 ```java package com.example.demo.controller; import com.example.demo.model.Employee; import com.example.demo.service.EmployeeService; import com.example.demo.util.Result; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/employees") public class EmployeeController { @Autowired private EmployeeService employeeService; @CrossOrigin(origins = "*") // 解决跨域问题 @PostMapping("/page") public Result getPage(@RequestBody Employee employee, @RequestParam int currentPage, @RequestParam int limit) { return employeeService.findAll(employee, currentPage, limit); } } ``` ### 2. 创建分页方法 在 `EmployeeController` 中已经定义了分页方法 `getPage`,它接收三个参数: - `employee`: 前端传过来的 JSON 数据格式,后端自动转换为对象。 - `currentPage`: 当前页码。 - `limit`: 每页显示的条数。 ### 3. 服务层接口 `EmployeeService` 假设服务层接口 `EmployeeService` 已经存在,并且有一个方法 `findAll`: ```java package com.example.demo.service; import com.example.demo.model.Employee; import com.example.demo.util.Result; public interface EmployeeService { Result findAll(Employee employee, int currentPage, int limit); } ``` ### 4. 统一结果返回类 `Result` 创建一个统一的返回结果类 `Result`: ```java package com.example.demo.util; public class Result<T> { private int code; private String message; private T data; public Result() {} public Result(int code, String message, T data) { this.code = code; this.message = message; this.data = data; } // Getters and Setters public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public T getData() { return data; } public void setData(T data) { this.data = data; } // Static method for success response public static <T> Result<T> success(T data) { return new Result<>(200, "Success", data); } // Static method for error response public static <T> Result<T> error(String message) { return new Result<>(500, message, null); } } ``` ### 5. 示例 `Employee` 模型类 为了完整性,这里提供一个简单的 `Employee` 模型类: ```java package com.example.demo.model; public class Employee { private Long id; private String name; private String position; private Double salary; // Getters and Setters public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPosition() { return position; } public void setPosition(String position) { this.position = position; } public Double getSalary() { return salary; } public void setSalary(Double salary) { this.salary = salary; } } ``` 这样,你就完成了一个基本的 Spring Boot 项目,其中包含一个 `EmployeeController` 控制器类,支持分页查询,并能够处理跨域请求和返回统一的结果格式。 [2024-11-28 21:17:59 | AI写代码神器 | 1064点数解答]