将数据从 servlet 发送到小程序:我该如何实现? [英] Sending data from a servlet to applet : How can I implement this?

查看:21
本文介绍了将数据从 servlet 发送到小程序:我该如何实现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将发送 HashMap 对象发送到请求它的小程序.servlet 具有该 HashMap 对象.有没有办法做到这一点?

I want to send send HashMap object to the applet that requested it. A servlet has that HashMap object. Is there a way I can do this ?

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 对象,但我不知道如何将它发送到小程序,我想知道它是否可以发送!

I have made a connection to the servlet and my servlet also has the HashMap object,but I don't know how to send it to the applet and I wonder if it can be sent !

推荐答案

我将利用一些外部库来回答您的问题:Google GsonApache IO 实用程序.

I'm going to make use of some external libraries in order to answer your question: Google Gson and Apache IO Utils.

因此您的 Servlet 中已经有了 HashMap 并希望将其发送到 Applet:

So you already have the HashMap in your Servlet and want to send it to the 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());

并在您的小程序中接收它:

And to receive it in your 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);

就是这样.这只是一个简单的例子,但我希望你能从中有所收获.

And that's it. It's just a simple example but I hope you get something out of it.

当然,您可以手动完成,而不是使用外部库,但这种方式要容易得多.

Of course you could be doing it by hand instead of using external libraries, but this way is much easier.

这篇关于将数据从 servlet 发送到小程序:我该如何实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆