QiYongchuan / MyGitBlog

个人博客主页,记录计算机学习,前端-后端-全栈学习ing
15 stars 0 forks source link

Springboot学习笔记:@RequestMapping #88

Open QiYongchuan opened 3 months ago

QiYongchuan commented 3 months ago

一句话介绍:@RequestMapping就是用来做路由映射的,即在Controller中,处理url地址以及前端发送的方法,进一步转到不同的方法中进行下一步的处理。

(补充:当然不仅限于URL路径,还可以设置(可选地)请求方法(如GET、POST等)、请求参数、请求头等条件)

@RequestMapping(value = "/users", method = RequestMethod.GET)
public List<User> getUsers() {
    // 方法体,返回用户列表
}

@RequestMapping(value = "/users", method = RequestMethod.POST, consumes = "application/json")
public User addUser(@RequestBody User user) {
    // 方法体,添加一个新用户
}

image 1.@RequestMapping 默认post、get请求均可以,可以在后面写上具体的方法,也可以直接用另一种等价的写法: @PostMapping 和@GetMapping

  1. 用实体来接受形参时:注意请求发送的形式不同:请求体(body)和URL查询参数传递数据 具体可参考 #87
 @RequestMapping("/Entiy")
    public String entity( User user){
        System.out.println(user);
        return "实体类接收参数";
    }
    @RequestMapping("/Entiy2")
    // 如果前端传递的参数是json格式的,
    // 那么可以使用@RequestBody
    public String entity2(@RequestBody User user){
        System.out.println(user);
        return "实体类接收参数Json";
    }

3.关于传参接收以及实体

多个参数自动装箱(boxing)成一个JavaBean

h5?empno=11&sal=1000&hiredate=2022-2-22
   @ResponseBody
    @RequestMapping("h5")
    public String h5(Emp emp)
    {
        return  "<h1>"+ emp + "</h1>";
    }

前提是该javaBean中有相应的属性