这是一个稍微复杂些的 Controller 的例子,演示了更多功能。
Spring Start io
pom.xml
<dependency>
<groupId>org.joda</groupId>
<artifactId>joda-money</artifactId>
<version>1.0.1</version>
</dependency>
<dependency>
<groupId>org.jadira.usertype</groupId>
<artifactId>usertype.core</artifactId>
<version>7.0.0.CR1</version>
</dependency>
application.properties, schema.sql, data.sql
如下工具可以帮助调试code,推荐使用 Postman。
class 上的path,是所有 method 的prefix
Get Request: http://localhost:8080/coffee/?name=latte
@GetMapping(path = "/", params = "name")
@ResponseBody
public Coffee getByName(String name) {
return coffeeService.getCoffee(name);
}
Get Request: http://localhost:8080/coffee/ @ResponseBody 代表结果将在 Response Body 中传回来。
@GetMapping(path = "/", params = "!name")
@ResponseBody
public List<Coffee> getAll() {
return coffeeService.getAllCoffee();
}
** Get Request: http://localhost:8080/coffee/2 produces 对应Request Header**: Accept = application/json;charset=UTF-8 @PathVariable Long id 代表 id 从 Request Path 中获取。
@RequestMapping(path = "/{id}", method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
public Coffee getById(@PathVariable Long id) {
Coffee coffee = coffeeService.getCoffee(id);
return coffee;
}
** Post Request: http://localhost:8080/order/ consumes 对应Request Header: Content-Type = application/json produces 对应Request Header**: Accept = application/json;charset=UTF-8 @RequestBody NewOrderRequest newOrder 代表 order信息 从 Request Body 中获取。 @ResponseStatus(HttpStatus.CREATED) 表示正确返回的状态为 201,不再是默认的 200。 注意:CoffeeOrderController 上的 @RestController = @Controller + @ResponseBody,所以此 method 没有添加 @ResponseBody 注解。
@PostMapping(path = "/", consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseStatus(HttpStatus.CREATED)
public CoffeeOrder create(@RequestBody NewOrderRequest newOrder) {
log.info("Receive new order: {}", newOrder);
Coffee[] coffeeList = coffeeService.getCoffeeByName(newOrder.getItems())
.toArray(new Coffee[]{});
return orderService.createOrder(newOrder.getCustomer(), coffeeList);
}