Spring引导REST应用程序
问题描述:
我想通过遵循教程here,使用Spring引导在Java中创建一个RESTful应用程序。我想修改它,以便我可以从URL中提取标识符并使用它来提供请求。Spring引导REST应用程序
因此http://localhost:8080/members/<memberId>
应该为我提供一个JSON对象,其中包含ID为<memberId>
的成员的信息。我不知道该怎么
- 地图所有http://localhost:8080/members/ *到一个控制器。
- 从URL中提取。
- 应该根据MVC架构提取memberId并使用它作为控制器或单独类的一部分?
我是Spring/Spring-boot/MVC的新手。开始使用是相当困惑的。所以请忍受我的新手问题。
答
正如您在下面的代码中看到的,为客户提供的服务是在一个控制器中获取一个并添加新客户。
所以,你将有2个服务:
http://localhost:8080/customer/
http://localhost:8080/customer/(编号)
@RestController("customer")
public class SampleController {
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public Customer greetings(@PathVariable("id") Long id) {
Customer customer = new Customer();
customer.setName("Eddu");
customer.setLastname("Melendez");
return customer;
}
@RequestMapping(value = "/{id}", method = RequestMethod.POST)
public void add(@RequestBody Customer customer) {
}
class Customer implements Serializable {
private String name;
private String lastname;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getLastname() {
return lastname;
}
}
}
答
地图所有http://localhost:8080/members/ *到一个控制器。
您可以在请求映射中使用占位符,以便处理多个URL。例如:
@RequestMapping("/members/{id}")
从URL
你可以有一个占位符的注入使用@PathVariable
注释与的名称相匹配的值你的控制器方法的价值提取ID占位符,在这种情况下, “ID”:
@RequestMapping("/members/{id}")
public Member getMember(@PathVariable("id") long id) {
// Look up and return the member with the matching id
}
应该提取membe的逻辑根据MVC体系结构,使用它作为控制器的一部分还是独立的类?
您应该让Spring MVC从URL中提取成员标识,如上所示。至于使用它,您可能会将URL传递给某种类型的存储库或服务类,该类提供findById
方法。