Escape Special Characters With Jakarta Commons

posted on 27 Jun 2005 21:50 by somkiat

สำหรับคนที่ต้องการหาวิธีการจัดการกับ Special Character เช่น <, >, &, .เป็นต้น

ใน Java นั้นมักจะมีปัญหากับตัว \ และ " (Double quote) ส่วนใน JavaScript จะมีปัญหากับ ' (Single quote) และสุดท้าย SQL ก็มักจะมีปัญหากับ single quote

โดยในการจัดการปัญหาเหล่านี้ก้มีหลายวิธีที่แตกต่างกันไป แล้วแต่จะคิดได้ครับ แต่วันนี้ผมขอแนะนำอีกวิธีครับ คือ Jakarta Common-Lang

จะใช้ class StringEscapeUtils ซึ่งจะใช้เป็นตัวช่วยสำหรับการจัดการอักษรพิเศษดังข้างต้น

จะมี 2 function หลักๆ ดังนี้

1. escapeHTML

2. unescapeHTML

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

String textWithBrackets = "There is always < (less) or > (more) than you want.";
String textEscaped = StringEscapeUtils.escapeHTML(textWithBrackets);
System.out.println(textEscaped); // There is always < (less) or > (more) than you want.
String textUnescaped = StringEscapeUtils.unescapeHTML(textEscaped);
System.out.println(textWithBrackets.equals(textEscaped)); // true

Resource

http://jakarta.apache.org/commons/lang/

Comment



smilebig smileopen-mounthed smileconfused smilesad smileangry smiletonguequestionembarrassedsurprised smilewinkdouble winkcry

Tweet

หายไปนาน

กลับมาเป็นเรื่องเลย

#1 By plynoi แว่วศรี on 2005-06-27 23:00

ช่วงนี้งานยุ่งครับ ไม่ค่อยมีเวลามา update ครับ

ขอบคุณครับ

#2 By somkiat on 2005-07-05 00:02