Sending data from a servlet to applet : How can I implement this?
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.
How about serializing it and sending it in response ? Consider converting it to JSON or XML.
You can open an URL connection to the servlet if the servlet is in the same server from where the applet was downloaded. The you can read the
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();
Meanwhile in the servlet you write your data back to the client using the HttpServletResponse.
If you need something more "sofisticated", you can use axis as webservice stack in your applet, or include a lightweight REST lib like Jersey. But these solutions force you to use other server component instead a Servlet.
This post will help you:
They both use json-lib to parse/serialize objects from JSON format.
Hope this help.
链接地址: http://www.djcxy.com/p/46070.html上一篇: 将JSON从一个JSP返回到另一个?