原文地址:https://dzone.com/articles/spring-boot-passing-parameters
译者:高行行
Spring Boot 通过 Java 注解使传递参数变得容易。
请求 URL 时传递参数是 Spring Boot 的最基本功能之一。本文介绍了在请求中传递参数的方法。有两种方法可以传递参数。传递参数的常用方法是在 URL 调用中显式指定参数。格式如下:
https://www.youtube.com/watch?v=tuNhqqxgxXQ&t=153s
在上面的 URL 中,有两个参数 v 和 t。要传递参数,请输入”?”。然后,添加参数名称,后跟”=”和参数值。它看起来像这样的”?v=value”。要传递另一个参数,请使用”&”,后跟第二个参数作为第一个参数。
传递参数的第二种方法是路径变量。例如:
http://www.twitter.com/hashimati
此 URL 中的单词“ hashimati”是一个变量。
Spring Boot 通过 Java 注释使传递参数变得容易。让我们看看它在 Spring Boot 中是如何工作的。
创建一个项目
使用Spring Initializer生成 Gradle 或 Maven 项目。你唯一需要的依赖是Web。
路径变量
在 path 变量中,我们在 Web 服务的路径内传递参数。下面的代码段演示了一种编写采用 path 变量的 Web 服务的方法:
@GetMapping("/hello0/{name}")
public String hello0(@PathVariable("name") String name)
{
return "Hello " + name;
}
- 该变量嵌入在服务路径中的大括号之间。
name
- 该
name
参数都被注解@PathVariable
。我们通过name
在@PathParameter
表明,在方法签名店 name 参数的{name}
值。
Request Parameter
在 Spring Boot 中,有两种方法可以在 URL 请求中传递参数:
- 使用
@RequestParam
:
@RequestParam
可用于注解方法签名中的参数。如以下代码片段所示:
@GetMapping("/hello1")
public String hello1(@RequestParam(name="name", required = false, defaultValue = "Ahmed") String name){
return "Hello " + name;
}
@RequestParam
具有以下参数:
name
:请求参数的名称defaultValue
:如果未在请求中传递参数,则为默认值。required
:如果为 true,则该参数为必填。否则,不是。
- 将参数封装在对象中
使用对象是一种将参数封装在一个对象中的好方法。让我们看一下下面的代码片段。首先,我们将创建一个名称为的类 Params
:
public class Parms {
private String a, b;
public void setA(String a) {
this.a = a;
}
public void setB(String b) {
this.b = b;
}
public String getA() {
return a;
}
public String getB() {
return b;
}
}
在Param
类中应实现 getter 和 setter 方法 。然后,我们将Param
在 Web 服务方法签名中使用
@GetMapping("/hello2")
public String hello2(Parms parameters){
//implement the setter and getter of the Params class.
return "Hello " + parameters.a + " " + parameters.b;
}
最后,该 Web 服务获取到两个参数,分别是a
和b
。
希望你喜欢!