springboot注解及GET、POST接口写法

一、注解
springboot提供了@Contrller和@RestController。

@Controller:返回页面和数据

@RestController:返回数据

@RestMapping注解:主要做路径映射url

value:请求URL的路径。

method:HTTP请求方法。

@RestMapping(value="user", method= RequestMethod.GET)

1.1 GET

  • 无参数
@RequestMapping (value="/hello", method= RequestMethod.GET)
    public String hello(String name){
        return "123"+name;
    }
  • 参数传递
@RequestMapping (value="/hello", method= RequestMethod.GET)
    public String hello(String name){
        return "123"+name;
    }
  • 参数映射

@RequestParam注解代表参数映射,将传入进来的nickname映射到name

@RequestMapping (value="/hello2", method= RequestMethod.GET)
    public String hello2(@RequestParam(value ="nickname",required = false) String name){
        return "123"+name;
    }

1.2 POST

  • 无参数
@RequestMapping(value = "/post1", method = RequestMethod.POST)
    public String post1(){
        return "hello post";
    }
  • 带参数
@RequestMapping(value = "/post2", method = RequestMethod.POST)
    public String post2(String username, String password){
        return username+"-"+password;
    }
  • Bean封装
@RequestMapping(value = "/post3",method = RequestMethod.POST)
    public String post3(User user){
        System.out.println(user);
        return "post";
    }
  • json

要在参数前面加一个注解@RequestBody,传入进来的参数名和类的私有变量要保持一致

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

1.3错误

  • 404 :路劲不对
  • 405:方法不被允许

相关推荐

  1. springboot注解GET、POST接口写法

    2024-04-02 06:26:02       17 阅读
  2. springboot 注解+AOP实现接口方法出入参打印

    2024-04-02 06:26:02       47 阅读
  3. springboot如何通过注解优雅实现接口多版本管理

    2024-04-02 06:26:02       18 阅读
  4. SpringBoot + Redis 实现接口限流,一个注解的事

    2024-04-02 06:26:02       15 阅读
  5. SpringBoot注解

    2024-04-02 06:26:02       43 阅读
  6. SpringBoot注解

    2024-04-02 06:26:02       18 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-04-02 06:26:02       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-04-02 06:26:02       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-04-02 06:26:02       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-04-02 06:26:02       20 阅读

热门阅读

  1. Towhee

    Towhee

    2024-04-02 06:26:02      21 阅读
  2. Android Room的使用

    2024-04-02 06:26:02       16 阅读
  3. easyexcel 动态列导出

    2024-04-02 06:26:02       15 阅读
  4. Ubuntu 自启动应用程序的方法

    2024-04-02 06:26:02       14 阅读
  5. 郭天祥新概念51单片机(第五期读书笔记)

    2024-04-02 06:26:02       15 阅读
  6. 【日常积累】指定ruby版本环境安装

    2024-04-02 06:26:02       16 阅读
  7. GPT带我学-设计模式11-组合模式

    2024-04-02 06:26:02       17 阅读
  8. 选择排序与冒泡排序

    2024-04-02 06:26:02       15 阅读
  9. Day4:学习尚上优选项目

    2024-04-02 06:26:02       15 阅读
  10. redis中怎么用分布式token

    2024-04-02 06:26:02       15 阅读
  11. Docker

    2024-04-02 06:26:02       13 阅读