使用路径变量增强 Hello World 服务

@PathVariable 注解用于从 URI 中提取值。它在包含某些值的 RESTful Web 服务中非常适用。Spring MVC 允许我们在同一个方法中使用多个 @PathVariable 注解。路径变量是创建 REST 资源的关键部分。

我们将创建另一个带有路径参数的 hello-world-bean 请求。

步骤 1: 打开 HelloWorldController.java 文件并添加另一个 helloWorldBean() 服务。

无法在文本框中显示代码,可以在您的 IDE 中打开 HelloWorldController.java 文件,并添加以下代码:

package cn.javatiku.server.main;  
import org.springframework.web.bind.annotation.GetMapping;  
import org.springframework.web.bind.annotation.PathVariable;  
import org.springframework.web.bind.annotation.RestController;  
import org.springframework.context.annotation.Configuration;  
@Configuration  
//Controller  
@RestController  
public class HelloWorldController   
{  
//using get method and hello-world URI  
@GetMapping(path="/hello-world")  
public String helloWorld()  
{  
return "Hello World";  
}  
@GetMapping(path="/hello-world-bean")  
//method- which returns "Hello World"  
public HelloWorldBean helloWorldBean()  
{  
return new HelloWorldBean("Hello World");//constructor of HelloWorldBean  
}  
//passing a path variable  
@GetMapping(path="/hello-world/path-variable/{name}")  
public HelloWorldBean helloWorldPathVariable(@PathVariable String name)  
{  
return new HelloWorldBean(String.format("Hello World, %s", name)); //%s replace the name  
}  
}  

无论我们将什么值传递给路径变量,控制器都会捕获该值并返回给响应。

步骤 2: 在浏览器中键入 URL http://localhost:8080/hello-world/path-variable/javatiku

步骤 3: 运行 HelloWorldController.java 文件。在浏览器上,我们会得到以下响应:

restful-web-services-path-variable.png

让我们再次更改路径变量:http://localhost:8080/hello-world/path-variable/Anubhav

restful-web-services-path-variable2.png

我们可以看到我们在路径变量中输入的任何内容都会被返回到响应中。

创建用户 Bean 和用户服务

在本节中,我们将创建真实的资源用户和帖子。我们将使用静态数组列表来表示数据。

步骤 1: 创建一个名为 cn.javatiku.server.main.user 的新包。

步骤 2: 创建一个用于存储用户详细信息的 Bean 类(User)。

在包 user 上右键单击 -> 新建 -> 类 -> 输入名称 -> 完成。在此,我们提供了类名 User

步骤 3: 定义三个私有变量 id、namedob

步骤 4: 生成 GettersSetters

在文件上右键单击 -> 源码 -> 生成 Getter 和 Setter... -> 选择全部 -> 生成。

步骤 5: 生成 toString

在文件上右键单击 -> 源码 -> 生成 toString... -> 选择全部 -> 生成。

步骤 6: 生成 Constructors

在文件上右键单击 -> 源码 -> 使用字段生成构造函数... -> 生成。

package cn.javatiku.server.main.user;  
import java.util.Date;  
public class User   
{  
public User(Integer id, String name, Date dob)   
{  
super();  
this.id = id;  
this.name = name;  
this.dob = dob;  
}  
private Integer id;  
private String name;  
private Date dob;  
public Integer getId()   
{  
return id;  
}  
public void setId(Integer id)   
{  
this.id = id;  
}  
public String getName()   
{  
return name;  
}  
public void setName(String name)   
{  
this.name = name;  
}  
public Date getDob()   
{  
return dob;  
}  
public void setDob(Date dob)   
{  
this.dob = dob;  
}  
@Override  
public String toString()   
{  
//return "User [id=" + id + ", name=" + name + ", dob=" + dob + "]";  
return String.format("User [id=%s, name=%s, dob=%s]", id, name, dob);  
}  
}  

在进行下一步之前,首先将 HelloWorldBean.javaHelloWorldController.java 移动到包 cn.javatiku.server.main.helloworld 中。

步骤 7: 在包 cn.javatiku.server.main.user 中创建一个名为 UserDaoService 的类。

package cn.javatiku.server.main.user;  
import java.util.ArrayList;  
import java.util.Date;  
import java.util.List;  
import org.springframework.stereotype.Component;  
@Component  
public class UserDaoService   
{  
public static int usersCount=5;  
//creating an instance of ArrayList  
private static List<User> users=new ArrayList<>();  
//static block   
static  
{  
//adding users to the list  
users.add(new User(1, "John", new Date()));  
users.add(new User(2, "Robert", new Date()));  
users.add(new User(3, "Adam", new Date()));  
users.add(new User(4, "Andrew", new Date()));  
users.add(new User(5, "Jack", new Date()));  
}  
//method that retrieve all users from the list  
public List<User> findAll()  
{  
return users;  
}  
//method that add the user in the list   
public User save(User user)  
{  
if(user.getId()==null)  
{  
//increments the user id  
user.setId(++usersCount);  
}  
users.add(user);  
return user;  
}  
//method that find a particular user from the list  
public User findOne(int id)  
{  
for(User user:users)  
{  
if(user.getId()==id)  
return user;  
}  
return null;  
}  
}  

为用户资源实现 Get 方法

步骤 8: 现在创建一个名为 UserResource 的用户控制器类。

package cn.javatiku.server.main.user;  
import java.util.List;  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.web.bind.annotation.GetMapping;  
import org.springframework.web.bind.annotation.RestController;  
@RestController  
public class UserResource   
{  
@Autowired  
private UserDaoService service;  
@GetMapping("/users")  
public List<User> retriveAllUsers()  
{  
return service.findAll();  
}  
}  

步骤 9: 运行应用程序,并在浏览器的地址栏中键入 localhost:8080/users。它将以 JSON 格式返回用户列表。

如果日期以默认的时间戳格式显示为:

"dob": "1500370250075"

我们需要进行设置以获取正确的日期格式。

打开 application.properties 文件。删除调试配置,并添加以下配置:

spring.jackson.serialization.write-dates-as-timestamps=false  

上述语句告诉 Jackson 框架在序列化时不要将日期视为时间戳。

步骤 10: 如果我们想在浏览器上显示特定用户的详细信息,请添加映射 "/users/{id}" 并在 UserResource 中创建一个 retrieveUser() 方法。

jpackage cn.javatiku.server.main.user;  
import java.util.List;  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.web.bind.annotation.GetMapping;  
import org.springframework.web.bind.annotation.PathVariable;  
import org.springframework.web.bind.annotation.RestController;  
@RestController  
public class UserResource   
{  
@Autowired  
private UserDaoService service;  
@GetMapping("/users")  
public List<User> retriveAllUsers()  
{  
return service.findAll();  
}  
//retrieves a specific user detail  
@GetMapping("/users/{id}")  
public User retriveUser(@PathVariable int id)  
{  
return service.findOne(id);  
}  
}  

步骤 11: 运行应用程序,并在浏览器中输入 localhost:8080/users/{id}。它将返回特定用户 id 的详细信息。

在下面的图片中,我们获取了具有 id 4 的用户的详细信息。

restful-web-services-path-variable4.png

标签: spring, Spring教程, Spring语言学习, Spring框架, Spring框架教程, Spring框架高级教程, spring boot, spring boot入门教程, spring boot学习教程, spring boot下载, spring boot框架入门, spring boot面试题, spring boot笔试题, spring boot学习指南, spring boot技术