远道而重任

导航

使用哪种注解处理后台Map参数类型,探究前端发送请求URL限制

如何处理接口参数是Map类型探究URL限制

法1:前端发送Get请求

需求:为了得到分页结果,我将分页时需要的参数封装到Map中进行传递

@GetMapping("/page")
public R queryPage(@RequestParam Map<String,Object> params){}
// 1.测试GET http://localhost:8080/product/categorybrandrelation/page接口
// @GetMapping("/page")
// public R queryPage(@RequestParam Map<String,Object> params)
const getCategoryBrand = () => {
    axios.get( `http://localhost:8080/product/categorybrandrelation/page`,{
              params: {
                  page: "2",
                  limit: "100"
              }
              }).then(res => {
        console.log(res.data)
    })
}

结果:结果返回200

说明:这是符合Restful规范,但是有一个缺点,发送GET请求的URL长度通常是有限制的,对于参数较少可以使用&拼接参数到URL地址后面进行拼接,传递给后端接口;如果一旦参数较多,超过URL长度8000字节,推荐使用Post请求,在post请求体中传递参数可以限制达到4GB(足以使用)

法2:前端发送post请求,参数是以json格式发送过去(推荐)

@PostMapping("/page")
public R queryPage(@RequestBody Map<String,Object> params){}
// 2.测试 http://localhost:8080/product/categorybrandrelation/page接口
let body = {
    page: "1",
    limit: "6"
};
const getCategoryBrand2 = () => {
    axios.post( `http://localhost:8080/product/categorybrandrelation/page`,body,{
    Headers: {
    	'Content-type': 'application/json'
    }
    }).then(res => {
    	console.log(res.data)
    })
}

结果:

说明:虽然不符合Restful规范,Post方式通过json以请求体的方式传递参数封装Map中,参数限制数量远大于GET方式

注意:后端除了@RequestBody处理参数,也可以使用@RequestParam处理参数

法3:前端发送post请求,参数是以表单格式发送过去

如果你硬是要发送表单形式的参数,也是可以的,我觉得json更方便

 @PostMapping("/page")
 public R queryPage(@RequestParam Map<String,Object> params)
 // 3.测试 http://localhost:8080/product/categorybrandrelation/page接口
// @PostMapping("/page")
// public R queryPage(@RequestParam Map<String,Object> params)
import qs from 'qs';

let body2 = {
    page: "1",
    limit: "6"
};
const getCategoryBrand3 = () => {
    axios.post(`http://localhost:8080/product/categorybrandrelation/page`, qs.stringify(body2), {
        headers: {
            "Content-Type": "application/x-www-form-urlencoded"
        }
    }).then(res => {
        console.log(res.data)
    })
}

结果:

说明:如果是以表单的形式传递参数,必须使用@RequestParam

posted on 2023-08-26 09:36  远道而重任  阅读(78)  评论(0编辑  收藏  举报