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
กลับมาเป็นเรื่องเลย
#1 By plynoi แว่วศรี on 2005-06-27 23:00