JavaのForm入出力のエンコーディング
javaをつかってFormの入力データをやり取りしていると、
次画面へデータを表示させたとき、
必ず文字化けしている。
jspのヘッダを指定しても、
requestのキャラクターセットを行ってもダメ。
泣きそうでした。
んで、以下、上手くいった設定メモ。
1.Tomcatのconf\server.xmlのConnectorタグに、
useBodyEncodingForURI="true" を設定。
<Connector
port="8080" maxHttpHeaderSize="8192"
maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
enableLookups="false" redirectPort="8443" acceptCount="100"
connectionTimeout="20000" disableUploadTimeout="true"
useBodyEncodingForURI="true"/>
2.Filterを継承するクラスを作成。
ここでは、test.common.SetCharacterEncodingFilterでビルド。
doFilterメソッドは以下のような記述。
public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain)
throws IOException, ServletException {// Conditionally select and set
//the character encoding to be used
if (ignore || (request.getCharacterEncoding() == null)) {
String encoding = selectEncoding(request);
if (encoding != null)
request.setCharacterEncoding(encoding);
}
chain.doFilter(request, response);
}
public void init(FilterConfig filterConfig)
throws ServletException {
this.filterConfig = filterConfig;
this.encoding = filterConfig.getInitParameter("encoding");
String value = filterConfig.getInitParameter("ignore");
if (value == null)
this.ignore = true;
else if (value.equalsIgnoreCase("true"))
this.ignore = true;
else if (value.equalsIgnoreCase("yes"))
this.ignore = true;
else
this.ignore = false;
}
3.該当サイトのweb.xmlに以下の記述を追加
ここでは、EUC-JPに設定。
ちなみに、ここでencodingパラメーターに設定した文字コードが、
上記クラスのメソッド内で取得され、
アプリケーションで扱う文字コードとしてフィルタリングされます。
<filter>
<filter-name>EUC-JP Encoding</filter-name>
<filter-class>test.common.SetCharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>EUC-JP</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>EUC-JP Encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
今までやってきたJavaプロジェクトのソースを漁って見つけた方法なんだけど、
結構普通の手法なんだね。。
ごめんよ、こんなところまで、辿り着けなくて。
っていうか、前任者すごい。