owo
控制器
- Spring Boot 提供了
@Controller 和
@RestController 两种注解来标识此类负责接收和处理http请求
@Controller 需要返回一个视图(可以理解为html页面)
@RestController 可以以纯文本返回
路由映射
@RequestMapping("/user")
- 支持正则表达式匹配
- Method 匹配:
@RequestMapping(value = "/getData", method = RequestMethod.GET)
1 2 3 4 5 6 7 8 9 10
| @RestController public class HelloController {
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String hello() { return "你好"; } }
|
传参的参数名要对上
1 2 3 4 5 6
| @RequestMapping(value = "/hello", method = RequestMethod.GET)
public String hello(String nickname, String phone) { System.out.println(phone); return "你好" + nickname; }
|
@RequestParam() 指定必须参数,否则报错
1 2 3 4 5
| @RequestMapping(value = "/getTest3", method = RequestMethod.GET) public String getTest3(@RequestParam("nickname") String name) { System.out.println("nickname:" + name); return "GET请求"; }
|
可以通过 required=false 关闭强制要求
1 2 3 4 5
| @RequestMapping(value = "/getTest3", method = RequestMethod.GET) public String getTest3(@RequestParam(value = "nickname",required = false) String name) { System.out.println("nickname:" + name); return "GET请求"; }
|
用对象接收参数
1 2 3 4 5
| @RequestMapping(value = "/postTest1", method = RequestMethod.POST) public String postTest1(User user) { System.out.println(user); return "POST请求"; }
|
接收json
1 2 3 4 5
| @RequestMapping(value = "/postTest2", method = RequestMethod.POST) public String postTest2(@RequestBody User user) { System.out.println(user); return "POST请求"; }
|
通配符
1 2 3 4 5
| @RequestMapping(value = "/test/**", method = RequestMethod.GET) public String postTest3() { System.out.println("Hello"); return "POST"; }
|