天天看點

解決servlet的out輸出流html中文亂碼

代碼如下。兩種方法可以解決。

1.

 response.setContentType("text/html");

       PrintWriter out = response.getWriter();

       out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");

       out.println("<HTML>");

       out.println("  <HEAD><TITLE>中文亂碼解決</TITLE></HEAD>");

       out.println("  <BODY>");

       out.print("    This is ");

       out.print(this.getClass());

--------------------------------------------------      

code如下 

      /*

      *解決辦法,就是将字元串str的格式轉換成别的格式,一般是gb1803就可以了。編碼格式自己選。

       */

       String str="<center><p>哈哈哈哈 哈哈哈哈哈 哈哈哈哈哈</p></center>";  

       byte[] b = str.getBytes("gb18030");  

       str= new String(b,"iso8859-1");  

       out.println(str); 

       out.println("  </BODY>");

       out.println("</HTML>");

       out.flush();

       out.close(); 

2.   

-----------------------------------------------------------------------

      * 第二招 就是一句話, response.setContentType("text/html;charset=GB2312"); 即可解決問題

      */

       response.setContentType("text/html;charset=GB2312"); 

       PrintWriter out= response.getWriter();

       out.println("<html>");

       out.println("<head>");

       out.println("<title>JasperReports - Web Application Sample</title>");

       out.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"../stylesheet.css\" title=\"Style\">");

       out.println("</head>");

       out.println("<body bgcolor=\"white\">");

       out.println("<span class=\"bnew\">JasperReports 提示資訊:</span>");

       String str = "<center><p><pre style='color:red;border=2px'>報表伺服器正在處理其他檔案,請您稍後重試。</pe> </p></center>";

       out.println("</body>");

       out.println("</html>");

       out.close();

3.我将自己的源碼全拿出來,你們自己試吧,總能搞定的。搞不定了繼續百度。。

public voiddoGet(HttpServletRequest request, HttpServletResponse response)throwsServletException, IOException {

       /*第一招

      response.setContentType("text/html");

       //out.println("<meta http-equiv=\"content-type\" content=\"text/html; charset=GB18030\">") ;

       out.println("  <HEAD><TITLE>劉振宇</TITLE></HEAD>");

       //String str= "";

       //out.println(", "+str+" using the GET method");

        */

        /*第二招

       //response.setContentType("text/html");

       response.setContentType("text/html;charset=GB2312");

       //out.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=GB2312\">");

       //out.println("<meta http-equiv=\"Content-Type\" contentType=\"text/html; charset=GB18030\">");

       //response.setCharacterEncoding("gb2312");//設定PrintWriter的編碼

       //response.setContentType("text/html;charset=utf-8");//可增加Content-Type頭字段

        String str = "<center><p><pre style='color:red;border=2px'>報表伺服器正在處理其他檔案,請您稍後重試。</pe> </p></center>";

       //e.printStackTrace(out);

    }

     */

 }

                  2012-911  許昌