Applet与servlet通信问题.

03-07-30 e-peng

我在学习通过“对象序列”的技术从Servlet向Applet传输完整的Java对象时,程序总是调试通不过.请各位高人指点.程序清单如下:

///////////////////////////

1.所需要对象序列的对象类.

import java.io.*;

public class DataObject implements Serializable

{

int id;

String name;

int age;

String department;

public DataObject(int id,String name,int age,String department)

{

this.id = id;

this.name = name;

this.age = age;

this.department = department;

}

private void writeObject(ObjectOutputStream out)throws IOException

{

out.writeInt(id);

out.writeInt(age);

out.writeUTF(name);

out.writeUTF(department);

}

private void readObject(ObjectInputStream in) throws IOException

{

id = in.readInt();

age = in.readInt();

name = in.readUTF();

department = in.readUTF();

}

}

///////////////////////////////////////////

2.服务器Servlet清单

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class TestServlet extends HttpServlet

{

public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException

{

//传回对象给Applet

res.setContentType("application/octet-stream");

DataObject dataObj = new DataObject(1,"张三",88,"历史系");

try {

OutputStream out;

ObjectOutputStream objStream;

out = res.getOutputStream();

objStream = new ObjectOutputStream(out);

objStream.writeObject(dataObj);

objStream.close();

} catch (ClassNotFoundException e) {

}

}

public String getServletInfo()

{

return "A simple Servlet!";

}

}

///////////////////////////////////////////

3.客户端applet程序清单.

import java.awt.*;

import java.applet.*;

import java.net.*;

import java.io.*;

public class TestApplet extends Applet {

public void init() {

}

public void paint(Graphics g) {

g.drawString("Welcome to Java!!", 50, 60 );

}

public void invoke() {

try {

DataObject dataObj;

String info;

URL url = new URL("http://192.168.1.130:8080/Servlet/TestServlet");

URLConnection con = url.openConnection();

con.connect();

InputStream in = con.getInputStream();

showStatus("2");

ObjectInputStream objStream;

objStream = new ObjectInputStream(in);

dataObj = (DataObject)objStream.readObject();

// objStream.close();

info = Integer.toString(dataObj.id);

this.getGraphics().drawString(info,50,80);

info = Integer.toString(dataObj.age);

this.getGraphics().drawString(info,50,100);

info = dataObj.name;

this.getGraphics().drawString(info,50,120);

info = dataObj.department;

this.getGraphics().drawString(info,50,140);

}

catch (Exception e) {

}

}

}