728x90
Converter 객체 생성
package hello.typeconverter.type;
import lombok.EqualsAndHashCode;
import lombok.Getter;
@Getter
@EqualsAndHashCode
public class IpPort {
private String ip;
private int port;
public IpPort(String ip, int port) {
this.ip = ip;
this.port = port;
}
}
Converter 생성
package hello.typeconverter.converter;
import hello.typeconverter.type.IpPort;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.convert.converter.Converter;
@Slf4j
public class StringToIpPortConverter implements Converter<String, IpPort> {
@Override
public IpPort convert(String source) {
log.info("covert source={}", source);
String[] split = source.split(":");
String ip = split[0];
int port = Integer.parseInt(split[1]);
return new IpPort(ip, port);
}
}
Converter 등록
package hello.typeconverter;
import hello.typeconverter.converter.IntegerToStringConverter;
import hello.typeconverter.converter.IpPortToStringConverter;
import hello.typeconverter.converter.StringToIntegerConverter;
import hello.typeconverter.converter.StringToIpPortConverter;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(new StringToIntegerConverter());
registry.addConverter(new IntegerToStringConverter());
registry.addConverter(new StringToIpPortConverter());
registry.addConverter(new IpPortToStringConverter());
}
}
컨트롤러
@GetMapping("/ip-port")
public String ipPort(@RequestParam IpPort ipPort) {
System.out.println("ipPort.getIp() = " + ipPort.getIp());
System.out.println("ipPort.getPort() = " + ipPort.getPort());
return "ok";
}
728x90
'백엔드 > Spring(Boot)' 카테고리의 다른 글
스프링 Formatter 적용 (0) | 2021.10.04 |
---|---|
스프링 뷰 템플릿 Converter 적용 (0) | 2021.10.03 |
스프링 @ExceptionResolver 예외처리(API) (0) | 2021.10.03 |
스프링 부트 에러 페이지 설정 (0) | 2021.10.02 |
스프링 서블릿 예외처리에 대한 로그 필터(필터 중복 호출 설정) (0) | 2021.10.02 |