Help us understand the problem. What is going on with this article?

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

More than 3 years have passed since last update.

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 仕様)

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

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away