JSTL: fmt

Language/JSP 2014. 11. 14. 17:39

FMT, I18N - 국제화(Internationalization)

기능  : 지역, 메시지 형식, 숫자 및 날짜형식

접두어(Prefix)  :  fmt

directive : <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>


JSTL 국제화 지역화 태그로 다국어 문서를 처리할 때 유용하고, 날짜와 숫자 형식을 다룰 때 사용된다.  




목차

setLocale

requestEncoding

bundle

setBundle

message

formatNumber

parseNumber

formatDate

parseDate

setTimeZone, timeZone





setLocale

다국어를 지원하는 페이지를 만들 경우 ResourceBundle로 불러오는 *.properties 파일들과 연계되어서 사용한다. 


<fmt:setLocale value="locale"  [variant="variant"] [scope="{page|request|session|application}"]/>


 value의 locale 값은 http://ftp.ics.uci.edu/pub/ietf/http/related/iso639.txt 언어코드와 http://userpage.chemie.fu-berlin.de/diverse/doc/ISO_3166.html  국가코드로  이루어진다. 생략될경우 톰캣 서버의 기본 값으로 설정이 되고, 둘 중에 하나만 사용할 수도 있다.


 <%@ page contentType = "text/html; charset=utf-8" %> 

 <%@ taglib  uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> 

 <%@ taglib  uri="http://java.sun.comjsp/jsp/jstl/fmt" prefix="fmt"%> 


 <pre> 

    default  locale  : <%=  response.getLocale() %> 

    set  locale  : ko <fmt:setLocale value="ko"  /> 

    now: <%=  response.getLocale() %> 

    set  locale  : ja  <fmt:setLocale value="ja"  /> 

    now: <%=  response.getLocale() %> 

    set  locale  : en  <fmt:setLocale value="en"  /> 

    now: <%=  response.getLocale() %> 

 </pre> 




requestEncoding

request.setCharacterEncoding() 역할을 한다. 


<fmt:requestEncoding  [value="charsetName"]/> 

 <%@ page contentType = "text/html;charset=utf-8" %> 

 <%@ taglib  uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> 


 <%@ taglib  uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %> 

 <fmt:requestEncoding value="utf-8"/> 

 파라미터:<c:out value="${param.id}"/> 
 <form  method="post"> 
       <input type="text"  name="id"/> 
       <input type="submit"/> 

 </form> 



bundle
properties 확장자를 사용하는 자원 파일을 읽어오는 역할을 한다. 

<fmt:bundle  basename="basename"  [prefix="prefix"]> 
     body content 
</fmt:bundle> 

basename 속성에  지정된 properties 파일을  찾아서 locale  에  따라 읽어들인다.  
properties 파일은 보통 WEB-INF/classes 아래에 위치하며 디렉토리의 깊이에 따라서 패키지형식의 이름을 취한다. TestBundle.properties 파일이com/itexpert/test/msg 디렉토리에 있다면 basename="com.itexpert.test.msg.TestBundle"  이라고 지정하면 된다. 

locale이 ko라면 TestBundle_ko.properties 파일을 읽어오게 되며, locale이 맞지 않는 경우에는 TestBundle.properties처럼 코드가 붙지 않은 파일을 읽어온다.

prefix 속성은 key 명칭이 공통적인 부분을 지정해서 body에서 표현되는 key를 단축시킨다. import 에서 패키지 명을 지정하면 클래스명만 쓸 수 있는 것과 같이 생각할 수  있다.


setBundle
페이지 전체에서 사용할 수 있는 번들을 지정할 수 있는데, 이에 대한 지정은 <fmt:setBundle/> 태그가 담당한다. var속성에서 정한 변수를 이후에 나오는 <fmt:message/>태그에서 basename  속성에 변수 명으로 대체할 수  있다. 

<fmt:setBundle  basename="basename" [var="varName"] [scope="{page|request|session|application}"]/> 



message
 번들 태그에서 정한  값들을 가져온다. 

Syntax 1: body  없는 경우
<fmt:message  key="messageKey"  [bundle="resourceBundle"] [var="varName"] 
        [scope="{page|request|session|application}"]/> 

Syntax 2: 메시지 파라미터를 지정하는 body가 있는 경우
<fmt:message  key="messageKey"  [bundle="resourceBundle"] [var="varName"] 
        [scope="{page|request|session|application}"]> 
        <fmt:param>  서브태그 
</fmt:message> 

Syntax 3: 키와 선택적 메시지 파라미터를 지정하는 body가 있는 경우
<fmt:message  [bundle="resourceBundle"]  [var="varName"] 
        [scope="{page|request|session|application}"]> 
        key 
        선택적 <fmt:param>  서브태그 
</fmt:message> 

 번들에 있는 key값을 불러온다. bundle 속성으로 번들을 직접 설정할 수도 있고, <fmt:bundle/> 태그 사이에 중첩되어서 키 값만 받아서 출력할 수 있다. 

● 예제 
1) 웹  루트\WEB-INF\classes\bundle  경로에  다음의 properties 파일  두  개를  작성  한다. 
- testBundle_ko.properties 
  name=\ud558\ud558\ud558. 
  message=JSTL \uc7ac\ubbf8\uc788\ub2e4. 

- testBundle.properties 
  name=Han. 
  message=JSTL is fun. 

※ 참고 :  properties 파일은 한글은 입력할 수 없기 때문에 유니코드로 입력해야 하며 j2sdk의 /bin/native2ascii.exe 파일을 이용하여 한글을 유니코드 값을 확인 할 수 있다.  먼저 한글을 입력하고 엔터를 누르면 유니코드로 변환되어 출력한다. 

 properties  파일을  두  개  작성하는  이유는 로케일에  따라 영어 또는  한글로 출력할  수  있다.  영어로 출력하기 위해서는 익스플로러의 "인터넷 옵션-일반-언어"에서 한국어를 지우고 영어를 선택하면 영어로 출력 된다. 

2) JSP  파일  작성 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<%@ page contentType = "text/html; charset=utf-8" %>
<%@ taglib  prefix="c"  uri="http://java.sun.comjsp/jsp/jstl/core" %>
<%@ taglib  prefix="fmt"  uri="http://java.sun.com/jsp/jstl/fmt"  %>
 
<html>
<head><title>JSTL fmt  예제 -  bundle  , message</title></head>
<body>
 
<fmt:bundle  basename="bundle.testBundle">
    <fmt:message  key="name"/>
    <p/>
    <fmt:message  key="message" var="msg"/>
    <c:out value="${msg}"/>
</fmt:bundle>
 
</body>
</html>



formatNumber
숫자  형식을 표현할  때 사용된다. 

Syntax 1: body 없는 경우
<fmt:formatNumber value="numericValue" 
        [type="{number|currency|percent}"]  [pattern="customPattern"] 

        [currencyCode="currencyCode"] [currencySymbol="currencySymbol"] 

        [groupingUsed="{true|false}"]  [maxIntegerDigits="maxIntegerDigits"] 

        [minIntegerDigits="minIntegerDigits"] [maxFractionDigits="maxFractionDigits"] 

        [minFractionDigits="minFractionDigits"]  [var="varName"] 

        [scope="{page|request|session|application}"]/> 


Syntax 2: 형식에 맞출 수치가 body에 있는 경우

<fmt:formatNumber  [type="{number|currency|percent}"] 

        [pattern="customPattern"]  [currencyCode="currencyCode"] 

        [currencySymbol="currencySymbol"]  [groupingUsed="{true|false}"] 

        [maxIntegerDigits="maxIntegerDigits"]  [minIntegerDigits="minIntegerDigits"] 

        [maxFractionDigits="maxFractionDigits"] [minFractionDigits="minFractionDigits"] 

        [var="varName"] [scope="{page|request|session|application}"]> 

        형식화될 수치 

</fmt:formatNumber> 

<fmt:formatNumber value="1700600"/> // 1,700,600

<fmt:formatNumber value="1700600" type="currency" groupingUsed="true"/> // ₩1,700,600

<fmt:formatNumber value="50" type="percent" groupingUsed="false"/> // 5000%

<fmt:formatNumber value="1670400" type="currency"  currencySymbol="&"/> // &1,670,400

<fmt:formatNumber value="999" minIntegerDigits="5" minFractionDigits="2"/> // 00,999.00


속성

동적

Type

설명

value

true

String 

또는 Number

  형식화될 수치

type

true

String

  숫자, 통화, 퍼센트  중  어느 것으로 표시할  지 지정

  {number|currency|percent}

pattern

true

String

  사용자가  지정한 형식 패턴.

currencyCode

true

String

  ISO 4217 통화 코드 (통화 형식일 때만 적용)

  (type="currency")

currencySymbol

true

String

  통화 기호 (통화 형식일 때만 적용)

  (type="currency")

groupingUsed

true

boolean

  형식 출력에 그룹 분리기호를 포함할지 여부

 (기본값은 true)

maxIntegerDigits

true

int

  형식 출력에서 integer 최대 자리 수

minIntegerDigits

true

int

  형식 출력에서 integer 최소 자리 수

maxFractionDigits

true

int

  형식 출력에서 소수점 이하 최대 자리 수

minFractionDigits

true

int

  형식 출력에서 소수점 이하 최소 자리 수

var

false

String

  형식 출력 결과 문자열을 담는 scope에 해당하는 변수명

scope

false

String

  var의 scope

  



parseNumber

반대로 정해진 패턴을 문자열에서 수치를 파싱해내는 태그


Syntax 1: body가  없는 경우

<fmt:parseNumber value="numericValue" 

        [type="{number|currency|percent}"]  [pattern="customPattern"] 

        [parseLocale="parseLocale"] [integerOnly="{true|false}"] 

        [var="varName"] [scope="{page|request|session|application}"]/> 


Syntax 2: 파싱할 수치를 body에 갖고 있는 경우

<fmt:parseNumber  [type="{number|currency|percent}"] 

        [pattern="customPattern"]  [parseLocale="parseLocale"] 

        [integerOnly="{true|false}"]  [var="varName"] 

        [scope="{page|request|session|application}"]> 

        파싱할 수치 

</fmt:parseNumber>


속성

동적

Type

설명

value

true

String 또는 Number

  파싱할 수치

 type

true

String

  숫자, 통화, 퍼센트 중 어느 것으로 표시할 지 지정

  {number|currency|percent}

pattern

true

String

  사용자가 지정한 형식 패턴

parseLocale

true

String 또는 java.util.Locale

  파싱 작업의 기본 형식 패턴(숫자, 통화, 퍼센트 각각)을 제공하는 Locale

integerOnly

true

boolean

  true일 경우 주어진 값에서 Integer 부분만 파싱

var

false

String

  파싱 결과(java.lang.Number)를 담는 scope에 해당하는 변수명

scope

false

String

  var의 scope



formatDate
날짜 형식을 표현하는 태그

<fmt:formatDate value="date" 
        [type="{time|date|both}"] [dateStyle="{default|short|medium|long|full}"] 
        [timeStyle="{default|short|medium|long|full}"] [pattern="customPattern"] 
        [timeZone="timeZone"] 
        [var="varName"] [scope="{page|request|session|application}"]/> 

속성

동적

Type

설명

value

true

java.util.Date

  형식화 될 Date와 Time 

type

true

String

  형식화 할 데이터가 시간, 날짜, 혹은 시간과 날짜인지 지정

dateStyle

true

String

  미리 정의된 날짜 형식. java.text.DateFormat 클래스에 정의된 문법을 따른다. 

  type 속성이 생략되었거나 date 혹은 body일 때 사용

timeStyle

true

String

  미리 정의된 시간 형식.

  type 속성이 time 혹은 body일 때 사용

pattern

true

String

  사용자 지정 형식 스타일

timeZone

true

String 또는 java.util.TimeZone

  형식화 시간에 나타날 타임 존

var

false

String

  형식 출력 결과 문자열을 담는 scope에 해당하는 변수명

scope

false

String

  var의 scope



parseDate
정해진 패턴의 문자열에서  날짜를 파싱해내는  태그 

Syntax 1: body 없는 경우
<fmt:parseDate value="dateString"
        [type="{time|date|both}"] [dateStyle="{default|short|medium|long|full}"] 
        [timeStyle="{default|short|medium|long|full}"] [pattern="customPattern"] 
        [timeZone="timeZone"] [parseLocale="parseLocale"] 
        [var="varName"] [scope="{page|request|session|application}"]/> 

Syntax 2: 파싱한 값이 body에 있는 경우
<fmt:parseDate  [type="{time|date|both}"] 
        [dateStyle="{default|short|medium|long|full}"]  
        [timeStyle="{default|short|medium|long|full}"] [pattern="customPattern"] 
        [timeZone="timeZone"] [parseLocale="parseLocale"] [var="varName"] 
        [scope="{page|request|session|application}"]> 
        파싱할 Date  와 time 
</fmt:parseDate> 

속성

동적

Type

설명

value

true

java.util.Date

  파싱할 Date와 Time 

type

true

String

  파싱할 데이터가 시간, 날짜, 혹은 시간과 날짜인지 지정

dateStyle

true

String

  미리 정의된 날짜 형식. java.text.DateFormat 클래스에 정의된 문법을 따른다.

  type 속성이 생략되었거나 date 혹은 body일 때 사용

timeStyle

true

String

  미리 정의된 시간 형식

  type 속성이 time 혹은 body일 때 사용

pattern

true

String

  사용자 지정 형식 스타일 

timeZone

true

String 또는 java.util.TimeZone

  형식화 시간에 나타날 타임 존 

parseLocale

true

String 또는 java.util.Locale

  파싱하는 동안 적용될 미리 정의된 형식스타일의 Locale 

var

false

String

  파싱 결과(java.util.Date)를 담는 scope에 해당하는 변수명 

scope

false

String

  var의 scope


● 예제

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
32
33
34
<%@ page contentType = "text/html; charset=utf-8" %>
<%@ page pageEncoding="utf-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
 
<!DOCTYPE html>
<html>
<head><title></title></head>
<body>
    <pre>
        <fmt:setLocale value="ko_KR"/>
        number : <fmt:formatNumber value="9876543.61" type="number"/>
        currency : <fmt:formatNumber value="9876543.61" type="currency"/>
        percent : <fmt:formatNumber type="percent">9876543.61</fmt:formatNumber>
 
        pattern=".000"    :<fmt:formatNumber value="9876543.61" pattern=".000" />
        pattern="#,#00.0#":<fmt:formatNumber value="9876543.612345" pattern="#,#00.0#"/>
 
        <jsp:useBean id="now" class="java.util.Date"/>
        <c:out value="${now}"/>
        date : <fmt:formatDate value="${now}" type="date"/>
        time : <fmt:formatDate value="${now}" type="time"/>
        both : <fmt:formatDate value="${now}" type="both"/>
        default : <fmt:formatDate value="${now}" type="both"  dateStyle="default" timeStyle="default"/>
        short : <fmt:formatDate value="${now}" type="both"  dateStyle="short"   timeStyle="short"   />
        medium : <fmt:formatDate value="${now}" type="both"  dateStyle="medium"   timeStyle="medium"  />
        long : <fmt:formatDate value="${now}" type="both"  dateStyle="long"     timeStyle="long"    />
        full : <fmt:formatDate value="${now}" type="both"  dateStyle="full"     timeStyle="full"     />
 
        pattern="yyyy년MM월dd일 HH시mm분ss초"
        <fmt:formatDate value="${now}"  type="both" pattern="yyyy년MM월dd일 HH시mm분ss초"/>
    </pre>
</body>
</html>




setTimeZone, timeZone
<fmt:setTimeZone/> : 특정 스코프의 타임 존을 설정한다.
<fmt:setTimeZone value="timeZone" [var="varName"] [scope="{page|request|session|application}"]/>

<fmt:timeZone/> : 타임 존을 부분 적용한다.
<fmt:timeZone value="timeZone"> 
    body content 
</fmt:timeZone> 

● 예제

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
<%@ page contentType = "text/html; charset=utf-8" %>
<%@ taglib  uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib  uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
 
<!DOCTYPE html>
<html>
<head><title></title></head>
<body>
    <pre>
        <fmt:setLocale value="ko_KR"/>
        <jsp:useBean id="now" class="java.util.Date"/>
 
        default : <c:out value="${now}"/>
        Korea KST :
        <fmt:formatDate value="${now}" type="both" dateStyle="full" timeStyle="full"/>
         
        <fmt:timeZone value="GMT">
            Swiss GMT :
            <fmt:formatDate value="${now}" type="both" dateStyle="full" timeStyle="full"/>
        </fmt:timeZone>
 
        <fmt:timeZone value="GMT-8">
            NewYork GMT-8 :
            <fmt:formatDate value="${now}" type="both" dateStyle="full" timeStyle="full"/>
        </fmt:timeZone>
    </pre>
</body>
</html>




출처 - http://noritersand.tistory.com/256


'Language > JSP' 카테고리의 다른 글

JSTL 정리  (0) 2014.11.14
JSTL: fn  (0) 2014.11.14
JSTL: core  (0) 2014.11.14
JSTL  (0) 2014.11.14
JSP 게시판 구현 시 Paging 처리 하기  (0) 2014.11.11
: