แท็ก <fmt:setLocale> ใช้เก็บ Locale ที่กำหนดไว้ใน locale configuration variable เพื่อให้แท็ก Formatting อื่นๆ ใช้ Locale นี้
แอตทริบิวต์ของ <fmt:setLocale>
| แอตทริบิวต์ | คำอธิบาย | จำเป็น | ค่าเริ่มต้น |
|---|---|---|---|
| value | รหัส Locale: ภาษา (ISO-639) + ประเทศ (ISO-3166) เช่น en_US, th_TH | ใช่ | en_US |
| variant | รหัส Variant เฉพาะ Browser/Platform | ไม่ | None |
| scope | ขอบเขตของ locale configuration variable | ไม่ | Page |
ตัวอย่างสมบูรณ์: สร้าง Resource Bundle และเปลี่ยน Locale
1. Default Bundle (Example_En.java)
package com.tutorialspoint;
import java.util.ListResourceBundle;
public class Example_En extends ListResourceBundle {
public Object[][] getContents() { return contents; }
static final Object[][] contents = {
{"count.one", "One"},
{"count.two", "Two"},
{"count.three", "Three"}
};
}
2. Spanish Bundle (Example_es_ES.java)
package com.tutorialspoint;
import java.util.ListResourceBundle;
public class Example_es_ES extends ListResourceBundle {
public Object[][] getContents() { return contents; }
static final Object[][] contents = {
{"count.one", "Uno"},
{"count.two", "Dos"},
{"count.three", "Tres"}
};
}
คอมไพล์ทั้งสองไฟล์ ให้ได้ Example.class และ Example_es_ES.class วางใน CLASSPATH ของ Web App
3. JSP ใช้งาน
<%@ taglib uri="https://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="https://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<html>
<head>
<title>JSTL fmt:setLocale Tag</title>
</head>
<body>
<fmt:bundle basename="com.tutorialspoint.Example">
<fmt:message key="count.one"/><br/>
<fmt:message key="count.two"/><br/>
<fmt:message key="count.three"/><br/>
</fmt:bundle>
<!-- เปลี่ยน Locale เป็น Spanish -->
<fmt:setLocale value="es_ES"/>
<fmt:bundle basename="com.tutorialspoint.Example">
<fmt:message key="count.one"/><br/>
<fmt:message key="count.two"/><br/>
<fmt:message key="count.three"/><br/>
</fmt:bundle>
</body>
</html>
ผลลัพธ์
One Two Three Uno Dos Tres
สรุป: fmt:setLocale เปลี่ยน Locale เริ่มต้นสำหรับแท็ก fmt ต่อไป fmt:bundle ใช้ basename เดียวกันแต่โหลด class ตาม Locale ใหม่