What is `ResponseEntity` does?

ResponseEntity 作为 Spring MVC controller层 的 HTTP 响应的类,包含状态码, headers, body (内容可以是任意类型的数据,包括字符串、对象、甚至是文件流)这三部分

返回集合数据:

@RestController
@Slf4j
public class SearchController {
    @Autowired
    UserService userService;

    @RequestMapping(value = "/getAllStudents4", method = RequestMethod.GET)
    public ResponseEntity<List<Student>> getAllStudents4() {
        List<Student> students = userService.listStudents3(1, 5);

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("test", "test");
        return ResponseEntity.ok().headers(httpHeaders).contentType(MediaType.APPLICATION_JSON).body(students);
    }
}

在这里插入图片描述
返回JSON数据:

@RestController
public class MyController {

    @GetMapping("/users/{id}")
    public ResponseEntity<User> getUser(@PathVariable Long id) {
        User user = userService.getUserById(id); // 假设userService是获取用户的方法

        if (user == null) {
            return ResponseEntity.notFound().build();
        }

        return ResponseEntity.ok(user);
    }
}

自定义错误信息:

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseEntity<String> handleException(Exception ex) {
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("An error occurred");
    }

    @ExceptionHandler(NotFoundException.class)
    public ResponseEntity<String> handleNotFoundException(NotFoundException ex) {
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Resource not found");
    }
}

在这里插入图片描述

Further Reading : @ControllerAdvice

处理成功或失败时返回不同状态码的样例:

@RestController
public class MyResourceController {

    @DeleteMapping("/resources/{id}")
    public ResponseEntity<Void> deleteResource(@PathVariable Long id) {
        try {
            resourceService.deleteResource(id); // 假设resourceService是资源删除服务
            return ResponseEntity.noContent().build(); // 成功删除时返回204 No Content
        } catch (ResourceNotFoundException e) {
            return ResponseEntity.notFound().build(); // 资源未找到时返回404 Not Found
        } catch (ResourceDeletionException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                                 .body(new ErrorResponse("Error deleting resource", e.getMessage()));
        }
    }

    // 自定义错误响应类
    static class ErrorResponse {
        private String error;
        private String message;

        public ErrorResponse(String error, String message) {
            this.error = error;
            this.message = message;
        }

        // getters and setters...
    }
}

下载文件:

@GetMapping("/download")
public ResponseEntity<Resource> downloadFile(@PathVariable String fileName) throws FileNotFoundException {
    Resource file = resourceLoader.getResource("classpath:files/" + fileName);

    HttpHeaders headers = new HttpHeaders();
    headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"");

    return ResponseEntity.ok()
                         .headers(headers)
                         .contentLength(file.contentLength())
                         .contentType(MediaType.APPLICATION_OCTET_STREAM)
                         .body(file);
}

处理分页结果:

@GetMapping("/users/page")
public ResponseEntity<Page<User>> getUsersByPage(Pageable pageable) {
    Page<User> usersPage = userService.getUsersByPage(pageable);
    
    if (usersPage.hasContent()) {
        return ResponseEntity.ok(usersPage);
    } else {
        return ResponseEntity.notFound().build();
    }
}
  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值