HTMLエンコードとは、HTMLとして特殊な意味を持つ文字を、特殊な意味を持たない文字列に置換することです。
具体的には、「&」「lt;」「gt;」「"」などを、「&」「<」「>」「"」に置換します。
Javaでは、HTMLエンコード処理が標準でサポートされていませんので、独自に処理をする必要があります。
サーブレットコンテナなどが提供している場合が多いですから、その機能を使う方法もありますが、移植性が悪くなります。
そこで、以下に、ASHで作成したHTMLエンコード処理を紹介します。
ASPを使った場合の、server.HTMLencodeに相当する機能です。
JSPなどで簡単にHTMLエンコードするためのクラスを作成してみます。 Htmlクラスのメソッドとして、encodeメソッドを作成します。 staticクラスとして作成してありますので、newする必要がありません。
クラス static Html メソッド String encode(String) 機能 入力された文字列をHTMLエンコードして返却する パラメータ HTMLエンコードしたい文字列 返却値 HTMLエンコードされた文字列 |
以下に、Htmlクラスのソースを示します。
最初に入力文字列(strIn)を出力文字列(strOut)にコピーして、エンコードが必要な文字が出てきた場合に、出力文字列を置換しています。
出力文字列の置換は、先頭の&は置換し、残りを挿入する処理となっています。
このアルゴリズムは、エンコードが必要な文字が少ない場合に、高速に処理できる特徴があります。
HTMLエンコードが必要な文字と、エンコード後の文字列は、配列で初期値を設定しています。
| Html.java |
|---|
// Copyright (C)1995-2002 ASH multimedia lab. http://ash.jp/
package jp.ash.common;
/** HTMLユーティリティ **/
public class Html {
/** HTMLエンコードが必要な文字 **/
static char[] htmlEncChar = {'&', '"', '<', '>'};
/** HTMLエンコードした文字列 **/
static String[] htmlEncStr = {"&", """, "<", ">"};
/**
* HTMLエンコード処理。
* &,",<,>の置換
**/
public static String encode (String strIn) {
if (strIn == null) {
return(null);
}
// HTMLエンコード処理
StringBuffer strOut = new StringBuffer(strIn);
// エンコードが必要な文字を順番に処理
for (int i = 0; i < htmlEncChar.length; i++) {
// エンコードが必要な文字の検索
int idx = strOut.toString().indexOf(htmlEncChar[i]);
while (idx != -1) {
// エンコードが必要な文字の置換
strOut.setCharAt(idx, htmlEncStr[i].charAt(0));
strOut.insert(idx + 1, htmlEncStr[i].substring(1));
// 次のエンコードが必要な文字の検索
idx = idx + htmlEncStr[i].length();
idx = strOut.toString().indexOf(htmlEncChar[i], idx);
}
}
return(strOut.toString());
}
}
|
JSPファイルでHTMLエンコード処理を使った例です。
<input ... value="<%= Html.encode("エンコードしたい文字列") %>" />
|
| HtmlEncode.jsp |
|---|
<%@ page contentType="text/html; charset=Shift_JIS" %>
<%@ page import="jp.ash.common.*" %>
<html>
<head><title>HTMLエンコードのテスト</title></head>
<body>
<h1>HTMLエンコードのテスト</h1>
<form>
<table><tr>
<td>&の付いたデータ</td>
<td><input type="text" value="<%= Html.encode("joe&joe") %>" /></td>
</tr><tr>
<td><>の付いたデータ</td>
<td><input type="text" value="<%= Html.encode("<joe>") %>" /></td>
</tr><tr>
<td>"の付いたデータ</td>
<td><input type="text" value="<%= Html.encode("\"joe\"") %>" /></td>
</tr></table>
</form>
</body>
</html>
|