Post请求,参数跟在url后面的问题

一.问题描述

我们知道一般post请求的请求参数是不会跟在url后面的,get请求才会跟在后面,所以大家才说post请求比get请求安全嘛。但是今天写代码的时候,明明我发送的是post请求,参数还是跟在了url后面。

二.问题复现

package com.itheima.boot.Controller;

import org.springframework.web.bind.annotation.*;

@RestController
public class PostTestController {
    @PostMapping("/postTest")
    public String postTest(String name){
        System.out.println(name);
        return name;
    }

}

结果在用swagger进行测试的时候:

 三.问题解决

1.普通单个参数

只写个@PostMapping是不够的,还得在参数面前加上一个@RequestBody注解

@PostMapping("/postTest")
    public String postTest(@RequestBody String name){
        System.out.println(name);
        return name;
    }

2.普通多个参数

错误方式

首先我们说一种错误的方式,给两个参数都加上这个注解的时候会报错:Resolved [org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public java.lang.String com.itheima.boot.Controller.PostTestController.postTest1(java.lang.String,java.lang.String)]

//错误使用
@PostMapping("/postTest")
public String postTest(@RequestBody String name,@RequestBody String gender){
    System.out.println(name+"    "+gender);
    return name+"    "+gender;
}

swagger显示错误:

第一种解决方式(不建议用)

@PostMapping("/postTest3")
    public String postTest3(@RequestBody String name,String gender){
        System.out.println(name+"    "+gender);
        return name+"    "+gender;
    }

第二种方式

我们把请求的参数封装成一个对象就可以了。这样一个注解@RequestBody就能对两个参数起作用

@PostMapping("/postTest4")
    public String postTest4(@RequestBody User user){
        System.out.println(user.getAge()+"  "+user.getUsername());
        return user.getAge()+"  "+user.getUsername();
    }

 四.思考原因

其实我们做的事情就是加了个@RequestBody注解,并且,通过上面的例子我们可以得知,这个注解在一个方法里面只能使用一次。那这个注解有啥特殊的呢?

@RequestBody接收的参数是来自请求体。该注解常用来处理Content-Type:不是application/x-www-form-urlencoded编码的内容,例如application/json, application/xml等。

而@RequestParam注解接受的参数是来自请求头。用来处理Content-Type:为:application/x-www-form-urlencoded编码的内容

经验分享 程序员 微信小程序 职场和发展