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

控制器:

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对象;若为简单类型,则系统依然会将空字符串与对应的简单类型进行强转,转换失败的,则抛异常出来。

原文地址:https://www.cnblogs.com/xiaobaibailongma/p/15084822.html