foods.html 파일에 식품 리스트 UI를 구현한다.
기존 h2 태그의 hello world 테스트 문구는 Foods 로 변경하고, table 태그를 작성하여 목록을 보여준다.
상세보기 앵커태그와 수량, 유통기한 값을 'yyyy-MM-dd' 패턴으로 포맷한다.
pom.xml 에 HATEOAS 라이브러리 의존성을 추가한다.
restTemplate의 exchange메서드를 사용한다. exchange 메서드의 파라미터는 순서대로 서버 URL, HTTP 방식, 요청 객체, 응답 클래스 타입, 요청 URI변수값을 가진다.
실제 메서드는 /foods URL을 GET 방식으로 ResponseType은 Resources<FoodCommand> 인 HTTP 통신을 호출한다.
만약, 응답상태코드가 2xx 대이면 model 에 response Body에 getContent 한 내용을 foodList 라는 이름으로 추가하여 View로 전달한다.
테스트 코드는 registerFood 테스트 메서드에 이어서 확인하는 방식으로 진행한다.
alert.accept 메서드를 호출해야 alert 창을 닫고 다음 코드를 진행할 수 있다.
foods View페이지로 이동하여 해당 페이지의 table태그를 찾고 그 자식태그중에서 anchor 태그들중 가장 마지막 태그의 text값을 등록한 식품이름과 같은지 비교하여 검증한다.
등록과 목록 UI가 완료되면 상세페이지와 수정페이지를 작성하는데, 상세페이지가 곧 수정페이지로 간단하게 표현한다. View 파일은 updateFoodForm.html 로 정하고 파일을 생성한다.
상세/수정 페이지는 등록페이지와 차이가 거의 없다. form태그의 action 속성값과 method 속성값만 변경하면 된다. action 속성에는 foodCommand model값의 id를 uriVariables 에 기입하고, method 속성값은 put으로 지정한다.
나머지 코드는 등록폼페이지와 동일하다.
테스트 코드는 registerFood 테스트 메서드에 계속 이어서 기입한다.
anchorElement는 앞서 목록페이지에 첫번째 앵커태그를 가리키며, 해당 element에 click 메서드 호출하면 페이지가 이동한다. 상세페이지로 이동하면 input tag의 name 애트리뷰트의 값이 name 인 태그를 찾고, 해당 태그의 value attribute 값을 가져와서 식품의 이름과 비교한다.
즉, 저장된 food의 name이 등록폼 페이지에서 입력했던 식품명과 일치하는지 확인한다.
컨트롤러 메서드는 다음과 같다.
updateFoodForm 메서드는 uri 변수로 식품의 id를 입력받는다. 메서드 파라미터는 long 타입의 PathVariable과 Model 객체를 전달받는다.
restTemplate의 getForEntity 메서드를 호출해서 api서버의 식품 상세데이터를 호출한다. 응답상태코드가 2xx 대 이면 foodCommand 라는 키값을 가진 model 을 View 에 추가하는데 값은 응답결과의 body를 전달한다.
상세/수정페이지에서 정보를 수정하고 submit하는 테스트 메서드를 작성한다.
input name태그의 값을 clear 메서드로 삭제하고 sendKeys 메서드로 새로운 식품명을 입력한다.
quantity태그도 20으로 변경하고 form submit을 수행하면, 목록페이지로 이동해서 alert창으로 메시지를 확인하는 검증을 실행한다. 그리고 alert창을 닫는다.
컨트롤러 메서드는 다음과 같다.
processUpdateFood 메서드에 @PutMapping애너테이션이 선언되어 있고, {id} 값을 uri 변수로 매핑한다. 등록 컨트롤러 메서드와 동일하게 Validation을 수행해서 실패하면 수정폼View로 forward 시킨다.
restTemplate의 put메서드를 호출해서 request 객체 foodCommand를 전달하고 flashAttribute를 추가하여 식품목록페이지로 redirect한다.
processRegistrationFood 메서드와 거의 흡사하다.
fridge 프로젝트의 FoodController에서 findAllFoods 메서드를 수정한다.
데이터를 DB에서 가져와서 list내용이 없을경우 notFound를 응답으로 보내는 코드를 삭제한다.
목록페이지에서 등록폼으로 갈 수 있도록 앵커태그를 하나 추가하고 테스트메서드도 해당 태그를 클릭해서 등록페이지로 넘어갈 수 있도록 수정한다.
식품 삭제는 상세페이지에서 앵커태그를 사용하는 방식으로 구현한다.
/web/foods/delete/{id} URL경로로 페이지를 이동시키는 앵커태그를 submit버튼 옆에 작성한다. 삭제 테스트 메서드는 다음과 같다.
이어서 삭제기능을 구현한 컨트롤러 메서드다.
restTemplate.delete 메서드를 호출하면 HttpMethod.Delete 방식으로 해당 url을 호출한다.
alert를 이용해서 성공메시지를 전달하고 목록페이지로 redirect 한다.
이전글: 냉장고 가계부 프로젝트 12
다음글: 냉장고 가계부 프로젝트 14
<body> <h2>Foods</h2> <table> <thead> <tr> <th>식품명</th> <th>수량</th> <th>유통기한</th> </tr> </thead> <tbody> <tr th:each="food : ${foodList}"> <td><a href="/web/foods/1" th:href="@{/web/foods/{id}(id=${food.id})}" th:text="${food.name}">파스퇴르 우유 1.8L</a></td> <td th:text="${food.quantity}">1</td> <td th:text="${#dates.format(food.expiryDate, 'yyyy-MM-dd')}">2018-09-28</td> </tr> </tbody> </table> </body>
기존 h2 태그의 hello world 테스트 문구는 Foods 로 변경하고, table 태그를 작성하여 목록을 보여준다.
상세보기 앵커태그와 수량, 유통기한 값을 'yyyy-MM-dd' 패턴으로 포맷한다.
pom.xml 에 HATEOAS 라이브러리 의존성을 추가한다.
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-hateoas</artifactId> </dependency>
@GetMapping public String foods(Model model) { ResponseEntity<Resources<FoodCommand>> response = restTemplate.exchange("http://localhost:8081/foods", HttpMethod.GET, null, new ParameterizedTypeReference<Resources<FoodCommand>>() {}, Collections.emptyMap()); if(response.getStatusCode().is2xxSuccessful()) { model.addAttribute("foodList", response.getBody().getContent()); } return "food/foods"; }
restTemplate의 exchange메서드를 사용한다. exchange 메서드의 파라미터는 순서대로 서버 URL, HTTP 방식, 요청 객체, 응답 클래스 타입, 요청 URI변수값을 가진다.
실제 메서드는 /foods URL을 GET 방식으로 ResponseType은 Resources<FoodCommand> 인 HTTP 통신을 호출한다.
만약, 응답상태코드가 2xx 대이면 model 에 response Body에 getContent 한 내용을 foodList 라는 이름으로 추가하여 View로 전달한다.
테스트 코드는 registerFood 테스트 메서드에 이어서 확인하는 방식으로 진행한다.
alert.accept(); List<WebElement> anchorElements = browser.findElementByTagName("table").findElements(By.tagName("a")); WebElement anchorElement = anchorElements.get(anchorElements.size() - 1); assertThat(anchorElement.getText()).isEqualTo(name);
alert.accept 메서드를 호출해야 alert 창을 닫고 다음 코드를 진행할 수 있다.
foods View페이지로 이동하여 해당 페이지의 table태그를 찾고 그 자식태그중에서 anchor 태그들중 가장 마지막 태그의 text값을 등록한 식품이름과 같은지 비교하여 검증한다.
등록과 목록 UI가 완료되면 상세페이지와 수정페이지를 작성하는데, 상세페이지가 곧 수정페이지로 간단하게 표현한다. View 파일은 updateFoodForm.html 로 정하고 파일을 생성한다.
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>Food</title> </head> <body> <h2>식품 상세</h2> <form th:action="@{/web/foods/{id}(id=${foodCommand.id})}" th:object="${foodCommand}" th:method="put"> <div th:if="${#fields.hasErrors('*')}"> <ul> <li th:each="err : ${#fields.errors('*')}" th:text="${err}">Input is incorrect</li> </ul> </div> <label for="name">이름: <input type="text" th:field="*{name}" /> </label><br/> <label for="quantity">수량: <input type="text" th:field="*{quantity}" /> </label><br/> <label for="expiryDate">유통기한: <input type="date" th:field="*{expiryDate}" /> </label><br/> <button type="submit">저장</button> </form> </body> </html>
상세/수정 페이지는 등록페이지와 차이가 거의 없다. form태그의 action 속성값과 method 속성값만 변경하면 된다. action 속성에는 foodCommand model값의 id를 uriVariables 에 기입하고, method 속성값은 put으로 지정한다.
나머지 코드는 등록폼페이지와 동일하다.
테스트 코드는 registerFood 테스트 메서드에 계속 이어서 기입한다.
anchorElement.click(); assertThat(browser.findElement(By.name("name")).getAttribute("value")).isEqualTo(name);
anchorElement는 앞서 목록페이지에 첫번째 앵커태그를 가리키며, 해당 element에 click 메서드 호출하면 페이지가 이동한다. 상세페이지로 이동하면 input tag의 name 애트리뷰트의 값이 name 인 태그를 찾고, 해당 태그의 value attribute 값을 가져와서 식품의 이름과 비교한다.
즉, 저장된 food의 name이 등록폼 페이지에서 입력했던 식품명과 일치하는지 확인한다.
컨트롤러 메서드는 다음과 같다.
@GetMapping("/{id}") public String updateFoodForm(@PathVariable long id, Model model) { ResponseEntity<FoodCommand> response = restTemplate.getForEntity("http://localhost:8081/foods/{id}", FoodCommand.class, id); if(response.getStatusCode().is2xxSuccessful()) { model.addAttribute("foodCommand", response.getBody()); } return "food/updateFoodForm"; }
updateFoodForm 메서드는 uri 변수로 식품의 id를 입력받는다. 메서드 파라미터는 long 타입의 PathVariable과 Model 객체를 전달받는다.
restTemplate의 getForEntity 메서드를 호출해서 api서버의 식품 상세데이터를 호출한다. 응답상태코드가 2xx 대 이면 foodCommand 라는 키값을 가진 model 을 View 에 추가하는데 값은 응답결과의 body를 전달한다.
상세/수정페이지에서 정보를 수정하고 submit하는 테스트 메서드를 작성한다.
nameElement = browser.findElement(By.name("name")); nameElement.clear(); nameElement.sendKeys("코카콜라 500mL"); quantityElement = browser.findElement(By.name("quantity")); quantityElement.clear(); quantityElement.sendKeys("20"); browser.findElementByTagName("form").submit(); wait.until(ExpectedConditions.alertIsPresent()); alert = browser.switchTo().alert(); assertThat(alert.getText()).isEqualTo("식품을 저장했습니다."); alert.accept();
input name태그의 값을 clear 메서드로 삭제하고 sendKeys 메서드로 새로운 식품명을 입력한다.
quantity태그도 20으로 변경하고 form submit을 수행하면, 목록페이지로 이동해서 alert창으로 메시지를 확인하는 검증을 실행한다. 그리고 alert창을 닫는다.
컨트롤러 메서드는 다음과 같다.
@PutMapping("/{id}") public String processUpdateFood(@PathVariable long id, @Valid FoodCommand foodCommand, Errors errors, RedirectAttributes ra) { if(errors.hasErrors()) { return "food/updateFoodForm"; } restTemplate.put("http://localhost:8081/foods/{id}", foodCommand, id); ra.addFlashAttribute("registerFoodMessage", "식품을 저장했습니다."); return "redirect:/web/foods"; }
processUpdateFood 메서드에 @PutMapping애너테이션이 선언되어 있고, {id} 값을 uri 변수로 매핑한다. 등록 컨트롤러 메서드와 동일하게 Validation을 수행해서 실패하면 수정폼View로 forward 시킨다.
restTemplate의 put메서드를 호출해서 request 객체 foodCommand를 전달하고 flashAttribute를 추가하여 식품목록페이지로 redirect한다.
processRegistrationFood 메서드와 거의 흡사하다.
fridge 프로젝트의 FoodController에서 findAllFoods 메서드를 수정한다.
List<Food> foods = jpaFoodRepository.findAll(); if(foods.isEmpty()) { return ResponseEntity.notFound().build(); }
데이터를 DB에서 가져와서 list내용이 없을경우 notFound를 응답으로 보내는 코드를 삭제한다.
목록페이지에서 등록폼으로 갈 수 있도록 앵커태그를 하나 추가하고 테스트메서드도 해당 태그를 클릭해서 등록페이지로 넘어갈 수 있도록 수정한다.
foods.html
... <h2>Foods</h2> <a href="/web/foods/add" th:href="@{/web/foods/add}" th:text="식품등록" id="btnRegistrationFood">등록</a> <table> ...
WebFoodControllerTests.java
@Test public void registerFood() { String name = "파스퇴르 우유 1.8L"; int quantity = 1; browser.get(BASE_URL + "/web/foods"); browser.findElement(By.id("btnRegistrationFood")).click(); ...
식품 삭제는 상세페이지에서 앵커태그를 사용하는 방식으로 구현한다.
updateFoodForm.html
... <button type="submit">저장</button> <a href="/web/foods/delete/1" th:href="@{/web/foods/delete/{id}(id=*{id})}">삭제</a> </form> ...
/web/foods/delete/{id} URL경로로 페이지를 이동시키는 앵커태그를 submit버튼 옆에 작성한다. 삭제 테스트 메서드는 다음과 같다.
... browser.findElement(By.linkText("코카콜라 500mL")).click(); browser.findElement(By.linkText("삭제")).click(); wait.until(ExpectedConditions.alertIsPresent()); alert = browser.switchTo().alert(); assertThat(alert.getText()).isEqualTo("식품을 삭제했습니다."); alert.accept();
이어서 삭제기능을 구현한 컨트롤러 메서드다.
@GetMapping("/delete/{id}") public String deleteFood(@PathVariable long id, RedirectAttributes ra) { restTemplate.delete("http://localhost:8081/foods/{id}", id); ra.addFlashAttribute("registerFoodMessage", "식품을 삭제했습니다."); return "redirect:/web/foods"; }
restTemplate.delete 메서드를 호출하면 HttpMethod.Delete 방식으로 해당 url을 호출한다.
alert를 이용해서 성공메시지를 전달하고 목록페이지로 redirect 한다.
이전글: 냉장고 가계부 프로젝트 12
다음글: 냉장고 가계부 프로젝트 14