SpringBoot Controller层接收参数的方式

入参注解

先来了解几个入参注解的定义:

  • @RequestParam:获取查询参数,用在方法的参数前面。即 url?name= 这种形式。比如

    http://localhost:8080/demo/123?name=suki_rong

    String a =request.getParameter("a")。

  • @PathVariable:路径变量。参数与路径上大括号里的名字要一致。

    RequestMapping("user/get/mac/{macAddress}")
    public String getByMacAddress(@PathVariable String macAddress){
          
          
      //do something;
    }
    
  • @ResponseBody:表示该方法的返回结果直接写入HTTP response body中

    一般在异步获取数据时使用,在使用@RequestMapping后,返回值通常解析为跳转路径,加上@responsebody后返回结果不会被解析为跳转路径,而是直接写入HTTP response body中。比如异步获取json数据,加上@responsebody后,会直接返回json数据

  • @RestController
    用于标注控制层组件(如struts中的action),包含 @Controller 和 @ResponseBody。


GET方式传参

@PathVariable: 接受restful风格,不接受josn方式传递,可以通过路径传递参数,常用的注解
在这里插入图片描述
在这里插入图片描述
@RequestParam:用于指定参数名称
在这里插入图片描述
在这里插入图片描述

POST方式传参

  • post方式最好的方式是用josn格式。
  • 在cotroller层对象前加注解@RequestBody将数据和前端映射,前端会将json或者thml格式的数据存入body缓冲区传到controller
  • @ResponseBody会将获取的数据以json的格式返回
    在这里插入图片描述
    在这里插入图片描述

POST方式用 @RequestParam 注解,会以表单的形式接受数据
在这里插入图片描述
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_44668898/article/details/121797596