测试开发进阶——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

页面无法正常跳转,报错如下

 

posted @ 2021-07-31 16:40  小白龙白龙马  阅读(84)  评论(0编辑  收藏  举报