Spring Boot - 5. Controller 的使用
2018-01-18 本文已影响20人
ChenME
-
@Controller
:处理 http 请求; -
@RestController
:Spring4 之后新加的注解,原来返回 json 需要@ResponseBody
配合@Controller
;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
}
-
@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";
}
-
@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
-
@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
-
@GetMapping @PostMapping
... :组合注解;