创建项目:
IDEA新建springboot项目;
如图所示建包和类;
项目结构:
关键代码:
ParaController.java
1 package com.example.demo.controller; 2 3 import org.springframework.web.bind.annotation.*; 4 5 @RestController 6 // 该类下的所有方法加统一前缀 7 // @RequestMapping("/prefix") 8 public class ParaController { 9 10 // http://localhost:8080/firstRequest 11 @GetMapping({"/firstRequest"}) 12 public String firstRequest(){ 13 return "第一个接口."; 14 } 15 16 17 // http://localhost:8080/requestPara?num=34 18 @GetMapping({"/requestPara"}) 19 public String requestPara(@RequestParam Integer num){ 20 return "para from request: " + num; 21 } 22 23 24 // http://localhost:8080/para/6 25 @GetMapping({"/para/{num}"}) 26 public String pathPara(@PathVariable Integer num){ 27 return "para from path: " + num; 28 } 29 30 31 // 多url 32 // http://localhost:8080/para1/9 33 // http://localhost:8080/para2/9 34 @GetMapping({"/para1/{num}", "/para2/{num}"}) 35 public String multiUrl(@PathVariable Integer num){ 36 return "para from path: " + num; 37 } 38 39 40 // 参数设默认值 41 // http://localhost:8080/required 42 // http://localhost:8080/required?num=5 43 @GetMapping({"/required"}) 44 public String required(@RequestParam(required = false, defaultValue = "0") Integer num){ 45 return "para from request: " + num; 46 } 47 48 }
方法分析:
最简单的实现:
http://localhost:8080/firstRequest
1 @GetMapping({"/firstRequest"}) 2 public String firstRequest(){ 3 return "第一个接口."; 4 }
路径中带参数:
http://localhost:8080/requestPara?num=34
1 @GetMapping({"/requestPara"}) 2 public String requestPara(@RequestParam Integer num){ 3 return "para from request: " + num; 4 }
路径中带参数:
http://localhost:8080/para/6
1 @GetMapping({"/para/{num}"}) 2 public String pathPara(@PathVariable Integer num){ 3 return "para from path: " + num; 4 }
多url:
http://localhost:8080/para1/9
http://localhost:8080/para2/9
1 @GetMapping({"/para1/{num}", "/para2/{num}"}) 2 public String multiUrl(@PathVariable Integer num){ 3 return "para from path: " + num; 4 }
参数设默认值:
http://localhost:8080/required
http://localhost:8080/required?num=5
1 @GetMapping({"/required"}) 2 public String required(@RequestParam(required = false, defaultValue = "0") Integer num){ 3 return "para from request: " + num; 4 }