@RequestBody和@RequestParam区别与用法

@RequestBody和@RequestParam区别与用法

观前提示:

本文所使用的,IDEA版本为ultimate 2019.1,JDK版本为1.8.0_141,Tomcat版本为9.0.12。

1.@RequestBody

1.1 简介

@RequestBody接收的参数是来自requestBody中,即请求体中。

处理HttpEntity传递过来的数据,一般用来处理非Content-Type: application/x-www-form-urlencoded编码格式的数据。

1.2 例子

测试类 TestController .java

package com.example.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 测试Controller
 * @author jjy
 * @date 2020-07-21
 */
@Controller
@RequestMapping("/test")
public class TestController {
    
    

    /**
     * 测试RequestBody
     * @param jsonStr
     * @return
     */
    @RequestMapping("/testRequestBody")
    @ResponseBody
    public String testRequestBody(@RequestBody String jsonStr){
    
    
        System.out.println(jsonStr);
        return "success";
    }
}

使用Postman发送请求测试,结果如下
在这里插入图片描述

在这里插入图片描述

2. @RequestParam

2.1 简介

@RequestParam接收的参数是来自requestHeader中,即请求头。

用来处理Content-Type: 为 application/x-www-form-urlencoded编码的内容。

扫描二维码关注公众号,回复: 11858643 查看本文章

@RequestParam可以配置三个参数:

  1. required 表示是否必须,默认为 true,必须。

  2. defaultValue 可设置请求参数的默认值。

  3. value 为接收url的参数名(相当于key值)。

2.2 例子

测试类 TestController .java

package com.example.controller;

import com.example.model.Person;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 测试Controller
 * @author jjy
 * @date 2020-07-21
 */
@Controller
@RequestMapping("/test")
public class TestController {
    
    

    /**
     * 测试RequestParam
     * @param name
     * @return
     */
    @RequestMapping("/testRequestParam")
    @ResponseBody
    public String testRequestParam(@RequestParam(name = "userName") String name){
    
    
        System.out.println(name);
        return "success";
    }
}

使用Postman发送请求测试,结果如下

在这里插入图片描述
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43611145/article/details/107491118