软件编程
位置:首页>> 软件编程>> java编程>> SpringMVC中@ModelAttribute与@RequestBody的区别及说明

SpringMVC中@ModelAttribute与@RequestBody的区别及说明

作者:弱水提沧  发布时间:2023-11-24 12:09:51 

标签:SpringMVC,@ModelAttribute,@RequestBody

@ModelAttribute与@RequestBody的区别

最近在写代码的过程中,发现之前项目都是使用的@ModelAttribute注解,而自己的一贯使用都是@RequestBody,在网上找资料也没有发现写的十分具体的博客,因此自己写了个SpringBoot的样例进行了测试验证。

@ModelAttribute与@RequestBody都是用来注解解析前端发来数据,并自动对应到所定义的字段名称。

这里先放结论

使用@ModelAttribute注解的实体类接收前端发来的数据格式需要为"x-www-form-urlencoded",@RequestBody注解的实体类接收前端的数据格式为JSON(application/json)格式。

(若是使用@ModelAttribute接收application/json格式,虽然不会报错,但是值并不会自动填入)

测试

首先新建一个SpringBoot项目,这个不需要像SpringMVC项目那么配置麻烦,因为十分推荐这个。

导入需要的spring-boot-starter-web包。由于测试的前端发送的为json数据,因此还需要导入json依赖。

        <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.4</version>
            <classifier>jdk15</classifier>
        </dependency>
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>commons-beanutils</groupId>
            <artifactId>commons-beanutils</artifactId>
            <version>1.9.2</version>
        </dependency>
        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>3.2.1</version>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.2</version>
        </dependency>

根据前端发送的数据,定义自己的接收实体类RuleModify,其字段名与前端发送的key值一致,若是需要改变,可以使用@SerializerName("")进行对应相应的key值。这里就不贴出代码。 

在Controller层对于要测试的方法使用@RequestBody接收前端数据,可以看到数据都一一对应到实体类中了(测试工具为postman)。

@RestController
@RequestMapping("/")
public class TestController {
 
    @RequestMapping(value = "/test" ,method = RequestMethod.POST)
    public String testJson(@RequestBody RuleModify rule){
        System.out.println("执行");
        JSONObject jsonObject = JSONObject.fromObject(rule);
        System.out.println(jsonObject);
        return "hello";
    }
    
}

postman模拟前端发送请求。

SpringMVC中@ModelAttribute与@RequestBody的区别及说明

可以看到成功打印出实体类,数据已经对应到字段中了。

SpringMVC中@ModelAttribute与@RequestBody的区别及说明

接下来使用@ModelAttribute注解RuleModify类,可以看到JSON(application/json) 格式下,数据为空,字段没有进行注入。

SpringMVC中@ModelAttribute与@RequestBody的区别及说明

使用postman的x-www-form-urlencoded方式进行模拟

SpringMVC中@ModelAttribute与@RequestBody的区别及说明

可以看到后端成功的注入了数据。

SpringMVC中@ModelAttribute与@RequestBody的区别及说明

至于这两个注解的选择,还是看前端会发送什么格式的数据之后来进行自由的选择吧。

来源:https://blog.csdn.net/qq_42684642/article/details/83058211

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com