2017-11-30 16 views
1

나는 URI 아래의이 (가) 전달 된 CUSTOMER_ID에 대한 세부 정보를 가져 선택적 @PathVariable은 REST 컨트롤러 봄에 4

http://localhost:8080/customers/{customer_id} 
  1. 다음 않습니다에 나머지 서비스 (HTTP 가져 오기 엔드 포인트), 쓰고 있어요 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); 

} 

그러나, 두 번째 시나리오 컨트롤 상기 코드는 getCustomers 흐와().

참고 : 내가보기 엔이에 어떤 도움을 주셔서 감사합니다 Java8 봄 - 웹 4.3.10 버전

을 사용하고 있습니다.

당신은 개별 요청을 처리하기 위해 여기에 두 개의 엔드 포인트를 작성해야합니다

답변

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이며 들어오는 요청에 경로 변수가없는 경우 예외가 throw됩니다. 이 경우 널 또는 Java 8 java.util.Optional을 선호하면이 값을 false로 전환하십시오. 예 : 다른 요청을 처리하는 ModelAttribute 메서드에서.

당신은 java8

+0

값 = { "/ 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을 사용할 수 있지만, 모두 자바 방법은 동일한 작업을 수행하기위한 것입니다. 나는 코드 중복을 피하는 하나의 자바 메소드를 찾고 있었다. @ByeBye가 – technoJ