Java basics-use Servlet to send objects to Applet

Source: Internet
Author: User

One of my friends talked to me about Servlet and Applet sharing Java objects the day before. I have published this article to share it with you. I hope you can advise me a lot.


A friend is talking about the following requirement: He wants to call a server Servlet through an Applet on the page, and generates a Java object from the Servlet and then transmits it to another Applet, how to let the Servlet pass objects to the Applet in real time is a problem. One solution is to use JMS (JavaMessageService), which will be described in my subsequent articles. here I will show you a simple implementation, that is, let the Applet actively access the Servlet and let the Servlet return Java objects. all the code and configurations are provided below. The Applet section covers
Javascript and Applet calls each other, friends who are not interested in this part can repeat.

& Lt pre & gt
Step 1: Compile the object class to be passed
/**
* 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 {// The Serializable interface must be implemented before serialization.
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;
}

// Method declared in the Serializable Interface
Private void writeObject (java. io. ObjectOutputStream out)
Throws IOException {
Out. defaultWriteObject ();
}

// Method declared in the Serializable Interface
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 ();
}
}
}


Step 2: Implement 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: XSchoolWorkingRoomexappletsrcjava. obj ";

String act = req. getParameter ("Action ");
If (act. equals ("UpdateObject ")){
// Create and update a 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 ")){
// Return the object to the 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! ";
}
}


Step 3: implement the Applet for calling Servlet to update objects
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 ){
}
}
}


Step 4: implement the Applet for extracting objects
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-Name:" + p. getName () + "-Age:" + p. getAge ()};
JSObject. getWindow (this). call ("alert", info );
} Catch (Exception e ){
}
}
}

Step 5: Configure WebServer (I use Tomcat4.0)
Copy the compiled MyServlet. class to the corresponding directory,
Edit the corresponding web. xml file to make sure the following content is correct.
& Lt? Xml version = "1.0" encoding = "UTF-8 "? & Gt
& Lt! DOCTYPE web-app PUBLIC "-// Sun Microsystems, Inc. // DTD Web Application 2.2 //" http://java.sun.com/j2ee/dtds/web-app_2_2.dtd "& gt
& Lt web-app & gt
& Lt servlet & gt
& Lt servlet-name & gtPostToApplet & lt/servlet-name & gt
& Lt servlet-class & gtexapplet. MyServlet & lt/servlet-class & gt
& Lt/servlet & gt

& Lt servlet-mapping & gt
& Lt servlet-name & gt
PostToApplet
& Lt/servlet-name & gt
& Lt url-pattern & gt
/Exapplet/PostToApplet
& Lt/url-pattern & gt
& Lt/servlet-mapping & gt
& Lt/web-app & gt

Step 6: compile an html file
Call updated html
& Lt HTML & gt
& Lt HEAD & gt
& Lt TITLE & gt New Document For Using Applet Call Servlet Update Java Object & lt/TITLE & gt
& Lt/HEAD & gt

& Lt BODY & gt
Hello This is a Test! & Lt br & gt
& Lt APPLET id = "obj_applet" align = center code = "exapplet. myApplet "codeBase = ". "width = 400 height = 300 name =" obj_applet "archive =" BV7RFD3P. ZIP "& gt & lt/APPLET & gt
& Lt Input type = button value = "CallAppletMethod" onclick = "callApplet ()" & gt
& Lt Script language = javascript & gt
Function callApplet ()
{
Obj_applet.invoke ();
}
& Lt/Script & gt
& Lt/BODY & gt
& Lt/HTML & gt

Extract the html of an object
& Lt HTML & gt
& Lt HEAD & gt
& Lt TITLE & gt New Document For Using Applet & lt/TITLE & gt
& Lt/HEAD & gt

& Lt BODY & gt
Hello This is a Test! & Lt br & gt
& Lt APPLET id = "obj_applet" align = center code = "exapplet. myAppletB "codeBase = ". "width = 400 height = 300 name =" obj_applet "archive =" BV7RFD3P. ZIP "& gt & lt/APPLET & gt
& Lt Input type = button value = "CallAppletMethod" onclick = "callApplet ()" & gt
& Lt Script language = javascript & gt
Function callApplet ()
{
Obj_applet.invoke ()

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.