In JSP writing often in the page using variable direct output (eg.<%=username%>), sometimes to display information, sometimes as a JS parameter provided, and sometimes used to assemble the URL. Because of the existence of an escape character of the HTML language itself, the direct output of the variable will cause the page to display abnormally, or JS syntax error, or URL error, this article discusses the analysis and solution of this problem, at the same time explore the struts framework for the solution of this problem, I hope that other similar problems can be inspired to solve.
Html:
< Escape sequence for <
> Escape sequence for >
& Escape sequence for &
" Escape sequence for "
Javascript:
Url:
Struts Solution:
Report:
public class Pageutil {/** * genarate escape sequance in HTML for special str * @see HTML 4.01 Specificati On 5.3.2 Character Entity references */public static string escape4html (String str) {StringBuffer SB =
New StringBuffer ();
for (int i=0;i<str.length (); i++) {char c = str.charat (i);
if (c = = ' ") sb.append (" " ");
else if (c = = ' < ') sb.append ("<");
else if (c = = ' > ') sb.append (">");
else Sb.append (c);
return sb.tostring (); }/** * Genarate escape sequance in JavaScript for special str * @see JavaScript Language 1.1 specification 2.7.5 Escape sequences for String literals/public static String Escape4js (String str) {StringBuffer
SB = new StringBuffer (); for (int i=0;i<str.length (); i++) {char c = Str.chaRAt (i);
if (c = = '/') sb.append ("///'");
else if (c = = ' ") sb.append ("///");
else Sb.append (c);
return sb.tostring ();
public static void Main (string[] args) {}}