Spring Boot 中使用 ResponseEntity 和 @ResponseBody

2,394 阅读1分钟

转自连接: zetcode.com/springboot/…
原文作者: zetcode
原作者更多文章: zetcode.com/

Spring Boot 中使用 ResponseEntity 和 @ResponseBody

ResponseEntity

  • ResponseEntity 代表一个 HTTP 响应, 包含 headers, body 和 status.
  • @ResponseBody 断言将返回值放在响应的 body 中
  • ResponseEntity 允许自定义 headers 和 status.
代码
Country
public class Country {
    
    private String name;
    private int population;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getPopulation() {
        return population;
    }

    public void setPopulation(int population) {
        this.population = population;
    }
}
Controller
@Controller
public class MyController {
    
    @RequestMapping(value = "/getCountry")
    public ResponseEntity<Country> getCountry() {
        
        var c = new Country();
        c.setName("France");
        c.setPopulation(66984000);
        
        var headers = new HttpHeaders();
        headers.add("Responded", "MyController");
        
        return ResponseEntity.accepted().headers(headers).body(c);
    }
    
    @RequestMapping(value = "/getCountry2")
    @ResponseBody
    public Country getCountry2() {
        
        var c = new Country();
        c.setName("France");
        c.setPopulation(66984000);
        
        return c;
    }    
}