Servlet传送对象给Applet使用
时间:2011-07-22
需求是这样的:他想通过页面上一个Applet呼叫一个服务器Servlet,而从Servlet产生一个Java对象再传给另外一个Applet,怎么样让Servlet实时地把对象传给Applet这是一个问题,有一个方案是采用JMS(JavaMessageService),在我以后的文章中会有叙述的.这里我给大家展示一个简单的实现,那就是让Applet主动访问Servlet,让Servlet返回Java对象.下面给出全部代码和配置,其中Applet部分涵盖了javascript与Applet的互相调用,对于该部分不感兴趣的朋友可以复略.
第一步,编写需要传递的对象类
/**
* 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;
}
//Serializable接口中声明的方法
private void writeObject(java.io.ObjectOutputStream out)
throws IOException {
out.defaultWriteObject();
}
//Serializable接口中声明的方法
private void readObject(java.io.ObjectInputStream in)
throws IOException, ClassNotFoundException {
in.defaultReadObject();
}
public static void main(String[] args) {
try {
Person p = new Person("Liaoyuan",25);
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File("test.obj")));
oos.writeObject(p);
oos.close();
ObjectInputStream ois = new ObjectInputStream (new FileInputStream(new File("test.obj")));
Person q = (Person)ois.readObject();
ois.close();
System.out.println(q.getName());
System.out.println(q.getAge());
} catch(Exception exp) {
exp.printStackTrace();
}
}
}
Servlet传送对象给Applet使用(2)
时间:2011-07-22
第二步,实现Servlet
package exapplet;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
String fPath = "H:\\XSchool\\Wo***ngRoom\\exapplet\\src\\java.obj";
String act = req.getParameter("Action");
if ( act.equals("UpdateObject") ) {
//创建更新JavaObject
Person p = new Person("Liaoyuan",26);
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File(fPath)));
oos.writeObject(p);
oos.close();
DataOutputStream dos = new DataOutputStream(res.getOutputStream());
dos.writeBytes("Server Java Object Updated OK!");
dos.close();
} else if ( act.equals("GetObject") ) {
//传回对象给Applet
res.setContentType("application/octet-stream");
Person p;
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File(fPath)));
try {
p = (Person)ois.readObject();
} catch (ClassNotFoundException e) {
p = new Person();
}
ois.close();
ObjectOutputStream oos = new ObjectOutputStream(res.getOutputStream());
oos.w
|