2012-02-10 79 views
0

從servlet檢索響應有問題,我想用下面在J2ME

public String receiveData() { 
     HttpConnection connection = null; 
     String url = "http://localhost:8084/MCastServer/Create"; 
     DataInputStream is = null; 
     OutputStream os = null; 
     StringBuffer stringBuffer = new StringBuffer(); 
     String res = null; 
     try { 
      connection = (HttpConnection) Connector.open(url); 
      connection.setRequestMethod(HttpConnection.GET); 
      connection.setRequestProperty("IF-Modified-Since", "20 Jan 2001 16:19:14 GMT"); 
      connection.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Confirguration/CLDC-1.0"); 
      connection.setRequestProperty("Content-Language", "en-CA"); 
      connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
      os = connection.openOutputStream(); 
      is = connection.openDataInputStream(); 
      System.out.println(url); 
      int ch = 0; 
      while ((ch = is.read()) == -1) { 
       stringBuffer.append((char) ch); 
       System.out.println(stringBuffer); 
      } 
      res = stringBuffer.toString(); 
      System.out.println(res); 
      //ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
     } catch (Exception e) { 
     } finally { 
      try { 
       if (is != null) { 
        is.close(); 
       } 
       if (os != null) { 
        os.close(); 
       } 
       if (connection != null) { 
        connection.close(); 

       } 
       //display.setCurrent(textBox); 
      } catch (Exception e) { 
      } 

     } 
     return res; 
    } 

代碼中檢索從一個servlet到一個MIDlet的迴應,但它一直返回一個空的輸出。我已經搜索並嘗試了各種方法,但它仍然返回相同的結果。 下面是我寫的Servlet

protected void processRequest(HttpServletRequest request, HttpServletResponse response) 
      throws ServletException, IOException { 
     response.setContentType("text/plain"); 
     PrintWriter out = response.getWriter(); 

     String groupNames = "SELECT phone_group_name FROM phone_group_name"; 
     InteractToDB dbCall = new InteractToDB("org.postgresql.Driver"); 
     dbCall.connect("jdbc:postgresql://localhost:5432/mcast", "postgres", "mimi"); 
     out.print(dbCall.getNames()); 
     System.out.println(dbCall.getNames() + " call"); 
     try { 

     } finally { 
      out.close(); 
     } 
    } 
+0

你在哪裏傳遞查詢groupNames來執行?你在服務器的日誌文件中看到了什麼?你能看到System.out.println(dbCall.getNames()+「call」)的輸出。 – Rocky 2012-02-10 10:56:39

+0

如果你從瀏覽器執行你的servlet,你會得到任何輸出嗎? – Kris 2012-02-10 11:03:42

+0

是的。我可以看到來自System.out.println ..和瀏覽器的輸出。 – nnanna 2012-02-10 11:07:52

回答

2

你有一個空的catch塊 - 這不是一個好主意。您應該至少打印堆棧跟蹤。

我也認爲把數據庫代碼放在一個servlet中是一個糟糕的主意。我會編寫一個基於接口的POJO,在沒有servlet的情況下徹底地測試代碼,然後在servlet中調用它的方法。它將問題分解爲更小的問題,並幫助您進行單元測試。

爲什麼每個請求都創建一個連接?爲什麼不使用連接池來攤銷創建連接的成本?

爲什麼在課堂上以純文本方式硬連接信息?如果dbCall爲空,會發生什麼情況?如果拋出SQLException會怎麼樣?

我越看這段代碼,它得到的最差。我現在最好停下來。