2015-01-21 91 views
0

我想通過遵循教程here,使用Spring引導在Java中創建一個RESTful應用程序。我想修改它,以便我可以從URL中提取標識符並使​​用它來提供請求。Spring引導REST應用程序

因此http://localhost:8080/members/<memberId>應該爲我提供一個JSON對象,其中包含ID爲<memberId>的成員的信息。我不知道該怎麼

  1. 地圖所有http://localhost:8080/members/ *到一個控制器。
  2. 從URL中提取。
  3. 應該根據MVC架構提取memberId並使用它作爲控制器或單獨類的一部分?

我是Spring/Spring-boot/MVC的新手。開始使用是相當困惑的。所以請忍受我的新手問題。

回答

0

正如您在下面的代碼中看到的,爲客戶提供的服務是在一個控制器中獲取一個並添加新客戶。

所以,你將有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; 
    } 
} 

}

2

地圖所有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方法。

相關問題