spring mvc中post、get方法获取参数的几种方式

get与post两种方式的区别:对于本次主题而言,最显著的区别就是get请求方式参数是在url后,而post请求方式的参数是在request body中。因此两者获取参数的方式也大不一样

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class User implements Serializable {
    private static final long serialVersionUID = 1L;
    @JsonProperty(value = "id")
    private Integer id;
    @JsonProperty(value = "name")
    private String name;
    @JsonProperty(value = "age")
    private Integer age;
    @JsonProperty(value = "hobby")
    private List<String> hobby;
}

一、Get方式参数的获取

-

1、直接在方法体中指定参数

@GetMapping("/get")
    public User getUserById(Integer id) {
        if (id.intValue() == 0) {
            return null;
        }
        return list.get(id);
    }

访问 http://ip:port/xx/get?id=1

2、使用requestParam

@GetMapping("/get")
    public User getUserById(@RequestParam(name = "id", required = true) Integer id) {
        if (id.intValue() == 0) {
            return null;
        }
        return list.get(id);
    }

其中RequestParam中name表示url中请求的字段名,当required为true时,表示该参数必填;defaultValue表示当该参数没有传递数据时给出的默认值,如defaultvalue=”0”

访问方式同上

3、使用PathVariable

@GetMapping("/get/{id}")
    public User getUserByPathValue(@PathVariable(name = "id", required = true) Integer id) {
        return list.get(id);
    }

该方式用来获取路径中的参数。@PathVariable中的字段含义同RequestParam
访问http:///ip:port/xx/get/1 ——->对应于get/{id}

4、使用HttpServletRequest

@GetMapping("/get")
    public User getUserById(HttpServletRequest request) {
        Integer id = Integer.parseInt(request.getParameter("id"));
        if (id.intValue() == 0) {
            return null;
        }
        return list.get(id);
    }

访问 http://ip:port/xx/get?id=1

二、POST方式参数的获取

一般而言,post形式的参数被放在请求体中以application/json的形式被后端获取

1、获取一个对象

content-type:application/json

    @PostMapping("/save")
    public User saveUser(@RequestBody User user) {
        list.add(user);
        return user;
    }

这里写图片描述
会把这些字段组装到对象中

2、使用Map

map中存放的键值对就对应于json中的键值对 content-type:application/json

   @PostMapping("/save")
     public User saveUser(@RequestBody Map<String, Object> map) {
     Integer id = (Integer) map.get("id");
     String name = (String) map.get("name");
     Integer age = (Integer) map.get("age");
     List<String> hobby=(List<String>) map.get("hobby");
     User user = new User(id, name, age, hobby);
     list.add(user);
     return user;
     }

这里写图片描述

3、使用HttpServletRequest

将content-type改为x-www-form-urlencoded

 @PostMapping("/save")
     public User save(HttpServletRequest request) {
     Integer id = Integer.parseInt(request.getParameter("id"));
     String name = request.getParameter("name");
     Integer age = Integer.parseInt(request.getParameter("age"));
     String parameter = request.getParameter("hobby");
     User user = new User(id, name, age, null);
     list.add(user);
     return user;
     }

这里写图片描述

    4、通过HTTP协议将参数转换为JSONObject

    content-type:application/json

    @PostMapping("/save")
        public User save(HttpServletRequest request) throws IOException, JSONException {
    
            JSONObject jsonObject = handlerData(request);
            Integer id = jsonObject.getInteger("id");
            String name = jsonObject.getString("name");
            Integer age = jsonObject.getInteger("age");
            List<String> hobby = jsonObject.getObject("hobby", List.class);
            User user = new User(id, name, age, hobby);
            list.add(user);
            return user;
        }
        //这里使用的是alibaba的json工具类
        public static JSONObject handlerData(HttpServletRequest request) throws IOException, JSONException {
            StringBuffer sb = new StringBuffer();
            InputStream is = request.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is, "utf-8"));
            String s = "";
            while ((s = br.readLine()) != null) {
                sb.append(s);
            }
            if (sb.toString().length() <= 0) {
                return null;
            } else {
                return JSONObject.parseObject(sb.toString());
            }
        }
    

    本来使用的是org.json包下的JSONObject,无奈启动就报 org.json.JSONException,后改为使用alibaba的fastjson

    注意:使用缓冲输入流读取的是这里的json,因此是一行一行读取的:

    这里写图片描述!
    读取的时候 报出异常:not close json text,token:: 将json改为如下所示
    这里写图片描述

    • 1
      点赞
    • 1
      收藏
      觉得还不错? 一键收藏
    • 0
      评论

    “相关推荐”对你有帮助么?

    • 非常没帮助
    • 没帮助
    • 一般
    • 有帮助
    • 非常有帮助
    提交
    评论
    添加红包

    请填写红包祝福语或标题

    红包个数最小为10个

    红包金额最低5元

    当前余额3.43前往充值 >
    需支付:10.00
    成就一亿技术人!
    领取后你会自动成为博主和红包主的粉丝 规则
    hope_wisdom
    发出的红包
    实付
    使用余额支付
    点击重新获取
    扫码支付
    钱包余额 0

    抵扣说明:

    1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
    2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

    余额充值