埋め込み文字列内のXMLエンティティをエスケープする
プロパティ「"eventhandler.referenceinsertion.class"」と「"eventhandler.escape.html.match"」を設定することで、埋め込み文字列内のXMLエンティティのエスケープ(「<>&」→「<>&」)を行なってくれます。
- デフォルトは何もしないので、明示的に設定する必要があります。
- 「"eventhandler.referenceinsertion.class"」で組み込みのハンドラクラスを指定し、
- 「"eventhandler.escape.html.match"」でエスケープする変数を示す正規表現を指定します。
final VelocityEngine engine = new VelocityEngine(); Properties p = new Properties(); // プロパティとして、XMLエンティティのエスケープを行なうハンドラを指定 p.setProperty("eventhandler.referenceinsertion.class", "org.apache.velocity.app.event.implement.EscapeHtmlReference"); // エスケープを行なう変数名を正規表現で指定 // 指定しないと、エスケープしてくれないので注意。 p.setProperty( "eventhandler.escape.html.match", "/.*/" ); engine.init(p); VelocityContext context = new VelocityContext(); context.put( "test", "<b>test</b>" ); // エスケープが必要な文字列 StringWriter sw = new StringWriter(); engine.evaluate( context, sw, "test", "$test" ); // 結果を出力 System.out.println( sw.toString() );
実行結果です。
<b>test</b>,<b>test</b>
さて、問題はVelocityで出力されるHTML内に埋め込まれたscript内で動的に値を設定している部分だよな。
$("#foo").text("${var}");
とかなっている箇所の${var}をVelocityでエスケープしてしまうと、(jQueryでもエスケープされるので)二重にエスケープされてしまう(はず)。どうするかな。