从servlet到小程序发送数据:我怎样才能实现呢? [英] Sending data from a servlet to applet : How can I implement this?
问题描述
我想送送的HashMap
对象请求它的小程序。一个servlet有的HashMap
对象。有没有一种方法可以让我做到这一点?
小程序------要求HashMap对象---->的Servlet听这个请求
|
|
Servlet的搜索是HashMap对象
|
|
\\ /
< - 最后发送给小程序------------的Servlet得到HashMap对象
我已经到Servlet的连接,我的servlet还具有的的HashMap 的对象,但我不知道如何将它发送到小程序,我不知道它是否可以发送<! / p>
我要利用一些外部库,以回答你的问题:的谷歌GSON 并的 Apache的IO utils的。
所以,你已经在你的servlet HashMap中,并希望其发送到小程序:
地图&LT;字符串,字符串&GT; MYMAP =新的HashMap&LT;字符串,字符串&GT;(); //或什么
GSON GSON =新GsonBuilder()创建()。
字符串jsonString = gson.toJson(MYMAP);
IOUtils.write(jsonString,resp.getOutputStream()); //其中'RESP'是你的HttpServletResponse
IOUtils.closeQuietly(resp.getOutputStream());
和接收它在你的小程序:
字符串jsonString = IOUtils.toString(conn.getInputStream()); //其中'参数conn是一个HttpURLConnection类
IOUtils.closeQuietly(connection.getInputStream());
GSON GSON =新GsonBuilder()创建()。
//当泛型参与是必须的TypeToken
键入typeOfHashMap =新TypeToken&LT;地图&LT;字符串,字符串&GT;&GT;(){} .getType();
地图&LT;字符串,字符串&GT; MYMAP = gson.fromJson(jsonString,typeOfHashMap);
就是这样。这只是一个简单的例子,但我希望你得到的东西出来。
当然,你可以做手工,而不是使用外部库,但这种方式要容易得多。
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
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 !
I'm going to make use of some external libraries in order to answer your question: Google Gson and Apache IO Utils.
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屋!