栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Applet-服务器通信,我该怎么办?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Applet-服务器通信,我该怎么办?

只要只有您的applet与服务器通信,就可以使用序列化对象。您只需要在applet
jar和服务器上维护相同版本的对象类。它不是最开放或可扩展的方法,但可以快速达到开发时间,而且非常可靠。

这是一个例子。

实例化与Servlet的连接

URL servletURL = new URL("<URL To your Servlet>");URLConnection servletConnect = servletURL.openConnection();servletConnect.setDoOutput(true); // to allow us to write to the URLservletConnect.setUseCaches(false); // Write the message to the servlet and not from the browser's cacheservletConnect.setRequestProperty("Content-Type","application/x-java-serialized-object");

获取输出流并编写您的对象

MyCustomObject myObject = new MyCustomObject()ObjectOutputStream outputToServlet;outputToServlet = new ObjectOutputStream(servletConnection.getOutputStream());outputToServlet.writeObject(myObject);outputToServlet.flush(); //CleanupoutputToServlet.close();

现在阅读回应

ObjectInputStream in = new ObjectInputStream(servletConnection.getInputStream());MyRespObject myrespObj;try{    myrespObj= (MyRespObject) in.readObject();} catch (ClassNotFoundException e1){    e1.printStackTrace();}in.close();

在您的servlet中

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{  MyRespObject myrespObj= processSomething(request);  response.reset();  response.setHeader("Content-Type", "application/x-java-serialized-object");  ObjectOutputStream outputToApplet;  outputToApplet = new ObjectOutputStream(response.getOutputStream());  outputToApplet.writeObject(myrespObj);  outputToApplet.flush();  outputToApplet.close();}private MyRespObject processSomething(HttpServletRequest request){  ObjectInputStream inputFromApplet = new ObjectInputStream(request.getInputStream());  MyCustomObject myObject = (MyCustomObject) inputFromApplet.readObject();  //Do Something with the object you just passed  MyRespObject myrespObj= new MyRespObject();  return myrespObj;}

只要记住,您传递的两个对象都需要实现可序列化

 public Class MyCustomObject implements java.io.Serializable {


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/573871.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号