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

วิธี Escape ตัวอักษร XML ใน JSP ด้วย JSTL fn:escapeXml


ฟังก์ชัน fn:escapeXml() ใช้ Escape ตัวอักษรที่มีความหมายพิเศษใน XML ให้กลายเป็น Entity Reference ป้องกัน XSS และรักษาความสมบูรณ์ของ XML

Syntax

java.lang.String escapeXml(java.lang.String)

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

<%@ taglib uri="https://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="https://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<html>
<head>
<title>Using JSTL Functions</title>
</head>
<body>
<c:set var="string1" value="This is first String."/>
<c:set var="string2" value="This <abc>is second String.</abc>"/>
<p>ใช้ escapeXml():</p>
<p>string (1) : ${fn:escapeXml(string1)}</p>
<p>string (2) : ${fn:escapeXml(string2)}</p>
<p>ไม่ใช้ escapeXml():</p>
<p>string (1) : ${string1}</p>
<p>string (2) : ${string2}</p>
</body>
</html>

ผลลัพธ์

ใช้ escapeXml():
string (1) : This is first String.
string (2) : This &lt;abc&gt;is second String.&lt;/abc&gt;
ไม่ใช้ escapeXml():
string (1) : This is first String.
string (2) : This is second String.

คำอธิบาย: string2 มีแท็ก <abc> หากไม่ escape จะถูก Browser render เป็น HTML element หายไป escapeXml จะแปลง < → &lt; > → &gt; & → &amp; เป็นต้น