文字化け
しょーもないプログラムなのに、文字化けしてしまう。一応うまくいく方法も分かったけど、その理由がよく分からん。。
■jsp
<%@ page contentType="text/html; charset=UTF-8"%> <html> <head></head> <body> <form name="f" action="http://localhost:8080/MyApp/servlet/myservlet" method="GET"> <input type="text" name="hogehoge"> <input type="submit" value="送信"> </form> </body> </html>
public class MyServlet extends HttpServlet { protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { req.setCharacterEncoding("UTF-8"); req.getRequestDispatcher("/result.jsp").forward(req, res); } protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { req.setCharacterEncoding("UTF-8"); req.getRequestDispatcher("/result.jsp").forward(req, res); } }
■result.jsp
<%@ page contentType="text/html; charset=UTF-8"%> <html> <body> 入力文字列:<%= request.getParameter("hogehoge") %> </body> </html>
たかが、これだけのプログラム!
最初のjsp表示時のテキストフィールドに全角文字を入れて送信すると入力文字列が化けて表示される。。ちなみにformタグのmethodをGETからPOSTに変えるとうまく表示される。何が違うのさ!?
ちなみにアプリケーションサーバーはTomcat5.5です。妙にはまってるなぁ。トホホ・・・
追記(2008/9/11)
id:koumiyaさんに情報提供していただきました。どうもありがとうございます!
server.xmlのconnctor要素にuseBodyEncodingForURI=”true”という属性を追加するとGETパラメータでも文字化けしなくなるはずです。 参考:http://www.atmarkit.co.jp/fjava/rensai3/mojibake03/mojibake03.html
これでいけました!
@ITの記事によると、
フォームのデータ送信にGETメソッドを用いたときの振る舞いがWebコンテナの実装依存であることだ。(中略) 実はTomcat 5.xではGETにより受信したパラメータに対して、setCharacterEncodingメソッドの文字コードを「適用しない」という仕様変更がなされているのである。
なんじゃそりゃ!!っていうオチでした。