2013-01-11 45 views
1

我試圖發送一些簡單的字符串來測試我的servlet和小應用程序之間的數據傳輸 (servlet - > applet,而不是applet - > servlet),使用Json格式和Gson庫。 小程序中產生的字符串應該與原始消息完全相同,但事實並非如此。 我得到9個字符<!DOCTYPE字符串代替。JSON反序列化失敗? (servlet->小程序通信)

編輯:它看起來像servlet返回的HTML網頁,而不是JSON,不是嗎?
edit2:在NetBeans中使用「運行文件」命令激活servlet時,消息在瀏覽器中正確顯示。

能否請你在我的代碼來看看:

的Servlet:

//begin of the servlet code extract 
protected void processRequest(HttpServletRequest request, HttpServletResponse response) 
     throws ServletException, IOException 
{ 
    PrintWriter out = response.getWriter(); 
    try 
    { 
     String action; 
     action = request.getParameter("action"); 
     if ("Transfer".equals(action)) 
     { 
      sendItToApplet(response); 
     } 
    } 
    finally 
    { 
     out.close(); 
    } 
} 

public void sendItToApplet(HttpServletResponse response) throws IOException 
{ 
    String messageToApplet = new String("my message from the servlet to the applet"); 
    String json = new Gson().toJson(messageToApplet); 
    response.setContentType("application/json"); 
    response.setCharacterEncoding("UTF-8"); 

    Writer writer = null; 
    writer = response.getWriter(); 
    writer.write(json); 
    writer.close(); 
} 
//end of the servlet code extract 

小程序:

//begin of the applet code extract 
public void getItFromServlet() throws MalformedURLException, IOException, ClassNotFoundException 
{ 
    URL urlServlet = new URL("http://localhost:8080/Srvlt?action=Transfer"); 
    URLConnection connection = urlServlet.openConnection(); 
    connection.setDoInput(true); 
    connection.setDoOutput(true); 
    connection.setUseCaches(false); 
    connection.setRequestProperty("Content-Type", "application/json"); 

    InputStream inputStream = connection.getInputStream(); 
    BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); 
    JsonReader jr = new JsonReader(br); 
    String retrievedString = new Gson().fromJson(jr, String.class); 
    inputStream.close(); 
    jtextarea1.setText(retrievedString); //jtextarea is to display the received string from the servlet in the applet 
} 
//end of the applet code extract 
+0

那麼......當您使用瀏覽器或curl測試時,您的servlet會返回什麼結果? –

+0

它返回的是簡單格式的頁面,其值爲「String messageToApplet」,僅此而已。 – BMC

+0

如果您只需要在Servlet和Applet之間傳輸一個字符串,那麼使用JSON並不是必需的,而是一個開銷。順便說一句,你需要清理你的代碼。 –

回答

1

的問題是,你不能從你的servlet發送JSON,正如你從你的評論中發現的那樣。這是因爲... Gson對你想要做什麼感到困惑。

如果您在servlet中測試JSON序列化(從toJson()的輸出),您會發現...它沒有做任何事情,只是將String的內容用引號括起來。 JSON基於對象的文本表示(類的字段爲值),並且它肯定不想用String對象來實現;那麼默認的序列化就是將String內容放入生成的JSON中。

編輯補充:爲GSON一個典型的應用會是這樣的:

class MyClass { 
    String message = "This is my message"; 
} 

...

String json = new Gson().toJson(new MyClass()); 

產生的JSON是:

{ 「message」:「這是我的信息」}

+0

我明白了,謝謝。我應該創建一個類併發送它,而不是一個簡單的字符串。現在我得到一個像上面一樣的正確的JSON。 – BMC