之处甚多,望各位指教.
朋友谈论的需求是这样的:他想通过页面上一个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>
中间有错误的地方请指教,zlyperson@163.net
Servlet传送查询记录集给Applet
这篇文章是继<<Servlet传送对象给Applet使用>>后,征对网友的特殊问题写的又一个实例.
现发表出来与大家分享,文中瑕癖之处甚多,望各位指教.
这个问题在csdn上已经有讨论了http://www.csdn.net/expert/topic/971/971710.xml.
具体的需求就不讲了,这里把我的实现步骤详细写下,与<<Servlet传送对象给Applet使用>>中提到的方法
一样.用到的CachedRowSet可以到
http://java.sun.com//Download4?userid=zlyperson&platform=zip&button=continue&config-file=rowset-1_0-ea4.config
去下.还有一个netscape的包,在C:\WINNT\java\Packages\0S0W0NFX.ZIP中.
我也把所需要的包及我的实现代码打成了包,其中包扩了CachedRowSet&netscape&本文.
http://63.210.240.215/rookieport/rowset.jar
下面给出全部代码和配置,其中Applet部分涵盖
了Javascript与Applet的互相调用,对于该部分不感兴趣的朋友可以复略.
<pre>
第一步,实现Servlet
package exapplet;
import java.io.*;
import java.sql.*;
import javax.sql.*;
import sun.jdbc.rowset.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet extends HttpServlet
{
static {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch (Exception e) {
e.printStackTrace();
}
}
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
try {
Connection dbconn = DriverManager.getConnection("jdbc:odbc:BlueSite");
Statement stmt = dbconn.createStatement();
String dbsql = req.getParameter("DBSQL");
ResultSet dbrest = stmt.executeQuery(dbsql);
CachedRowSet crs = new CachedRowSet();
crs.populate(dbrest);
dbrest.close();
stmt.close();
dbconn.close();
file://传回对象给Applet
res.setContentType("application/octet-stream");
ObjectOutputStream oos = new ObjectOutputStream(res.getOutputStream());
oos.writeObject(crs);
oos.close();
} catch (Exception exp) {
exp.printStackTrace();
}
}
public String getServletInfo()
{
return "A simple Servlet!";
}
}
第二步,实现提取对象的Applet
package exapplet;
import java.awt.*;
import java.applet.*;
import java.io.*;
import java.net.*;
import javax.sql.*;
import sun.jdbc.rowset.*;
import netscape.javascript.*;
public class MyAppletB extends java.applet.Applet
{
public void init()
{
}
public void paint(Graphics g)
{}
file://This method will be call in html
public void invoke() {
try {
URL url = new URL("http://Liaoyuan:8080/WorkingRoom/exapplet/PostToApplet?DBSQL=Select%20TopicName,TopicName,TopicName%20from%20Topic");
file://注意url中的空个用%20替代.
URLConnection urlcon = url.openConnection();
urlcon.connect();
ObjectInputStream ois=new ObjectInputStream(urlcon.getInputStream());
CachedRowSet crs = (CachedRowSet)ois.readObject();
ois.close();
while ( crs.next() ) {
JSObject.getWindow(this).call("alert",new String[]{crs.getString(1)});
}
crs.close();
} catch (Exception e) {
}
}
}
第三步,配制WebServer(我用的是Tomcat4.0)
拷贝编译后的MyServlet.class到相应目录下,或者下载我打的包到WEB-INF\lib下
编辑对应的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 </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>
中间有错误的地方请指教,zlyperson@163.net
实在是抱歉,由于作者一时疏忽,在CSDN发表了两篇关于Servlet与Applet通讯的文章
(http://www.csdn.net/develop/read_article.asp?id=14917
http://www.csdn.net/develop/read_article.asp?id=14576),都忘记了策略文件的制作。这也应该算是Applet安全
的基础知识吧,先补充如下:
在作者另一篇文章《Applet直接访问数据库》http://www.csdn.net/develop/read_article.asp?id=15810
一文中讲述过Applet策略文件的制作。制作策略文件有两种方式,一是jdk带的policytool工具,它提供图形界面,为
applet分配权限,另一种是直接编辑策略文件,对于初学者采用第一种方式比较合适,熟练的话,直接编辑比较快速。下面我
就讲讲怎么样直接编辑其策略文件。策略文件的名称为".java.policy",这个文件必须放在用户根目录,在windows2000系统
下,为操作系统所在盘:\Documents and Settings\用户名 目录,比如我的系统装在C盘,用户为管理员,那么这个目录就
是C:\Documents and Settings\Administrator。".java.policy"这个文件不能够在windows2000图形界面创建,可以
打开一个命令行窗口,进入C:\Documents and Settings\Administrator,图形界面下建立一个文本文件,比如命名为
java.policy,然后用dos命令C:\Documents and Settings\Administrator>move java.policy .java.policy
这样就可以了,,然后用个编辑器,打开该文件,输入内容,内容可能类似于下:
grant {
permission java.lang.RuntimePermission "accessClassInPackage.com.microsoft.util";
permission java.lang.RuntimePermission "accessClassInPackage.com.microsoft.jdbc";
permission java.lang.RuntimePermission "accessClassInPackage.com.microsoft.jdbcx";
permission java.net.SocketPermission "192.9.200.52:1433", "connect";
};
保存就可以。第一行到第三行分别是授予applet访问三个包的权限,第四行是授予applet连接192.9.200.52:1433地址端口
的权限。
好了就到此,希望能够对迷途中的网友们有所帮助。