Spring 启动 REST 应用程序

Spring boot REST application

我正尝试按照教程 here 使用 Spring 引导在 Java 中创建一个 RESTful 应用程序。我想修改它,以便我可以从 URL 中提取标识符并使​​用它来处理请求。

所以 http://localhost:8080/members/<memberId> 应该为我提供一个 JSON 对象,其中包含有关 ID 为 <memberId> 的成员的信息。我不知道如何

  1. 将所有 http://localhost:8080/members/* 映射到一个控制器。
  2. 从 URL 中提取。
  3. 根据 MVC 架构,提取 memberId 并使用它的逻辑应该是控制器的一部分还是单独的 class?

我是 Spring/Spring-boot/MVC 的新手。开始时非常混乱。所以请多多包涵我的菜鸟问题

正如您在下面的代码中所看到的,客户服务在一个控制器中以获取一个并添加新客户。

因此,您将拥有 2 项服务:

http://localhost:8080/customer/

http://localhost:8080/customer/{id}

@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;
    }
}

}

Map all http://localhost:8080/members/* to a single controller.

您可以在请求映射中使用占位符,以便处理多个 URL。例如:

@RequestMapping("/members/{id}")

Extract the id from the URL

您可以使用 @PathVariable 注释将占位符的值注入到您的控制器方法中,该注释的值与占位符的名称相匹配,在本例中为 "id":

@RequestMapping("/members/{id}")
public Member getMember(@PathVariable("id") long id) {
    // Look up and return the member with the matching id       
}

Should the logic of extracting the memberId and using it be part of the controller or a separate class, as per the MVC architecture?

您应该让 Spring MVC 从 URL 中提取成员 ID,如上所示。至于使用它,您可能会将 URL 传递给某种提供 findById 方法的存储库或服务 class。