Spring Controller 学习笔记

owo

控制器

  • Spring Boot 提供了 @Controller@RestController 两种注解来标识此类负责接收和处理http请求
    • @Controller 需要返回一个视图(可以理解为html页面)
    • @RestController 可以以纯文本返回

路由映射

  • @RequestMapping("/user")
  • 支持正则表达式匹配
  • Method 匹配: @RequestMapping(value = "/getData", method = RequestMethod.GET)
@RestController
public class HelloController {

    @RequestMapping(value = "/hello", method = RequestMethod.GET)
//    @GetMapping("/hello")
    //这两种方式等价
    public String hello() {
        return "你好";
    }
}

传参的参数名要对上

@RequestMapping(value = "/hello", method = RequestMethod.GET)
//http://localhost:8080/hello?nickname=hxy
public String hello(String nickname, String phone) {
    System.out.println(phone);
    return "你好" + nickname;
}

@RequestParam() 指定必须参数,否则报错

@RequestMapping(value = "/getTest3", method = RequestMethod.GET)
public String getTest3(@RequestParam("nickname") String name) {
    System.out.println("nickname:" + name);
    return "GET请求";
}

可以通过 required=false 关闭强制要求

@RequestMapping(value = "/getTest3", method = RequestMethod.GET)
public String getTest3(@RequestParam(value = "nickname",required = false) String name) {
    System.out.println("nickname:" + name);
    return "GET请求";
}

用对象接收参数

@RequestMapping(value = "/postTest1", method = RequestMethod.POST)
public String postTest1(User user) {
    System.out.println(user);
    return "POST请求";
}

接收json

@RequestMapping(value = "/postTest2", method = RequestMethod.POST)
public String postTest2(@RequestBody User user) {
    System.out.println(user);
    return "POST请求";
}

通配符

@RequestMapping(value = "/test/**", method = RequestMethod.GET)
public String postTest3() {
    System.out.println("Hello");
    return "POST";
}
img_show