将数据从servlet发送到小程序:我如何实现这一点?
我想发送HashMap
对象到请求它的小程序。 一个servlet具有该HashMap
对象。 有什么办法可以做到这一点?
Applet ------requests HashMap object---->Servlet listens to this request
|
|
Servlet searches that HashMap Object
|
|
/
<--Finally Send this to applet------------ Servlet gets the HashMap object
我已经建立了与servlet的连接,并且我的servlet也有HashMap对象,但是我不知道如何将它发送给applet,我想知道它是否可以发送!
我将利用一些外部库来回答你的问题:Google Gson和Apache IO Utils。
所以你已经有了你的Servlet中的HashMap,并且想把它发送给Applet:
Map<String, String> myMap = new HashMap<String, String>();// or whatever
Gson gson = new GsonBuilder().create();
String jsonString = gson.toJson(myMap);
IOUtils.write(jsonString, resp.getOutputStream());// where 'resp' is your HttpServletResponse
IOUtils.closeQuietly(resp.getOutputStream());
并在您的Applet中接收它:
String jsonString = IOUtils.toString(conn.getInputStream()); // where 'conn' is an HttpURLConnection
IOUtils.closeQuietly(connection.getInputStream());
Gson gson = new GsonBuilder().create();
// The TypeToken is needed when Generics are involved
Type typeOfHashMap = new TypeToken<Map<String, String>>() {}.getType();
Map<String, String> myMap = gson.fromJson(jsonString, typeOfHashMap);
就是这样。 这只是一个简单的例子,但我希望你能从中得到一些东西。
当然你可以用手工来代替使用外部库,但这种方式要容易得多。
如何序列化并发送它作为回应? 考虑将其转换为JSON或XML。
如果servlet与applet的下载位置相同,则可以打开与servlet的URL连接。 你可以阅读
URL site = new URL("your site")
URLConnection urlCon = site.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
urlCon.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
同时在servlet中,使用HttpServletResponse将数据写回客户端。
如果你需要更加“简洁”的东西,你可以在你的applet中使用axis作为web服务栈,或者包含一个像Jersey这样的轻量级REST库。 但是这些解决方案迫使您使用其他服务器组件而不是Servlet。
这篇文章将帮助你:
他们都使用json-lib从JSON格式解析/序列化对象。
希望这个帮助。
链接地址: http://www.djcxy.com/p/46069.html上一篇: Sending data from a servlet to applet : How can I implement this?
下一篇: jQuery autocomplete UI with servlet is not returning any data