java springboot工程RESTful入门案例 认识请求类型 参数

我们先创建一个java的springboot工程
然后 我们先用老方式试一下
在启动类的同级创建目录controller
下面创建一个类 叫 UserController
参考代码如下

package com.example.threshold.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class UserController {
    
    

    @RequestMapping("/get")
    @GetMapping
    public String getMin(){
    
    
        return "访问成功";
    }
}

然后 启动项目
在这里插入图片描述
系统分配给我的端口是8080

然后 我们用浏览器访问 http://localhost:8080/user/get

在这里插入图片描述
可以看到 这就放回成功了
在这里插入图片描述
将RequestMapping的第二个参数 改为 method = RequestMethod 马上系统就会提示你它全部的类型 这里 我们选择get
在这里插入图片描述
最常用的 应该就是 get put post delete四种类型 其中 get和post会更多一些
我们将参考代码修改如下

package com.example.threshold.controller;

import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
public class UserController {
    
    

    @RequestMapping(value = "/get",method = RequestMethod.GET)
    @ResponseBody
    public String getMin(){
    
    
        return "访问成功";
    }
}

重启项目
在这里插入图片描述
端口没有变化 我们再次访问http://localhost:8080/user/get
没有任何问题

在这里插入图片描述
然后 我们将代码修改如下

package com.example.threshold.controller;

import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
public class UserController {
    
    

    @RequestMapping(value = "/get/{id}",method = RequestMethod.GET)
    @ResponseBody
    public String getMin(@PathVariable Integer id){
    
    
        return "您传输的id是"+id;
    }
}

PathVariable 就是在告诉系统 你这个参数要从路径上去拿 而这样 对应你的路径就也要改 我们在路径后面加了个 /id 这个id和下面的参数名id相同 所以可以匹配

我们再次重启程序
访问
http://localhost:8080/user/get/3 这次我们的路径后面跟了个3 这就是我们传给它的id
在这里插入图片描述
系统也是顺利的接到了并回馈了我们的参数

如果你的请求参数要在请求头中获取 且是JSON 那就 将 PathVariable 改成 RequestBody就好了
如果是 路径问号后的参数 例如 请求地址?XX=XX 或者表单类型的参数 那就用RequestParam

猜你喜欢

转载自blog.csdn.net/weixin_45966674/article/details/130175609