2017-11-30 3 views
1

に、私は以下のURIで、次のオプション@Pathvariable RESTコントローラバネ4

http://localhost:8080/customers/{customer_id} 
  1. が渡さCUSTOMER_IDの詳細をフェッチん休息サービス(HTTPのGetエンドポイント)、書いていますuri
  2. customer_idが渡されない場合(http://localhost:8080/customers)、すべての顧客の詳細を取得します。

コード:

@RequestMapping(method = RequestMethod.GET, value = "customers/{customer_id}") 
public List<Customer> getCustomers(
@PathVariable(name = "customer_id", required = false) final String customerId) { 
LOGGER.debug("customer_id {} received for getCustomers request", customerId); 

} 

しかしながら、上記のコードと、第2のシナリオ制御用)(getCustomersに流れています。

注:私は非常にこの上の任意の助けに感謝Java8と春-ウェブ4.3.10バージョン

を使用しています。

あなたは、個々のリクエスト処理するために、ここでは2つのエンドポイントを作成する必要があります

答えて

1

任意@PathVariableは、両方をマップする場合にのみ使用します。GET /customers/{customer_id}およびGET customersを単一のJavaメソッドに変換します。

customer_idを送信しないと、GET /customers/{customer_id}に送信されるリクエストを送信できません。

だからあなたの場合には、それは次のようになります。

@RequestMapping(method = RequestMethod.GET, value = {"/customers", "customers/{customer_id}"}) 
public List<Customer> getCustomers(@PathVariable(name = "customer_id", required = false) final String customerId) { 
    LOGGER.debug("customer_id {} received for getCustomers request", customerId); 
} 

パブリック抽象ブールパス変数が必要とされているかどうか

を必要としていました。

デフォルトではtrueに設定されているため、着信要求にパス変数がない場合は例外がスローされます。この場合、nullまたはJava 8 java.util.Optionalを使用する場合は、これをfalseに切り替えます。例えばさまざまな要求に対応するModelAttributeメソッドを使用します。

あなたはjava8

+0

value = {"/ customers"、 "customers/{customer_id}"})です。 –

+0

ありがとう@ByeBye ..魅力的な作品。 – technoJ

+0

@technoJは答えを受け入れることを忘れないでください。 –

0

@GetMapping("/customers") 
public List<Customer> getCustomers() { 
LOGGER.debug("Fetching all customer"); 
} 

@GetMapping("/customers/{id}") 
public List<Customer> getCustomers(@PathVariable("id") String id) { 
LOGGER.debug("Fetching customer by Id {} ",id); 
} 

@GetMapping@RequestMapping(method = RequestMethod.GET)@GetMapping("/customers/{id}")と同等であるが、このようなものだ@RequestMapping(method = RequestMethod.GET, value = "customers/{id}")

より良いアプローチと同等です:

@RestController 
@RequestMapping("/customers") 
public class CustomerController { 

    @GetMapping 
    public List<Customer> getAllCustomers() { 
    LOGGER.debug("Fetching all customer"); 
    } 

    @GetMapping("/{id}") 
    public Customer getCustomerById(@PathVariable("id") String id) { 
    LOGGER.debug("Fetching customer by Id {} ",id); 
    } 
+0

私が最初にこれをしなかったからnullまたはOptionalを使用することができますが、両方のJavaメソッドは、同じ操作を行うことを意図しています。私は、コードの重複を避ける単一のJavaメソッドを探していました。 @ByeByeが提案したようなものを探していたのは、 – technoJ

関連する問題