Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม

วิธีใช้ fmt:message แสดงข้อความตาม Locale และแทนที่พารามิเตอร์ใน JSP


แท็ก <fmt:message> ใช้สำหรับดึงข้อความจาก Resource Bundle ตาม Key และ Locale พร้อมทำ Parametric Replacement (แทนที่ค่า placeholder)

แอตทริบิวต์ของ <fmt:message>

แอตทริบิวต์ คำอธิบาย จำเป็น ค่าเริ่มต้น
key Key ของข้อความที่ต้องการดึง ไม่ Body
bundle Resource Bundle ที่จะใช้ (จาก var ของ setBundle) ไม่ Default bundle
var ชื่อตัวแปรเก็บข้อความที่แปลแล้ว ไม่ Print to page
scope ขอบเขตของตัวแปร ไม่ Page

ตัวอย่างการใช้งาน

<%@ 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:message Tag</title>
</head>
<body>
<fmt:setLocale value="en"/>
<fmt:setBundle basename="com.tutorialspoint.Example" var="lang"/>
<fmt:message key="count.one" bundle="${lang}"/><br/>
<fmt:message key="count.two" bundle="${lang}"/><br/>
<fmt:message key="count.three" bundle="${lang}"/><br/>
</body>
</html>

ผลลัพธ์ (Locale en)

One Two Three

โครงสร้าง Resource Bundle (Java Class)

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

Parametric Replacement: หากข้อความใน Bundle มี placeholder เช่น {0} สามารถส่งค่าเข้าไปผ่านแท็ก <fmt:param> ภายใน body ของ message ได้