需求是这样的:他想通过页面上一个Applet呼叫一个服务器Servlet,而从Servlet产生 一个java对象再传给另外一个Applet,怎么样让Servlet实时地把对象传给Applet这是一个问题,有一个方 案是采用JMS(JavaMessageService),在我以后的文章中会有叙述的.这里我给大家展示一个简单的实现,那 就是让Applet主动访问Servlet,让Servlet返回Java对象.下面给出全部代码和配置,其中Applet部分涵盖 了javascript与Applet的互相调用,对于该部分不感爱好的朋友可以复略. <pre> 第一步,编写需要传递的对象类 /** * Class Person just a demo for translate this class to client * @author: rookie * @datetime: 2002-7-26 */ package exapplet; import java.io.*;
public class Person implements Serializable {//必须实现Serializable接口才能序列化 PRivate String m_Name; private int m_Age;
public Person() { this("",0); } public Person(String name,int age) { this.m_Name = name; this.m_Age = age; } public String getName() { return m_Name; } public int getAge() { return m_Age; }
public class MyApplet extends java.applet.Applet { public void init() { } public void paint(Graphics g) {}
//This method will be call in Html public void invoke() { try { URL url = new URL("http://rookie:8080/workingroom/exapplet/PostToApplet?Action=UpdateObject"); URLConnection urlcon = url.openConnection(); urlcon.connect();
public class MyAppletB extends java.applet.Applet { public void init() { } public void paint(Graphics g) {}
//This method will be call in html public void invoke() { try { URL url = new URL("http://rookie:8080/workingroom/exapplet/PostToApplet?Action=GetObject"); URLConnection urlcon = url.openConnection(); urlcon.connect(); ObjectInputStream ois=new ObjectInputStream(urlcon.getInputStream()); Person p = (Person)ois.readObject(); ois.close(); String[] info = new String[]{"Person Info/n/n-Name: "+p.getName()+"/n-Age : "+p.getAge()}; JSObject.getWindow(this).call("alert",info); } catch (Exception e) { } } }