1. 程式人生 > 其它 >測試開發進階——spring boot——MVC——get訪問——使用@RequestParam獲取引數(前端可傳可不傳參,以及使用預設值)

測試開發進階——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物件;若為簡單型別,則系統依然會將空字串與對應的簡單型別進行強轉,轉換失敗的,則拋異常出來。