springboot中返回result类的具体代码controller,util,
时间: 2024-05-06 16:18:55 浏览: 113
详解Spring Boot中Controller用法
以下是一个使用Spring Boot返回Result类的示例代码:
Controller层:
```java
@RestController
@RequestMapping("/api")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/users")
public Result<List<User>> getAllUsers() {
List<User> userList = userService.getAllUsers();
return Result.success(userList);
}
@GetMapping("/users/{id}")
public Result<User> getUserById(@PathVariable("id") Long id) {
User user = userService.getUserById(id);
return Result.success(user);
}
@PostMapping("/users")
public Result<User> createUser(@RequestBody User user) {
User newUser = userService.createUser(user);
return Result.success(newUser);
}
@PutMapping("/users/{id}")
public Result<User> updateUser(@PathVariable("id") Long id, @RequestBody User user) {
User updatedUser = userService.updateUser(id, user);
return Result.success(updatedUser);
}
@DeleteMapping("/users/{id}")
public Result deleteUser(@PathVariable("id") Long id) {
userService.deleteUser(id);
return Result.success();
}
}
```
Util层:
```java
public class Result<T> {
private int code;
private String message;
private T data;
public Result() {
}
public Result(int code, String message) {
this.code = code;
this.message = message;
}
public Result(int code, String message, T data) {
this.code = code;
this.message = message;
this.data = data;
}
public static <T> Result<T> success() {
return new Result<>(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMessage());
}
public static <T> Result<T> success(T data) {
return new Result<>(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMessage(), data);
}
public static <T> Result<T> failure(ResultCode resultCode) {
return new Result<>(resultCode.getCode(), resultCode.getMessage());
}
public static <T> Result<T> failure(ResultCode resultCode, String message) {
return new Result<>(resultCode.getCode(), message);
}
// getters and setters
}
```
其中,Result类是一个泛型类,可以根据需要返回不同类型的数据。在这个示例中,我们使用了一个枚举类ResultCode来定义返回结果的状态码和信息。
```java
public enum ResultCode {
SUCCESS(200, "成功"),
FAILURE(400, "失败"),
UNAUTHORIZED(401, "未认证"),
NOT_FOUND(404, "不存在"),
INTERNAL_SERVER_ERROR(500, "内部服务器错误");
private final int code;
private final String message;
ResultCode(int code, String message) {
this.code = code;
this.message = message;
}
public int getCode() {
return code;
}
public String getMessage() {
return message;
}
}
```
阅读全文