ResponseEntity怎么用

ResponseEntity是 Spring 框架中用于处理 HTTP 响应的一个重要类。它可以让你完全控制 HTTP 响应的状态码、头部信息和响应体。

以下是一些常见的使用方式:

一、返回简单的响应体

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {

    @GetMapping("/example")
    public ResponseEntity<String> exampleEndpoint() {
        return new ResponseEntity<>("Hello, World!", HttpStatus.OK);
    }
}

在这个例子中,exampleEndpoint方法返回一个包含字符串 “Hello, World!” 的ResponseEntity,状态码为HttpStatus.OK(200)。

二、设置自定义状态码和响应体

@GetMapping("/custom-status")
public ResponseEntity<String> customStatusEndpoint() {
    return new ResponseEntity<>("Custom status response", HttpStatus.CREATED);
}

这里返回的状态码是HttpStatus.CREATED(201),表示资源已成功创建。

三、设置响应头部信息

import org.springframework.http.HttpHeaders;

@GetMapping("/with-headers")
public ResponseEntity<String> withHeadersEndpoint() {
    HttpHeaders headers = new HttpHeaders();
    headers.add("Custom-Header", "Value");
    return new ResponseEntity<>("Response with headers", headers, HttpStatus.OK);
}

这个例子中设置了一个自定义的头部信息 “Custom-Header”。

四、处理异常情况

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> handleException(Exception e) {
        return new ResponseEntity<>("An error occurred: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

通过@RestControllerAdvice注解,可以全局处理控制器中的异常,并返回适当的ResponseEntity

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值