最近突然发现自己的系统在输出字符串的时候出现下标越界的错误,如下:
java.lang.ArrayIndexOutOfBoundsException: 16384
at com.caucho.vfs.i18n.UTF8Writer.write(UTF8Writer.java:143)
at com.caucho.server.connection.ToByteResponseStream.flushCharBuffer(ToByteResponseStream.java:476)
at com.caucho.server.connection.ToByteResponseStream.nextCharBuffer(ToByteResponseStream.java:461)
at com.caucho.server.connection.ResponseWriter.write(ResponseWriter.java:144)
at com.caucho.vfs.AbstractPrintWriter.print(AbstractPrintWriter.java:210)
at cn.joy.action.BaseAction.outPrint(BaseAction.java:207)
at cn.joy.action.CommentsAction.commentsList(CommentsAction.java:70)
跟踪代码发现输出字符串的时候用的PrintWriter 对的print方法
HttpServletResponse response = ServletActionContext.getResponse(); response.setContentType("text/html;charset=utf-8"); PrintWriter out = null; try { out = response.getWriter(); } catch (IOException e) { } String result = message; if (out != null) { out.print(result); out.flush(); out.close(); }
最后测试发现当web服务器为tomcat的时候该问题不会出现,所以自己推断该问题与不同web服务器对PrintWriter的实现不同有关系,所以最后采用直接输出字节流的形式解决该问题:
HttpServletResponse response = ServletActionContext.getResponse(); //response.setContentType("text/html;charset=utf-8"); response.setContentType("application/json;charset=utf-8"); ServletOutputStream out = null; try { //out = response.getWriter(); response.setCharacterEncoding("utf-8"); out = response.getOutputStream(); if (out != null){ out.write(message.getBytes("utf-8")); out.flush(); } } catch (Exception e) { log.error(e.getMessage(), e); }finally{ try { if (out != null) { out.close(); } } catch (IOException e) { log.error(e.getMessage(), e); } }
希望对大家有帮助
版权声明:本文为博主原创文章,未经博主允许不得转载。