백기선(인프런 강의)/스프링 웹 MVC
WebMvcConfigurer 설정 - 포메터 설정
레알윙
2020. 9. 1. 21:17
반응형
Fometter
Controller에서 URL에 값을 같이 보낼 때 문자열을 객체로 매핑해주는 역할을 하는 기능이다.
Formatter에는 Printer와 Parser을 상속 받아 사용한다.
Printer
- 해당 객체를 (Locale 정보를 참고하여) 문자열로 어떻게 출력할 것인가
Parser
- 어떤 문자열을(Locale 정보를 참고하여) 객체로 어떻게 변환할 것인가
기본 구성도 및 세팅
localhost:8080/hello?jinseok 으로 들어갈 시
@RestController
public class SampleController {
@GetMapping("/hello/{name}")
public String hello(@PathVariable("name") Person person) {
return "hello " + person.getName();
}
}
public class Person {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Person [name=" + name + ", getName()=" + getName() + ", getClass()=" + getClass() + ", hashCode()="
+ hashCode() + ", toString()=" + super.toString() + "]";
}
}
import java.text.ParseException;
import java.util.Locale;
import org.springframework.format.Formatter;
public class PsersonFormatter implements Formatter<Person> {
@Override
public Person parse(String text, Locale locale) throws ParseException {
Person person = new Person();
person.setName(text);
return person;
}
@Override
public String print(Person object, Locale locale) {
return object.toString();
}
}
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
@RunWith(SpringRunner.class)
@WebMvcTest
public class SampleControllerTest {
@Autowired
MockMvc mockMvc;
@Test
public void hello() throws Exception {
this.mockMvc.perform(get("/hello/jinseok"))
.andDo(print())
.andExpect( content().string("hello jinseok"));
}
}
Fometter 여러가지 방법으로 Spring에 등록할 수 있다.
첫 번째, WebMvcConfigurer의 addFormatters(FormatterRegistry) 메소드 정의
@Configuration
public class WebConfig implements WebMvcConfigurer{
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addFormatter(new PsersonFormatter());
}
}
두 번째, 해당 포매터를 빈으로 등록(스프링 부트 사용때만 가능)
@Configuration
public class PsersonFormatter implements Formatter<Person> {
@Override
public Person parse(String text, Locale locale) throws ParseException {
Person person = new Person();
person.setName(text);
return person;
}
@Override
public String print(Person object, Locale locale) {
return object.toString();
}
}
참고
@RequestParam을 사용할 시
@RestController
public class SampleController {
@GetMapping("/hello")
public String hello(@RequestParam("name") Person person) {
return "hello " + person.getName();
}
}
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
@RunWith(SpringRunner.class)
@WebMvcTest
public class SampleControllerTest {
@Autowired
MockMvc mockMvc;
@Test
public void hello() throws Exception {
this.mockMvc.perform(get("/hello")
.param("name", "jinseok"))
.andDo(print())
.andExpect( content().string("hello jinseok"));
}
}
반응형