AdSense

網頁

2021/8/30

Spring Boot REST API使用ResponseEntity返回自訂的HTTP status及Content-Type

Spring Boot在Controller或ControllerAdvice可使用ResponseEntity<T>自訂回應(Reesponse)返回的HTTP狀態碼及Content-Type如下。


DemoController

package com.abc.demo.controller;

import com.abc.demo.model.Employee;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;

@RestController
public class DemoController {

    @GetMapping("/employees")
    public ResponseEntity<List<Employee>> getEmployees() {

        List<Employee> employeeList = Arrays.asList(
                new Employee(1, "John", 33),
                new Employee(2, "Mary", 28),
                new Employee(3, "Jason", 45)
        );

        return ResponseEntity
                .status(HttpStatus.OK) // HTTP Status
                .contentType(MediaType.APPLICATION_JSON) // Content-Type(media type)
                .body(employeeList);
    }

}


沒有留言:

AdSense