BBS水木清华站∶精华区

发信人: sleepyworm (睁着眼睡觉的瞌睡虫@_@), 信区: Java        
标  题: Re: JSP数据库插入中文:到底有没有可行的解决办法? 
发信站: BBS 水木清华站 (Fri Jun 16 21:42:59 2000) 
 
有关中文问题大家讨论了好久了, 
我自己的问题已经解决了. 
我那天看了看精华版,把各位的方法,汇总了一下. 
--------------------------------------------------------------- 
java(Jsp)中汉字问题; 
1. 
I just know something about the display of Asian Languge.For example, if you have Chinese or Japanese character in yourJava source, when compiling, use "-encoding" option like that: 
 
javac -g -encoding SJIS code_with_Japanese.java 
 
Jdk 1.1 provide the functions to convert local language characterto Uicode. I think it is " getbyte() " ( I'm not so sure ), youcan use it like that: 
 
    getbyte("汉字", Language option); 
                        BIG5/GB/SJIS ... the document describing 
the language code is released with Jdk1.1, in "Internationalization"part? 
 
 
在 JDK Documentation 中查到了此方法,应该是 String.getBytes()。但它只能把 Unicode 转换成相应平台的码制。实际上很多地方要把其它码制转换成 Unicode 码。比如要把利用已有的一些中文文本,用 Java 直接打开全是乱码。 
 

从jdbc中取数据,中文字符串,处理方法.下面介绍的方法可以解决从数据库中取数据的中文问题. 
以oracle为例 
if(rset.next ()) 

        InputStream inStream=rset.getBinaryStream(i);               
        int avail=inStream.available();                 
        byte[] byteTemp=new byte[avail];                
        inStream.read(byteTemp,0,avail);                
        querryData[i-1]=new String(byteTemp,"GBK");     
//注意不要直接使用getString( ) 

3. 
 我在servlet中按前面几位大侠的指导把string用GBK编码成java可认得中文, 但发现把这些string发送到网页的时候反而成了乱码,用system.out.println 是中文,这怎么解决?是网页的设置原因吗? 
 
还是我自己来回答吧, 原来java程序中必须用GBK编码才能正常操作, 而在网页上则必须重新用ISO8859_1编码, 所以在发送到网页前需要增加一步转换: 
String username = request.getParameter("username"); 
username = new String(username.getBytes("ISO8859_1"), "GBK"); 
...... 
...... 
username = new String(username.getBytes("GBK"), "ISO8859_1"); 
out.println(username); 
 
这样就正常了, 不过页面记得用gb2312编码.             
 

   这两天在win98下装apache1.3.9加jserv和gnujsp1.0,jdk1.2.2,jsdk2.0 
   发现中文无法正常显示。要么乱码,要么出错。 
   经网友提醒,总结了以下几条方法。 
   1:修改区域设置:在控制面版中选择区域设置,设为英语(美国)? 
      然后重起。一切就都正常。 
   2:在jsp页中加入一条语句: 
      <%@ page contentType="text/html;charset=gb2312" %> ? 
       jsp显示就正常了。 
   3:在编译servlet和jsp时加入代码选项。编译servlet使用 
       javac -encoding iso8859_1 myservlet.java 
      在jsp的zone配置文件中.修改编译参数为: 
       compiler=builtin-javac -encoding ISO8859_1 
     使用这种方法后,不需要作其他的改动就可以正常显示中文了。 
     只是看前面网友的文章在编译servlet时都用GBK码,我试了很多 
     次都不行。而且使用ISO8859_1在原理上难以理解。 
   4:最土的办法,在servlet源程序中加入代码变换语句。如 
      try{ 
      out.println(new ( (new String("我爱死你了")).getBytes("GBK"),"ISO8859_1") 
      } 
      catch( UnsupportedEncodingException e) 
      { 
       ....... 
       } 
      使用这种方法一定要注意捕获UnsupportedEncodingException这个异常。     
 
这个是我的用于数据库取出中文乱码和网络取出中文乱码的处理函数 
其实精华区也有类似的东西。 
入参是有问题的String,出参是解决了的String 
        String parseChinese(String in) 
        { 
                String s = null; 
                byte temp []; 
                if (in == null) 
                { 
                        System.out.println("Warn:Chinese null founded!"); 
                                return new String(""); 
                } 
                try 
                { 
                        temp=in.getBytes("iso-8859-1"); 
                        s = new String(temp); 
                }                                        
                { 
                        System.out.println("Warn:Chinese null founded!"); 
                                return new String("");        
                }                                        
                try                                       
                { 
                        temp=in.getBytes("iso-8859-1");       
                        s = new String(temp);                
                } 
                catch(UnsupportedEncodingException e) 
                { 
                        System.out.println (e.toString()); 
                } 
                return s; 
        } 
 
windows平台上出现中文问题.                                                                  
oracle: 
 在application中完全没有问题 
 在jsp中 , 
 1).jsp中 
  aa.insertString(str1.getBytes("ISO-8859-1") 
  aa是一个javabean 
  2)aa的实现 
   insertString(byte[] b1){ 
     String s1=new String("GBK"); 
...} 
 
如何在socket中传送汉字 
 
byte[] temp_t; 
String temp_p; 
temp_p=request.getParameter("message"); 
temp_t=temp_p.getBytes("ISO8859-1"); 
String temp=new String(temp_t); 
 
如何用servlet实现文件的上载?麻烦知道的大虾Re? 
   
给一个例子。(不用多谢,我也是抄来的)  
   
public class UploadServlet extends HttpServlet  
{  
  //default maximum allowable file size is 100k  
  static final int MAX_SIZE = 102400;  
  //instance variables to store root and success message  
  String rootPath, successMessage;  
  /**  
   * init method is called when servlet is initialized.  
   */  
  public void init(ServletConfig config) throws ServletException  
  {  
    super.init(config);  
    //get path in which to save file  
    rootPath = config.getInitParameter("RootPath");  
    if (rootPath == null)  
    {  
      rootPath = "/";  
    }  
    /*Get message to show when upload is complete. Used only if  
      a success redirect page is not supplied.*/  
    successMessage = config.getInitParameter("SuccessMessage");  
    if (successMessage == null)  
    {  
      successMessage = "File upload complete!";  
    }  
  }  
  /**  
   * doPost reads the uploaded data from the request and writes  
   * it to a file.  
   */  
  public void doPost(HttpServletRequest request,  
    HttpServletResponse response)  
  {  
    ServletOutputStream out=null;  
    DataInputStream in=null;  
    FileOutputStream fileOut=null;  
    try  
    {  
      /*set content type of response and get handle to output  
        stream in case we are unable to redirect client*/  
      response.setContentType("text/plain");  
      out = response.getOutputStream();  
    }  
    catch (IOException e)  
    {  
      //print error message to standard out  
      System.out.println("Error getting output stream.");  
      System.out.println("Error description: " + e);  
      return;  
    }  
    try  
    {  
      //get content type of client request  
      String contentType = request.getContentType();  
      //make sure content type is multipart/form-data  
      if(contentType != null && contentType.indexOf(  
        "multipart/form-data") != -1)  
      {  
        //open input stream from client to capture upload file  
        in = new DataInputStream(request.getInputStream());  
        //get length of content data  
        int formDataLength = request.getContentLength();  
        //allocate a byte array to store content data  
        byte dataBytes[] = new byte[formDataLength];  
        //read file into byte array  
        int bytesRead = 0;  
        int totalBytesRead = 0;  
        int sizeCheck = 0;  
        while (totalBytesRead < formDataLength)  
        {  
          //check for maximum file size violation  
          sizeCheck = totalBytesRead + in.available();  
          if (sizeCheck > MAX_SIZE)  
          {  
            out.println("Sorry, file is too large to upload.");  
            return;  
          }  
          bytesRead = in.read(dataBytes, totalBytesRead,  
            formDataLength);  
          totalBytesRead += bytesRead;  
        }  
        //create string from byte array for easy manipulation  
        String file = new String(dataBytes);  
        //since byte array is stored in string, release memory  
        dataBytes = null;  
        /*get boundary value (boundary is a unique string that  
          separates content data)*/  
        int lastIndex = contentType.lastIndexOf("=");  
        String boundary = contentType.substring(lastIndex+1,  
          contentType.length());  
        //get Directory web variable from request  
        String directory="";  
        if (file.indexOf("name=\"Directory\"") > 0)  
        {  
          directory = file.substring(  
            file.indexOf("name=\"Directory\""));  
          //remove carriage return  
          directory = directory.substring(  
            directory.indexOf("\n")+1);  
          //remove carriage return  
          directory = directory.substring(  
            directory.indexOf("\n")+1);  
          //get Directory  
          directory = directory.substring(0,  
            directory.indexOf("\n")-1);  
          /*make sure user didn't select a directory higher in  
            the directory tree*/  
          if (directory.indexOf("..") > 0)  
          {  
            out.println("Security Error: You can't upload " +  
              "to a directory higher in the directory tree.");  
            return;  
          }  
        }  
        //get SuccessPage web variable from request  
        String successPage="";  
        if (file.indexOf("name=\"SuccessPage\"") > 0)  
        {  
          successPage = file.substring(  
            file.indexOf("name=\"SuccessPage\""));  
          //remove carriage return  
          successPage = successPage.substring(  
            successPage.indexOf("\n")+1);  
          //remove carriage return  
          successPage = successPage.substring(  
            successPage.indexOf("\n")+1);  
          //get success page  
          successPage = successPage.substring(0,  
            successPage.indexOf("\n")-1);  
        }  
        //get OverWrite flag web variable from request  
        String overWrite;  
        if (file.indexOf("name=\"OverWrite\"") > 0)  
        {  
          overWrite = file.substring(  
            file.indexOf("name=\"OverWrite\""));  
          //remove carriage return  
          overWrite = overWrite.substring(  
            overWrite.indexOf("\n")+1);  
          //remove carriage return  
          overWrite = overWrite.substring(  
            overWrite.indexOf("\n")+1);  
          //get overwrite flag  
          overWrite = overWrite.substring(0,  
            overWrite.indexOf("\n")-1);  
        }  
        else  
        {  
          overWrite = "false";  
        }  
        //get OverWritePage web variable from request  
        String overWritePage="";  
        if (file.indexOf("name=\"OverWritePage\"") > 0)  
        {  
          overWritePage = file.substring(  
            file.indexOf("name=\"OverWritePage\""));  
          //remove carriage return  
          overWritePage = overWritePage.substring(  
            overWritePage.indexOf("\n")+1);  
          //remove carriage return  
          overWritePage = overWritePage.substring(  
            overWritePage.indexOf("\n")+1);  
          //get overwrite page  
          overWritePage = overWritePage.substring(0,  
            overWritePage.indexOf("\n")-1);  
        }  
        //get filename of upload file  
        String saveFile = file.substring(  
          file.indexOf("filename=\"")+10);  
        saveFile = saveFile.substring(0,  
          saveFile.indexOf("\n"));  
        saveFile = saveFile.substring(  
          saveFile.lastIndexOf("\\")+1,  
          saveFile.indexOf("\""));  
        /*remove boundary markers and other multipart/form-data  
          tags from beginning of upload file section*/  
        int pos; //position in upload file  
        //find position of upload file section of request  
        pos = file.indexOf("filename=\"");  
        //find position of content-disposition line  
        pos = file.indexOf("\n",pos)+1;  
        //find position of content-type line  
        pos = file.indexOf("\n",pos)+1;  
        //find position of blank line  
        pos = file.indexOf("\n",pos)+1;  
        /*find the location of the next boundary marker  
          (marking the end of the upload file data)*/  
        int boundaryLocation = file.indexOf(boundary,pos)-4;  
        //upload file lies between pos and boundaryLocation  
        file = file.substring(pos,boundaryLocation);  
        //build the full path of the upload file  
        String fileName = new String(rootPath + directory +  
          saveFile);  
        //create File object to check for existence of file  
        File checkFile = new File(fileName);  
        if (checkFile.exists())  
        {  
          /*file exists, if OverWrite flag is off, give  
            message and abort*/  
          if (!overWrite.toLowerCase().equals("true"))  
          {  
            if (overWritePage.equals(""))  
            {  
              /*OverWrite HTML page URL not received, respond  
                with generic message*/  
              out.println("Sorry, file already exists.");  
            }  
            else  
            {  
              //redirect client to OverWrite HTML page  
              response.sendRedirect(overWritePage);  
            }  
            return;  
          }  
        }  
        /*create File object to check for existence of  
          Directory*/  
        File fileDir = new File(rootPath + directory);  
        if (!fileDir.exists())  
        {  
          //Directory doesn't exist, create it  
          fileDir.mkdirs();  
        }  
        //instantiate file output stream  
        fileOut = new FileOutputStream(fileName);  
        //write the string to the file as a byte array  
        fileOut.write(file.getBytes(),0,file.length());  
        if (successPage.equals(""))  
        {  
          /*success HTML page URL not received, respond with  
            generic success message*/  
          out.println(successMessage);  
          out.println("File written to: " + fileName);  
        }  
        else  
        {  
          //redirect client to success HTML page  
          response.sendRedirect(successPage);  
        }  
      }  
      else //request is not multipart/form-data  
      {  
        //send error message to client  
        out.println("Request not multipart/form-data.");  
      }  
    }  
    catch(Exception e)  
    {  
      try  
      {  
        //print error message to standard out  
        System.out.println("Error in doPost: " + e);  
        //send error message to client  
        out.println("An unexpected error has occurred.");  
        out.println("Error description: " + e);  
      }  
      catch (Exception f) {}  
    }  
    finally  
    {  
      try  
      {  
        fileOut.close(); //close file output stream  
      }  
      catch (Exception f) {}  
      try  
      {  
        in.close(); //close input stream from client  
      }  
      catch (Exception f) {}  
      try  
      {  
        out.close(); //close output stream to client  
      }  
      catch (Exception f) {}  
 
    }  
  }  
}  
   
   
 
 
--------------------------------------------------------------- 
【 在 fishes (输了你,赢了世界又如何?) 的大作中提到: 】 
                                                 ^^^^^^^^^ 
                                         这个是html中输出中文的编码方式吧 
  你在html页面中显示,这个当然是可以的了 
 插入还是乱码的原因可能是数据库本身的编码方式不对 
 
 
-- 
※ 来源:·BBS 水木清华站 smth.org·[FROM: 202.112.96.134] 

BBS水木清华站∶精华区