แท็ก <fmt:requestEncoding> ใช้ระบุ Character Encoding สำหรับการถอดรหัสข้อมูลที่ส่งมาจาก Form (POST request)
แอตทริบิวต์ของ <fmt:requestEncoding>
| แอตทริบิวต์ | คำอธิบาย | จำเป็น | ค่าเริ่มต้น |
|---|---|---|---|
| key | ชื่อ Character Encoding ที่ต้องการใช้ (เช่น UTF-8) | ใช่ | None |
เหตุผลที่ต้องใช้แท็กนี้
- Browser ส่วนใหญ่ไม่ส่ง Header Content-Type ใน Request
- ถ้า Encoding ของหน้าที่สร้าง Response ต่างจาก Encoding ของ Request ต้องระบุชัดเจน
- หากมีการตั้งค่า Locale ผ่าน I18N formatting action ที่เรียก
ServletResponse.setLocale()Encoding ใน page directive จะถูกทับ - จำเป็นเมื่อใช้ Encoding ที่ไม่ใช่ ISO-8859-1
ตัวอย่างการใช้งาน
<%@ 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:requestEncoding Tag</title>
</head>
<body>
<fmt:requestEncoding value="UTF-8" />
<fmt:setLocale value="es_ES"/>
<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>
ผลลัพธ์
Uno Dos Tres
สรุป: วาง <fmt:requestEncoding value="UTF-8" /> ไว้ต้นหน้า JSP ก่อนอ่าน Parameter ใดๆ จาก Request