SpringMVC中的接口传参接参总结

本文详细介绍了SpringMVC中接口接收参数的多种方式,包括注解的使用,如@PathVariable、@RequestParam、@RequestBody等。推荐使用@RequestBody注解处理单个或多个参数,同时讲解了实体类传参接参的实现。还涵盖了文件上传以及不同注解的场景应用。
摘要由CSDN通过智能技术生成

1. 注解 @PathVariable

1.1. 方式一

不推荐使用,仅在单个参数的时候选择使用

@GetMapping("/getId/{id}")
@ResponseBody
public String pathVariableTest(@PathVariable Integer id) {
   
	return "id:   " + id;
}

1.2. 方式二

推荐使用,适用于单个、多个参数的情况

1.2.1. 单个参数

@GetMapping("/getId/{id}")
@ResponseBody
public String pathVariableTest(@PathVariable("id") Integer id) {
   
	return "id:   " + id;
}

1.2.2. 多个参数

@GetMapping("/getIdAny/{id}/{name}")
@ResponseBody
public String pathVariableTestAny(@PathVariable("id") Integer id, @PathVariable("name") String name) {
   
	return "id:" + id + "name:" + name;
}

1.3. 方式三

@GetMapping("/getId/{idValue}")
@ResponseBody
public String pathVariableTest(@PathVariable("idValue") Integer id) {
   
	return "id:   " + id;
}

以上三种方式的调用结果都是成功的

在这里插入图片描述

2. 注解 @RequestParam

@RequestParam:将请求参数绑定到你控制器的方法参数上,是 SpringMVC 中接收普通参数的注解

@RequestParam(value = "参数名", required = "true", defaultValue= " ")
  • valuename :参数名
  • required:是否包含该参数,默认为 true,表示该请求路径中必须包含该参数,如果不包含就报错
  • defaultValue:默认参数值,如果设置了该值,required = true 将失效,自动为 false,如果没有传该参数,就使用默认值

2.1. 方式一

不推荐使用,仅在单个参数的时候选择使用

@GetMapping("/getId")
@ResponseBody
public 
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值