ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Formatter 추가하기
    SPRING/스프링 MVC 2021. 6. 14. 22:43

    Formatter : Formatter는 데이터 바인딩을 수행해주는 것을 도와줍니다.

    즉, 객체<---> 문자열 간의 변환을 수행합니다.

     

    예제 코드

    public class Person {
    
        private String name;
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    }
    
    // @Component
    // 등록 방식 1 : Component로 등록시 WebConfig에서 addFormatter로 Formatter를 추가하지 않아도 된다.
    public class PersonFormatter implements Formatter<Person> {
    
        @Override
        public Person parse(String s, Locale locale) throws ParseException {
            Person person = new Person();
            person.setName(s);
            return person;
        }
    
        @Override
        public String print(Person person, Locale locale) {
            return person.toString();
        }
    }
    
    @RestController
    public class SampleController {
    
        @GetMapping("/hello")
        public String hello(@RequestParam("name") Person person) {
            return "hello " + person.getName();
        }
        
    }
    
    @Configuration
    public class WebConfig implements WebMvcConfigurer {
    
    // 등록 방식 2
        @Override
        public void addFormatters(FormatterRegistry registry) {
            registry.addFormatter(new PersonFormatter());
        }
    
    }
    
    

     

    PersonFormatter의 parse는 문자-> 객체에 쓰이는 메서드이고, print는 객체 -> 문자에 쓰이는 메서드이다.

     

    Formatter를 등록하는 방법

     

    1. WebConfig에서 addFormatters를 Override한 다음 Formatter를 등록하는 방식

    2. Formatter 클래스에 @Component 을 붙여서 Bean으로 등록하는 방식

     

    테스트

    @RunWith(SpringRunner.class)
    //@WebMvcTest 
    // WebMvcTest는 addFormatter 사용시 , 아래 2개의 어노테이션은 Component추가 방식
    @SpringBootTest
    @AutoConfigureMockMvc
    public class SampleControllerTest {
    
        @Autowired
        MockMvc mockMvc;
    
        @Test
        public void hello() throws Exception{
    
            this.mockMvc.perform(get("/hello")
                    .param("name", "jump"))
                    .andDo(print()) // 요청과 응답을 출력
                    .andExpect(content().string("hello jump"));
        }
    
    }
    

    'SPRING > 스프링 MVC' 카테고리의 다른 글

    Resource Handler  (0) 2021.06.16
    HandlerInterceptor (서블릿 필터 비교)  (0) 2021.06.15
    스프링 부트에서 JSP 사용하기  (0) 2021.06.13
    SPRING MVC 설정 관련 정리  (0) 2021.06.11
    스프링 MVC -WEB.XML 제거  (0) 2021.06.10
Designed by Tistory.