PrintWriter输出乱码问题

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;
    }
其中usingWriter 标志为getPrinteWriter方法中设定,可见其控制逻辑为一旦返回了PrintWriter,本函数即不再生效。
 

综合以上,在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();
   }
  }
 }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值