@RequestBody与@RequestParam

@RequestBody

1、注解@RequestBody接收的参数是来自请求体中的,一般用于处理非Content-Type:application/x-www-form-urlencoded编码格式的数据,一般用于处理:application/json、application/xml等类型数据
2、@RequestBody不能在同一个方法中出现多次
3、@RequestBody,接收的参数是来自请求体中的,一般对应使用的请求是POST请求
4、GET请求中,因为没有HttpEntity,所以@RequestBody并不适用。
5、POST请求中,通过HttpEntity传递的参数,必须要在请求头中声明数据的类型Content-Type,SpringMVC通过使用HandlerAdapter 配置的HttpMessageConverters来解析HttpEntity中的数据,然后绑定到相应的bean上。

了解注解

package org.springframework.web.bind.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RequestBody {
    boolean required() default true;
}

使用注解

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

@RequestParam

1、⽤来处理Content-Type: 为 application/x-www-form-urlencoded编码的内容。(Http协议中,如果不指定Content-Type,则默认传递的参数就是application/x-www-form-urlencoded类型)

了解注解

required 表示是否必须,默认为 true,必须。
defaultValue 可设置请求参数的默认值。
value 为接收url的参数名(相当于key值)。

package org.springframework.web.bind.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.core.annotation.AliasFor;

@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RequestParam {
    @AliasFor("name")
    String value() default "";

    @AliasFor("value")
    String name() default "";

    boolean required() default true;

    String defaultValue() default "\n\t\t\n\t\t\n\ue000\ue001\ue002\n\t\t\t\t\n";
}

使用注解

controller
在这里插入图片描述
请求该接口相当于:

在这里插入图片描述

总结

1.Post请求接收@RequestBody修饰的参数和@RequestParam修饰的参数,而Get请求则只能接收@RequestParam修饰的参数。
2.如果前端传的是Json类型的对象,后台就要使用@RequestBody修饰的实体类接收,如果是单个属性就使用@RequestParam修饰的变量或实体类。
3、@RequestBody和@ResquestParam()可以在同一个接口中一起用,@RequestBody最多只能有一个,而@ResquestParam()可以有多个

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值