@RequestBody和@RequestParam区别与用法

本文详细介绍了Spring MVC中@RequestBody和@RequestParam的区别与用法。@RequestBody用于处理非application/x-www-form-urlencoded编码格式的数据,从请求体获取信息;而@RequestParam则从请求头中获取Content-Type为application/x-www-form-urlencoded编码的内容。文章通过测试类和Postman测试举例说明了两者的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

@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编码的内容。

@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发送请求测试,结果如下

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值