🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
``` // @RestController: 等同于 @Controller + @RequestBody 注解 @RestController public class HelloController { // GET /get?name=剑齿虎 @GetMapping("/get") public String get(@RequestParam(name = "name", defaultValue = "剑齿虎") String name, @RequestParam("age") Integer age) { // defaultValue 默认值 // @RequestParam() 还有一个 required(bool类型), 是否必填参数 return name + "--" + age; } // POST /json {"name":"余小波", "age":16} @PostMapping(value = "/json", produces = MediaType.APPLICATION_XML_VALUE) public Lrz woc(@RequestBody Lrz lrz) { // 响应XMl, JSON同理 不过可以忽略produces, 默认即json lrz.setName("天王盖地虎"); return lrz; } // GET /formdata?name=余小波&age=14 @GetMapping("/formdata") public String formdata(Lrz lrz) { return lrz.toString(); } } ``` ### @RestController 资源控制器, 相当于`@Controller`+`@RequestBody` ``` @RestController public class HelloController { ... } ``` ### 请求类型 springboot是以注解来定义请求方法的, 定义请求方法的注解有以下几个 - GetMapping - PostMapping - PutMapping - DeleteMapping ```java @GetMapping("/employees") List<Employee> all() { ... } @PostMapping("/employees") Employee newEmployee(@RequestBody Employee newEmployee) { ... } // Single item @GetMapping("/employees/{id}") Employee one(@PathVariable Long id) { ... } @PutMapping("/employees/{id}") Employee replaceEmployee(@RequestBody Employee newEmployee, @PathVariable Long id) { ... } @DeleteMapping("/employees/{id}") void deleteEmployee(@PathVariable Long id) { ... } ```