- protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- PrintWriter pw = response.getWriter();
- response.setCharacterEncoding( "utf-8" );
- response.setContentType( "text/html; charset=utf-8" );
- pw.print( "中文" );
- }
- HTTP/ 1.1 200 OK
- Server: Apache-Coyote/ 1.1
- Content-Type: text/html;charset=ISO- 8859 - 1
- Content-Length: 2
- Date: Thu, 08 Mar 2007 06 : 04 : 55 GMT
- ??
PrintWriter getWriter() throws IOExceptionReturns a PrintWriter object that can send character text to the client. The PrintWriter uses the character encoding returned by getCharacterEncoding(). If the response's character encoding has not been specified as described in getCharacterEncoding (i.e., the method just returns the default value ISO- 8859 - 1 ), getWriter updates it to ISO- 8859 - 1 .
- public void setCharacterEncoding(String charset) {
- if (isCommitted())
- return ;
- // Ignore any call from an included servlet
- if (included)
- return ;
- // Ignore any call made after the getWriter has been invoked
- // The default should be used
- if (usingWriter)
- return ;
- coyoteResponse.setCharacterEncoding(charset);
- isCharacterEncodingSet = true ;
- }
ServletOutputStream
輸出不受此限制,經測試寫出如下代碼。
- ServletOutputStream out = response.getOutputStream();
- out.print( "中文" );
- //情況1:正常,瀏覽器按utf-8方式查看
- //response.setContentType("text/html; charset=utf-8");
- //情況2:瀏覽器缺省按簡體中文查看,手動設爲utf-8方式查看正常
- //response.setCharacterEncoding("utf-8");
setContentType(java.lang.String)
with the String
of text/html
and calling this method with the String
of UTF-8
is equivalent with calling setContentType
with the String
of text/html; charset=UTF-8
. setContentType(java.lang.String)
or setLocale(java.util.Locale)
, this method overrides it.- //情況1:正常,瀏覽器按utf-8方式查看
- response.setContentType( "text/html; charset=gbk" );
- response.setCharacterEncoding( "utf-8" );
- //情況2:正常,瀏覽器按簡體中文方式查看
- //response.setContentType("text/html; charset=utf-8");
- //response.setCharacterEncoding("gbk");
- PrintWriter pw = response.getWriter();
- pw.print( "中文" );
setContentType
或者 setCharacterEncoding
;採用ServletOutputStream方式,不受此限。setContentType
和 setCharacterEncoding
兩方法中設定characterEncoding的方法對服務器效果一致,不需要反覆調用。在輸出文本內容時,採用response.setContentType("text/html; charset=utf-8");似乎更爲方便。