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
{
    /**
     * 使用@RequestParam獲取引數
     * 這裡RequestParam註解會將括號裡面的前端引數名稱轉化為後面的引數名稱
     * @param name String 姓名,接收前端username引數
     * @param age int 年齡,接收前端user_age引數
     * @param score double 分數,接收前端score引數
     * @return 響應json字元
     */
    @RequestMapping("/param/requestparam")
    @ResponseBody
    public Map<String, Object> requestParam(@RequestParam("username") String name, @RequestParam("user_age") int age, @RequestParam("score") double score)
    {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("name", name);
        paramMap.put("age", age);
        paramMap.put("score", score);
        return paramMap;
    }







    /**
     * 無註解獲取引數時,引數名稱和HTTP請求引數必須一致
     * @param name String 姓名
     * @param age int 年齡
     * @param score double 分數
     * @return 響應json字元-@ResponseBody註解將map轉為json
     */
    @RequestMapping("/param/noannotation")
    @ResponseBody
    public Map<String, Object> noAnnotation(String name, int age, double score) {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("name", name);
        paramMap.put("age", age);
        paramMap.put("score", score);
        return paramMap;
    }



@RequestMapping("/123") public String testweb01() { return "abc"; }


@RequestMapping("/1234") public String testweb02() { return "123abc"; } }

  

URL: http://localhost:8080/param/requestparam?username=lisi&user_age=12&score=45.6

web訪問:

無註解情況下,HTTP引數與控制器引數名稱必須一致。

若HTTP引數與控制器引數不一致時,我們就需要將前端引數與後端引數對應起來,這裡我們使用@RequestParam來確定前後端引數名稱的對映關係。

方法中,我們接收前端的username,user_age和score,然後使用@RequestParam註解將其轉化對映為name,age和age。

如果將URL中username後面值置空,頁面可以正常跳轉,測試URL

http://localhost:8080/param/requestparam?username=&user_age=12&score=45.6

若我們將user_age 或 score值置空,則頁面會報錯

與無註解時錯誤相同,這裡不做解釋了。

如果我們刪除掉URL欄裡面username引數項,URL為http://localhost:8080/param/requestparam?user_age=12&score=45.6

頁面無法正常跳轉,報錯如下