如何通过UTF-8编码的ServletOutputStream字符发送

时间:2010-01-02 18:42:08

标签: java servlets utf-8 internationalization

我的servlet代码如下:

response.setContentType("text/html; charset=UTF-8");
response.setCharacterEncoding("UTF-8");
ServletOutputStream out = response.getOutputStream();
out.println(...MY-UTF-8 CODE...);

...

然后我收到错误:

java.io.CharConversionException: Not an ISO 8859-1 character: ש
 javax.servlet.ServletOutputStream.print(ServletOutputStream.java:89)
 javax.servlet.ServletOutputStream.println(ServletOutputStream.java:242)
 rtm.servlets.CampaignLogicServlet.doPost(CampaignLogicServlet.java:68)
 javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
 javax.servlet.http.HttpServlet.service(HttpServlet.java:717)

如何切换Servlet输出流的字符集???

6 个答案:

答案 0 :(得分:91)

我认为您想要使用getWriter()。这将接受一个字符串并对其进行编码,而输出流则用于处理二进制数据。

来自doc:

  

返回可以的PrintWriter对象   将字符文本发送给客户端。该   使用的字符编码是一个   在charset = property中指定   setContentType(java.lang.String)   方法,必须在之前调用   为charset调用此方法   生效。

     

这种方法或   可以调用getOutputStream()   写下身体,而不是两者。

以下是代码的更改:

response.setContentType("text/html; charset=UTF-8");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
out.println(...MY-UTF-8 CODE...);

答案 1 :(得分:8)

这也有效:

ServletOutputStream out = response.getOutputStream();
out.write("MY-UTF-8 CODE".getBytes("UTF-8")); 

答案 2 :(得分:3)

同样的情况发生在我之前,我试图在PrintWriter的顶部添加一行,这是工作。

response.setContentType(“text / html; charset = GBK”);
PrintWriter out = response.getWriter();

答案 3 :(得分:0)

public void output(String jsonStr, HttpServletResponse response) throws IOException {
    response.setContentType("text/html;charset=UTF-8;");
    response.setCharacterEncoding("UTF-8");
    ServletOutputStream out = response.getOutputStream();
    out.write(jsonStr.getBytes("UTF-8"));
    out.flush();
    out.close();
}

答案 4 :(得分:0)

在必须从doFilter向@WebServlet(“ / anywebpage”)请求分派器的情况下,该分派器应仅包含PrintWriter out = response.getWriter();

        String erpg = "anywebpage";
        response.setContentType("text/html; charset=UTF-8");
        RequestDispatcher rd = request.getRequestDispatcher(erpg);
        rd.include(request, response);

您不需要声明以下行: response.setCharacterEncoding(“ UTF-8”);

相反,请确保在PrintWriter out = response.getWriter();之前包括以下内容:说明:

response.setContentType("text/html; charset=UTF-8");

答案 5 :(得分:-1)

// HTML Output code list
StringBuffer select_code = new StringBuffer();
List<con_element> ccc = codeService.code_select(code);

for(int i=0;i<ccc.size();i++){
    select_code.append("<option value='" + ccc.get(i).getCce_num() + "'>" + ccc.get(i).getCce_hname() + "</option>" );
}

response.setContentType("text/html; charset=UTF-8");
response.setCharacterEncoding("UTF-8");
response.getWriter().print( select_code );