测试开发进阶——spring boot——MVC——get访问——使用@RequestParam获取参数(前端可传可不传参,以及使用默认值)

控制器:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package com.awaimai.web;
 
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
 
import java.util.HashMap;
import java.util.Map;
 
@RestController
public class kzq
{
 
    @RequestMapping("/param/requestparam")
    @ResponseBody
    public Map<String, Object> requestParam(
            @RequestParam("username") String name,
            @RequestParam(value = "user_age", required = false,defaultValue = "555") Integer age,
            @RequestParam(value = "score", required = false) Double score)
    {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("name", name);
        paramMap.put("age", age);
        paramMap.put("score", score);
        return paramMap;
    }
 
 
}

  

 

web访问:

 

 

 

 

 

 

 

 

 

 

PS:

 

前端可传可不传的参数时,怎么办?

 

@RequestParam注解给了一个required属性,标注该参数项是否必须有,其默认值为true,即必须传值;

 

若该值可能为空,则将required置为false。

 

注意,此时,@RequestParam后面的数据类型必须为包装类型,不可以是简单类型,若为简单类型,依然会报错。

 

包装类型时,可以接收null对象;若为简单类型,则系统依然会将空字符串与对应的简单类型进行强转,转换失败的,则抛异常出来。

posted @   小白龙白龙马  阅读(395)  评论(0编辑  收藏  举报
(评论功能已被禁用)
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端
点击右上角即可分享
微信分享提示