◆エラー内容
レスポンス用のjspで表示する日本語文字が文字化けした。
英語文字は問題なく表示される。
◆サーブレットのdoPost、doGetの内容
- doGetの内容
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
- ◆doPostの内容
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String text = request.getParameter("textName");
text += "hogehoge world!";
request.setAttribute("responseText", text);
request.getRequestDispatcher("response.jsp").forward(request, response);
}
◆エラーの原因
リクエストとレスポンスの文字コード設定を行っていなかったため。
◆修正点
doPostメソッド内に以下の部分を追記してエラーは解消された。
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
修正後のdoPostメソッドの全文は以下の通りです。
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
String text = request.getParameter("textName");
text += "hogehoge world!";
request.setAttribute("responseText", text);
request.getRequestDispatcher("response.jsp").forward(request, response);
}