웹 애플리케이션에서 객체를 문자로, 문자를 객체로 변환할때 유용하게 사용할 수 있는 포맷터에 대해서 공부했다.
ex)
숫자에 1000단위로 쉼표를 넣어야 하는 경우
OR
"1,000"이라는 문자를 1000이라는 숫자로 변경 해야하는 경우
이때 사용할 수 있는것이 Locale이다.
Locale ==> 날짜나 숫자표현 방법에 대한 현지화 정보
<Formatter>
package com.example.typeconverter.formatter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.format.Formatter;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
@Slf4j
public class MyNumberFormatter implements Formatter<Number> {
@Override
public Number parse(String text, Locale locale) throws ParseException { //문자 -> 숫자
log.info("text={}, locale={}",text,locale);
NumberFormat format = NumberFormat.getInstance(locale);
return format.parse(text);
}
@Override
public String print(Number object, Locale locale) { //객체 -> 문자
log.info("object={}, locale={}",object,locale);
return NumberFormat.getInstance(locale).format(object);
}
}
<WebConfig>
package com.example.typeconverter;
import com.example.typeconverter.converter.IntegerToStringConverter;
import com.example.typeconverter.converter.IpPortToStringConverter;
import com.example.typeconverter.converter.StringToIntegerConverter;
import com.example.typeconverter.converter.StringToIpPortConverter;
import com.example.typeconverter.formatter.MyNumberFormatter;
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 StringToIpPortConverter());
//registry.addConverter(new IntegerToStringConverter());
registry.addConverter(new IpPortToStringConverter());
//registry.addConverter(new StringToIntegerConverter());
registry.addFormatter(new MyNumberFormatter());
}
}
<테스트 결과>
숫자의 형식이 잘 변경되어 출력된것을 확인할 수 있다.
파라미터를 10,000으로 줘도 숫자 10000으로 변경된 값을 서버에서 받는 것도 확인 할 수 있다.
@GetMapping(value = "/hello-v2")
public String helloV2(@RequestParam Integer data){
System.out.println("data = "+data);
return "ok";
}
스프링이 제공하는 기본 포맷터
스프링은 개발자가 직접 포맷 형식을 지정하여 사용할 수 있도록 해주는 포맷터 두가지를 기본으로 제공한다
- @NumberFormat : 숫자 관련 형식 지정 포맷터 사용
- @DateTimeFormat : 날짜 관련 형식 지정 포맷터 사용
사용 예시는 다음과 같다.
package com.example.typeconverter.controller;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.format.annotation.NumberFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import java.time.LocalDateTime;
@Controller
public class FormatterController {
@GetMapping("/formatter/edit")
public String formatterForm(Model model){
Form form = new Form();
form.setNumber(10000);
form.setLocalDateTime(LocalDateTime.now());
model.addAttribute("form",form);
return "formatter-form";
}
@PostMapping("/formatter/edit")
public String formatterEdit(@ModelAttribute Form form){
return "formatter-view";
}
@Data
static class Form{
@NumberFormat(pattern = "###,###") //숫자 포맷 형식 설정
private Integer number;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") //날짜 포맷 형식 설정
private LocalDateTime localDateTime;
}
}
'BackEnd > 스프링 MVC' 카테고리의 다른 글
스프링을 이용한 파일 업로드, 다운로드 (0) | 2025.01.11 |
---|---|
스프링 - 파일 업로드(1) (0) | 2025.01.10 |
@ExceptionHandler (0) | 2025.01.09 |
스프링 부트 - ExceptionResolver (0) | 2025.01.09 |
HandlerExceptionResolver (0) | 2025.01.07 |