티스토리 뷰

intellij 의 단축키 command + o를 누르면 클래스들을 검색해 볼 수 있다.

Formatter를 검색하면 여러 포메터들이 보인다.

 

 

그 중에 스프링 것을 열어서 구현체를 확인해 보면 (왼쪽 초록 버튼)

 

 

수 많은 구현체들을 확인 해볼 수 있다..

 

이전 글에서는 포메터를 등록하고, 단 한가지의 방식으로 이쁘게 포멧을 해줬었다. (예 : 10,000)

 

하지만 여러 형식으로 표현하고 싶을 때는 여러개를 등록해야하니 표현하기가 어려워진다.

그것을 편하게 하기 위해 스프링에서 지원하는 것이 있다.

 

스프링이 제공하는 기본 포맷터

스프링은 자바에서 기본으로 제공하는 타입들에 대해 수 많은 포맷터를 기본으로 제공한다.
IDE
에서 Formatter 인터페이스의 구현 클래스를 찾아보면 수 많은 날짜나 시간 관련 포맷터가 제공되는 것을 확인할 수 있다.
그런데 포맷터는 기본 형식이 지정되어 있기 때문에, 객체의 각 필드마다 다른 형식으로 포맷을 지정하기는 어렵다.

스프링은 이런 문제를 해결하기 위해 애노테이션 기반으로 원하는 형식을 지정해서 사용할 수 있는 매우 유용한 포맷터 두 가지를 기본으로 제공한다.

@NumberFormat : 숫자 관련 형식 지정 포맷터 사용, NumberFormatAnnotationFormatterFactory

@DateTimeFormat : 날짜 관련 형식 지정 포맷터 사용, Jsr310DateTimeFormatAnnotationFormatterFactory

 

package hello.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 FommatterController {

    @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;
    }
}

 

get edit

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<form th:object="${form}" th:method="post">
  number <input type="text" th:field="*{number}"><br/>
  localDateTime <input type="text" th:field="*{localDateTime}"><br/>
  <input type="submit"/>
</form>
</body>
</html>

 

post edit

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body> <ul>
    <li>${form.number}: <span th:text="${form.number}" ></span></li>
    <li>${{form.number}}: <span th:text="${{form.number}}" ></span></li>
    <li>${form.localDateTime}: <span th:text="${form.localDateTime}" ></span></li>
    <li>${{form.localDateTime}}: <span th:text="${{form.localDateTime}}" ></span></li>
</ul>
</body>
</html>

 

get edit 페이지

 

post edit 페이지

 

이렇게 표시 된다. 여기서 중요 한 점이 있다.

 

get edit에서 서브밋을 눌렀을 경우

//"10,000" --> 10000
//"2021-06-18 23:00:45 -> localDateTime
@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;
}

 

post edit으로 넘어올 때에 데이터는 스트링 "10,000" number와 "2023-12-21 22:17:00이 넘어오게 된다.

 

post edit의 @ModelAttribute는 이 데이터를 보고 @NumberFormat 과 @DateTimeFormat을 보고 내가 가져가야할 데이터임을 알고 가져가게 된다. 그래서 객체는 각각

 

10000 과 2023-12-21T22:17이 되며 포메팅 하는 ${{}}을 썻을 때 우리가 원하는 값을 표출해 준다.

 

빽단에서 찍어보면

이런 모양으로 사용 되니 주의해야한다.

view단에 표시 될 때에만 thymleaf 의 field 속성 혹은 ${{}} 을 사용 했을 때에 포멧을 맞춰 표시 될 뿐이다.

 

참고
> @NumberFormat , @DateTimeFormat 의 자세한 사용법이 궁금한 분들은 다음 링크를 참고하거나 관련

애노테이션을 검색해보자.
> https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#format- CustomFormatAnnotations

 

'dev_공부일지 > spring boot + intelliJ' 카테고리의 다른 글

파일 업로드 소개  (0) 2023.12.25
포메터 정리 안되는거 있다.  (0) 2023.12.21
WebConfig에 Formatter 등록  (1) 2023.12.20
Formatter 사용  (0) 2023.12.20
뷰 템플릿에 컨버터 적용하기  (0) 2023.12.19
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
글 보관함