springMVC Controller层接收 JSON参数遇到得问题

1 篇文章 0 订阅
1 篇文章 0 订阅

@RequestBody

使用@RequestBody传参,@RequestBody可以传json

     @Autowired
    private IUserService userService;
    //在需要使用日志的地方加上这句代码即可
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    //insertUser方法
    @PostMapping("/insert")
    public String insertUser(
        @RequestBody User user
    ) throws Exception{
        logger.info("日志 getEmail = {}",user.getMobile());
        userService.insertUser(user);
        return "eeee";
    }
import lombok.Data;

@Data
public class User {

    private int id;
    private String email;
    private String mobile;
    private String username;
    private String role;
}

在postman里填入得值:
在这里插入图片描述

使用此方法遇到的问题:

在spring mvc框架中需要在pom文件中加上下面的内容来引入jackson,否则接受识别不了json。

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.9</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.9.9</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.9.9</version>
        </dependency>

如果使用springboot,它已经自动给你引入看jackson,不需要自己去引入。springMVC就是麻烦!!!!

@RequestParam

@RequestParam用来处理 Content-Type 为 application/x-www-form-urlencoded 编码的内容,Content-Type默认为该属性,也可以接收​​​​​​​application/json。

语法:@RequestParam(value=”参数名”,required=”true/false”,defaultValue=””)
 
value:参数名
 
required:是否包含该参数,默认为true,表示该请求路径中必须包含该参数,如果不包含就报错。
 
defaultValue:默认参数值,如果设置了该值,required=true将失效,自动为false,如果没有传该参数,就使用默认值
@PostMapping("/insert")
    public String insertUser(
           @RequestParam(value = "id") int id,
           @RequestParam(value = "email") String email,
           @RequestParam(value = "username") String username,
           @RequestParam(value = "role") String role,
           @RequestParam(value = "mobile") String mobile
    ) throws Exception{
        User user =new User();
        user.setId(id);
        user.setEmail(email);
        user.setUsername(username);
        user.setRole(role);
        user.setMobile(mobile);
        String getemail = user.getEmail();
        logger.info("日志 getEmail = {}",user.getMobile());
        userService.insertUser(user);
        return "eee";
    }

在postman里填入得值:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值