Spring Boot - 5. Controller 的使用

2018-01-18  本文已影响20人  ChenME
  1. @Controller :处理 http 请求;
  2. @RestController :Spring4 之后新加的注解,原来返回 json 需要 @ResponseBody 配合 @Controller
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
}
  1. @RequsetMapping :配置 url 映射;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String sayHello() {
    return "Hello";
}
  1. @PathVariable :获取 URL 中的数据;
import org.springframework.web.bind.annotation.PathVariable;

@RequestMapping(value = "/{id}/hello", method = RequestMethod.GET)
public String sayHello(@PathVariable("id") Integer id) {
    return "id is " + id;
}

// 访问 http://localhost:8081/cme/23/hello
屏幕快照 2018-01-18 15.58.51.png
  1. @RequestParam :获取请求参数的值;
import org.springframework.web.bind.annotation.RequestParam;

@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String sayHello(@RequestParam("id") Integer myId) {
    return "id is " + myId;
}

// 访问 http://localhost:8081/cme/hello?id=100
屏幕快照 2018-01-18 16.05.54.png
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String sayHello(@RequestParam(value = "id", required = false, defaultValue = "0") Integer myId) {
    return "id is " + myId;
}

// 访问 http://localhost:8081/cme/hello
屏幕快照 2018-01-18 16.11.44.png
  1. @GetMapping @PostMapping ... :组合注解;
上一篇下一篇

猜你喜欢

热点阅读