当前位置导航:炫浪网>>网络学院>>编程开发>>JAVA教程>>Java进阶

Servlet传送对象给Applet使用


  需求是这样的:他想通过页面上一个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;
  }
  
  //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
  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\\WorkingRoom\\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.writeObject(p);
   oos.close();
   }
  }
  public String getServletInfo()
  {
   return "A simple Servlet!";
  }
  }
  
  
  第三步,实现呼叫Servlet更新对象的Applet
  package exapplet;
  import java.awt.*;
  import java.applet.*;
  import java.io.*;
  import java.net.*;
  import netscape.javascript.*;
  
  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();
   
   DataInputStream dis=new DataInputStream(urlcon.getInputStream());
   String txt = dis.readLine();
   dis.close();
   
   String[] info = new String[]{txt};
   JSObject.getWindow(this).call("alert",info);
   } catch (Exception e) {
   }
  }
  }
  
  
  第四步,实现提取对象的Applet
  package exapplet;
  import java.awt.*;
  import java.applet.*;
  import java.io.*;
  import java.net.*;
  import netscape.javascript.*;
  
  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) {
   }
  }
  }
  
  第五步,配制WebServer(我用的是Tomcat4.0)
  拷贝编译后的MyServlet.class到相应目录下,
  编辑对应的web.xml文件,确保下面的内容正确
  <?xml version="1.0" encoding="UTF-8"?>
  <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN" "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">
  <web-app>
  <servlet>
      <servlet-name>PostToApplet</servlet-name>
      <servlet-class>exapplet.MyServlet</servlet-class>
    </servlet>
  
  <servlet-mapping>
      <servlet-name>
        PostToApplet
      </servlet-name>
      <url-pattern>
        /exapplet/PostToApplet
      </url-pattern>
    </servlet-mapping>
  </web-app>
  
  第六步,编写html文件
  呼叫更新的html
  <HTML>
  <HEAD>
  <TITLE> New Document For Using Applet Call Servlet Update Java Object</TITLE>
  </HEAD>
  
  <BODY>
  Hello This is a Test!<br>
  <APPLET id="obj_applet" align=center code="exapplet.MyApplet" codeBase="." width=400 height=300 name="obj_applet" archive="BV7RFD3P.ZIP"></APPLET>
  <Input type=button value="CallAppletMethod" onclick="callApplet()">
  <Script language=javascript>
  function callApplet()
  {
  obj_applet.invoke();
  }
  </Script>
  </BODY>
  </HTML>
  
  提取对象的html
  <HTML>
  <HEAD>
  <TITLE> New Document For Using Applet </TITLE>
  </HEAD>
  
  <BODY>
  Hello This is a Test!<br>
  <APPLET id="obj_applet" align=center code="exapplet.MyAppletB" codeBase="." width=400 height=300 name="obj_applet" archive="BV7RFD3P.ZIP"></APPLET>
  <Input type=button value="CallAppletMethod" onclick="callApplet()">
  <Script language=javascript>
  function callApplet()
  {
  obj_applet.invoke();
  }
  </Script>
  </BODY>
  </HTML>
  </pre>
  
相关内容
赞助商链接