PrintWriter输出乱码问题,我们先看API
PrintWriter getWriter() throws IOException
Returns 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.
PrintWriter getWriter() throws IOException
Returns 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.
就是讲,在返回一个PrintWriter对象的时候,CharactorEncoding就已经确定了,就已经设置好了字符集了。什么时候设置的呢?
现在来看下setCharacterEncoding方法的实现:
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;
}
综合以上,在servlet中输出中文,如果采用PrintWriter方式,需要在调用getPrintWriter()之前调用setContentType 或者 setCharacterEncoding;
如下:
/**
* Ajax中的验证码问题
*
* @return void
* */
public void validate() {
ActionContext actionContext = ActionContext.getContext();
String sessionCode = (String) actionContext.getSession().get(
Constant.VALIDATE_CODE);// 获取验证码生成时存入Session中的验证码
if (sessionCode != null && sessionCode != ""
&& !sessionCode.equals(validateCode)) {
try {
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("text/html;charset=utf-8");
PrintWriter printWriter = response.getWriter();
printWriter.write("验证码错误");
printWriter.flush();
printWriter.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}