10
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

setContentTypeでcharset=UTF-8を設定してもISO-8859-1になってしまう

Posted at

HttpServletResponseのsetContentTypeメソッドでcharsetをUTF-8にしているにもかかわらず、実際にブラウザから見るとResponseHeaderのContent-typeはISO-8859-1となっており文字化けしてしまう。

修正前

servlet.java

public void doGet(HttpServletRequest req,
                  HttpServletResponse res) 
                  throws ServletException, IOException {
  // 略

    try (PrintWriter pw = res.getWriter()) {
      res.setContentType("text/html; charset=UTF-8");
      StringBuffer sb = new StringBuffer();
      //返却するHTMLの内容
      sb.append("<html>");
      // 略
      pw.println(new String(sb));
      pw.close();
    } catch (IOException e) {
      // 例外処理
    }
}

修正後

servlet.java

public void doGet(HttpServletRequest req,
                  HttpServletResponse res) 
                  throws ServletException, IOException {
  // 略

    res.setContentType("text/html; charset=UTF-8");
    try (PrintWriter pw = res.getWriter()) {
      StringBuffer sb = new StringBuffer();
      //返却するHTMLの内容
      sb.append("<html>");
      // 略
      pw.println(new String(sb));
      pw.close();
    } catch (IOException e) {
      // 例外処理
    }
}

まとめ

HttpServretRequestのgetWriterを呼び出す前に、charsetを指定しないと、
defaultのISO-8859-1が設定されてしまう。

すでに動いていたコードからコピペしたら、うまく行かなかったけどAPI仕様を見たらちゃんと書いてあった。
ServletResponse (Servlet 2.4 API 仕様)

安易なコピペはダメゼッタイ!

10
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?