在Servlet的response輸出時,若輸出的內容是UTF-8編碼,則應設置
response.setContentType("text/html;charset=UTF-8");
也就是說必須指定contentType,Web Server才能按正確的編碼輸出內容。。。
然後再response.getWriter().write(e.getMessage());
但是response.getOutputStream().print依然有亂碼,因爲outputstream是輸出流,並不對編碼進行處理。。
而getWriter則有對編碼進行再處理。。。
/* get encoding from Content-Type header */
String encoding = getCharacterEncoding();
if (encoding==null && _servletHttpRequest!=null)
{
/* implementation of educated defaults */
String mimeType = _httpResponse.getMimeType();
encoding = _servletHttpRequest.getServletHandler()
.getHttpContext().getEncodingByMimeType(mimeType);
}
if (encoding==null)
// get last resort hardcoded default
encoding = StringUtil.__ISO_8859_1;
上面內容是Jetty的getWriter一個實現。。默認下使用的編碼是iso-8859-1
轉自:http://hi.baidu.com/wadise/blog/item/771fa8ecd1d0112263d09fed.html