기본 콘텐츠로 건너뛰기

냉장고 가계부 프로젝트 11

식품을 등록하는 폼 UI를 작성한다. 먼저, 다음과 같이 테스트 코드를 작성했다.
    @Test
    public void registerFood() {
        String name = "파스퇴르 우유 1.8L";
        int quantity = 1;
        String expiryDate = "2018. 09. 28";
        
        browser.get(BASE_URL + "/web/foods/add");
        WebElement nameElement = browser.findElement(By.name("name"));
        WebElement quantityElement = browser.findElement(By.name("quantity"));
        WebElement expiryDateElement = browser.findElement(By.name("expiryDate"));
        nameElement.sendKeys(name);
        quantityElement.sendKeys(Integer.toString(quantity));
        expiryDateElement.sendKeys(expiryDate);
        browser.findElementByTagName("form").submit();
        
        WebDriverWait wait = new WebDriverWait(browser, 10);
        wait.until(ExpectedConditions.alertIsPresent());
        Alert alert = browser.switchTo().alert();
        assertThat(alert.getText()).isEqualTo("식품을 저장했습니다.");
    }

registerFood 메서드는 다음과 같은 테스트들을 순서대로 실행한다.

  1. 식품을 등록하는 폼(/web/foods/add)을 브라우져로 연다.
  2. 식품명, 수량, 유통기한 input 태그(findElement)에 값을 입력(sendKeys)한다.
  3. form 태그를 찾아서(findElementByTagName) submit한다.
  4. alert가 발생할때까지(wait.until(ExpectedConditionsalertIsPresent())) 잠시(10초) 기다린다.
  5. alert내용이(alert.getText()) 텍스트내용과 일치하는지(isEqualTo) 검증한다.
form을 submit하고나서 폼 Validation을 수행하고 이상이 없는 경우 서버는 alert 으로 정상 처리되었다는 응답을 검증하는 테스트메서드이다.

다음은 등록폼 html이다. 기능만 구현한 간단한 html이다.
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <title>Food</title>
</head>
<body>
  <h2>식품 등록</h2>
  <form action="#" th:action="@{/web/foods/add}" th:object="${foodCommand}" method="post">
 <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>

html에서는 form 태그에 th:object로 할당된 foodCommand variable expression이 존재하고 for 태그 내의 th:field attribute에 애스터릭(*{...}) 변수는 selection variable expression 이라고 한다.
foodCommand 객체 내의 멤버변수에 접근자를 호출한다. th:action attribute 의 @{/web/foods/add} 는 Link URL 을 표현하는 표현식이다.
#fields message variable expression이며, Validation에 걸리면 #fields 메세지 변수가 할당된다. errors('*') 는 모든 에러를 전부 보여주는 컬렉션 형태이며, errors('name') 이런식으로 단일 에러도 표현할 수 있다.

등록폼은 이름, 수량, 유통기한을 입력받아서 post 방식으로 /web/foods/add URI로 전달한다.
등록이 완료되어 성공하면 목록페이지로 리다이렉트되며, 성공했다는 alert 또한 목록페이지에서 보여준다. 목록 페이지 소스는 다음과 같이 구현한다.
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <title>Food</title>
  <script th:inline="javascript" th:if="${!#strings.isEmpty(registerFoodMessage)}">
  alert([[${registerFoodMessage}]]);
  </script>
</head>
<body>
  <h2>Hello, world!</h2>
</body>
</html>

자바스크립트를 호출하는 태그가 표현되어 있다. th:if 로 registerFoodMessage 변수가 비어있지 않으면 alert로 해당 변수를 나타낸다.

이제 컨트롤러를 구현한다.
@GetMapping("/add")
public String registerFoodForm(@ModelAttribute("foodCommand") FoodCommand foodCommand) {
    return "food/registerFoodForm";
}
    
@PostMapping("/add")
public String processRegistrationFood(@Valid FoodCommand foodCommand, Errors errors, RedirectAttributes ra) {
    if(errors.hasErrors()) {
        return "food/registerFoodForm";
    }
    ra.addFlashAttribute("registerFoodMessage", "식품을 저장했습니다.");
    return "redirect:/web/foods";
}

등록 폼을 보여주는 registerFoodForm 메서드는 GET 방식으로 동작하고 /add 매핑URI를 가진다. 따라서 /web/foods/add 와 동일한 주소를 매핑하는데 GET 방식으로 호출했을때만 동작하는 메서드이다.
메서드 파라미터로 @ModelAttribute 애너테이션을 통한 foodCommand 라는 객체를 전달받는다.
@ModelAttribute 애너테이션을 이용하면 RequestParameter로 전달되는 데이터를 Command 객체에 자동으로 바인딩해줘서 아주 편리하다. registerFoodForm html에서 th:object로 커맨드객체를 호출하므로 빈 커맨드객체를 바인딩해주는 역할도 한다.
메서드의 리턴 타입은 String으로 ModelAndView를 굳이 사용하지 않아도 ViewName 으로 자동 인식하고 해당 view 파일을 찾아간다.

processRegistrationFood 메서드는 등록 폼에서 전달받은 input 값을 submit 받아서 등록 처리를 수행하는 컨트롤러 메서드이다. 등록 폼과 주소는 동일하며 POST 방식으로만 동작한다. 매개변수로 @Valid 애너테이션이 선언된 FoodCommand 객체를 받고, org.springframework.validation.Errors 인터페이스도 전달받고, org.springframework.web.servlet.mvc.support.RedirectAttributes 인터페이스도 전달받는다.

@Valid 애너테이션으로 선언한 FoodCommand 는 입력 데이터의 검증을 하고, 오류가 있으면 view에 에러 fields 변수를 전달해준다.
Errors 인터페이스는 특정객체에 검증내역에 오류가 있거나, 바인딩 오류가 있는지 확인하고 알려주는 역할을 한다. 메서드 내에서는 errors 변수에 hasErrors 메서드를 호출해서 오류가 있을 경우 등록폼 View name으로 forward 하는데 쓰인다.

RedirectAttributes 인터페이스는 리다이렉트할때 객체를 전달해주는 역할을 하는데, 메서드 내에서는 addFlashAttribute 메서드를 이용해서 간단한 저장 성공 메시지를 전달해주는데 사용한다. flash Attribute 는 리다이렉트 된 후 한번만 model 에 저장되며 리다이렉트 된 url을 재요청하면 데이터는 사라진다.

이제 FoodCommand 커맨드 객체를 구현한다. 커맨드 객체는 단순한 값 전달(DTO) 용도의 객체로 멤버변수와 접근자/수정자로 구성되며 UI 와 컨트롤러 사이에서 데이터를 표현하고, 바인딩하고, 검증하는 역할을 한다.
package com.poseidon.fridge.command;

import java.util.Date;

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import org.springframework.format.annotation.DateTimeFormat;

public class FoodCommand {
    
    private Long id;
    
    @NotNull
    @Size(max=20)
    private String name;
    
    @Min(1)
    @Max(999)
    private Integer quantity;
    
    @DateTimeFormat(pattern="yyyy-MM-dd")
    private Date expiryDate;
    
    public FoodCommand() {}
    
    public FoodCommand(String name, Integer quantity, Date expiryDate) {
        this.name = name;
        this.quantity = quantity;
        this.expiryDate = expiryDate;
    }

    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getQuantity() {
        return quantity;
    }
    public void setQuantity(Integer quantity) {
        this.quantity = quantity;
    }
    public Date getExpiryDate() {
        return expiryDate;
    }
    public void setExpiryDate(Date expiryDate) {
        this.expiryDate = expiryDate;
    }

    @Override
    public String toString() {
        return "FoodCommand [id=" + id + ", name=" + name + ", quantity=" + quantity + ", expiryDate=" + expiryDate
                + "]";
    }
    
}

필드 검증용도의 애너테이션들이 보이는데 더 다양하지만, 여기서는 @NotNull, @Size, @Min, @Max 정도를 사용한다. 애너테이션들의 이름만 봐도 무엇을 검증하려는지 알 수 있다.

expiryDate 변수의 타입이 java.util.Date 형태이며, @DateTimeFormat 애너테이션이 선언되어 있다.
View 에서 유통기한 입력값이 YYYY. MM. DD 형태로 전달되는데 String형태의 입력값을 Date형태로 바인딩할 때, @DateTimeFormat의 주어진 pattern 형태로 parse할 수 있도록 선언한다.

테스트를 실행해보면 크롬 브라우져가 순식간에 데이터를 입력하고 사라지는것을 확인할 수 있다.

이전글: 냉장고 가계부 프로젝트 10
다음글: 냉장고 가계부 프로젝트 12

이 블로그의 인기 게시물

냉장고 가계부 프로젝트 14

fridge-web 프로젝트에서 api 서버와 통신할때 URL을 매번 중복해서 입력하는 부분을 제거하기 위해 RestTemplate 빈 등록메서드를 수정한다. @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.rootUri("http://localhost:8081").build(); } builder에 rootUri 메서드를 호출해서 api 서버 url을 미리 설정하고 build해서 RestTemplate 객체를 반환하면 RestTemplate을 사용하는 부분에서는 root 다음 경로만 넘겨주면 된다. WebFoodController 클래스의 restTemplate 사용부분을 전부 수정한다. @GetMapping public String foods(Model model) { ResponseEntity<Resources<FoodCommand>> response = restTemplate.exchange("/foods", HttpMethod.GET, null, new ParameterizedTypeReference<Resources<FoodCommand>>() {}, Collections.emptyMap()); .... 다른 메서드들도 동일하게 수정한다. Food 클래스에서도 이제 더이상 사용하지 않는 Cloneable과 hashCode, equals 메서드를 정리한다. Guava 의존라이브러리도 다른곳에서는 사용하지 않으므로 정리한다. 식품에 대한 최소한의 기능은 구현하였다. 이번에는 냉장고 라는 개념을 모델링한다. 식품들이 들어가고 나가는 곳은 냉장고이기 때문에 냉장고라는...

냉장고 가계부 프로젝트 27

스프링 Data 에서 제공하는 @CreatedDate, @LastModifedDate 애너테이션을 이용해서 작성일자, 수정일자를 도메인객체가 생성되고, 수정될 때 관리될 수 있도록 한다. Spring Data를 쓰기 전에는 DB컬럼에 Date 타입의 등록일 컬럼을 추가하고 DEFAULT 값으로 SYSDATE 를 줘서 DB에 Insert 되는 시간에 등록일자 컬럼이 채워지는 방식을 사용했었고, Update 쿼리가 실행될때 수정일자 컬럼에 SYSDATE를 직접 Update 해주는 방식을 자주 썼다. 그 뿐만아니라, 등록일자와 더불어 등록한 사용자(ex: registerUser)를 식별하는 식별키(ex: userId, username ...) 를 Insert 쿼리가 실행될때 등록해주고, 수정한 사용자(ex: modifedUser)를 Update 쿼리에 설정하는 방식은 차후에 있을지도 모를 일에 대비해서 늘 반복해서 작업했다. 스프링 Data 에서 제공하는 JPA Audit 기능은 이런 코드의 반복을 줄여준다. 사용자 같은 경우 객체로 넘기면 객체의 식별자가 담긴다. 등록시간은 날짜형 타입이다. public class Blog { @CreatedBy private User user; @CreatedDate private LocalDateTime creadtedDate; } Blog 클래스의 User 객체는 @CreatedBy 애너테이션으로 선언되서 등록한 사용자를 나타내는 컬럼에 값을 입력할것이다. createdDate 필드는 도메인객체가 영속성 저장소에 반영되는 시간을 나타낸다. Fridge, Food 클래스에 등록일, 수정일만 먼저 적용한다. 두 클래스에 createdDate, lastModifedDate 멤버변수를 선언한다. @Data @NoArgsConstructor @Entity @EntityListeners(AuditingEntityListener.class) public class Fridge { ...

냉장고 가계부 프로젝트 10

API 가 어느정도 준비되었으므로, UI를 만든다. 별도의 프로젝트로 구성해서 API를 호출하는 방식으로 구성한다. 프로젝트명은 fridge-web이라고 정한다. 냉장고 가계부 프로젝트 1 을 참고한다. 새 프로젝트에서는 Dependencies를 Web, Thymeleaf, DevTools 세개를 체크한다. 프로젝트가 준비되면, pom.xml 파일을 연다. <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <gro...