我試圖發送一些簡單的字符串來測試我的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
那麼......當您使用瀏覽器或curl測試時,您的servlet會返回什麼結果? –
它返回的是簡單格式的頁面,其值爲「String messageToApplet」,僅此而已。 – BMC
如果您只需要在Servlet和Applet之間傳輸一個字符串,那麼使用JSON並不是必需的,而是一個開銷。順便說一句,你需要清理你的代碼。 –