Tuesday, 5 February 2013

Applet-Servlet communication | Java J2EE Tutorial pdf

Applet-Servlet communication

Through Http-Tunneling applets and servlets can communicate. Tunneling is process through which a sub-protocol of HTTP is created, which performs some specific tasks, the sub-protocol that is created for applet servlet communication contains all the information necessary to create an object on the web server. Invoke methods on that object and return the result back to the client. One advantage of using HTTP tunneling is that we do not need to be concerned about transporting the data packets between the client and the server and concentrate more on the specifics of the sub-protocol.
This program open an HTTP connection.
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
public class myapplet extends Applet implements ActionListener
{
TextField tf,tf1;
Button b;
URL url;
URLConnection uc;
public void init()
{
tf= new TextField(20);
b= new Button("Send");
add(tf);
add(b);
add(tf1);b.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
try
{
url=new
URL("http://localhost:8080/mycontext2/myservlet1");
uc=url.openConnection();
uc=setDOOutput(true);
uc=setDOInput(true);
DataOutputStream (uc.getOutputStream());
dout.writeUTF(tf.getText());
dout.flush();
DataInputStream din= new
DataInputStream(uc.getInputStream());
String data=din.readUTF();
tf1.setText(data);
}
catch (Exception e)
{
System.out.println("error"+e);
}
}
}
Writing servlets program
import javax.servlet.*;
import javax.servlet.http.*;
import java.awt.*;
import java.io.*;
public class myservlet extends HttpServlet
{
public void service (HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
try
{
ServletInputStream sin = req.getInputStream(;
DataInputStream din = new DataInputStream(sin);
ServletOutputStream sout= res.getOutputStream();
DataOutputStream dout = new DataOutputtStream(sout);
dout.writeUTF("Message from servlet - "+data);
dout.flush();
}
catch (Exception e)
{
System.out.println("error"+e);
}
}
}
 
HTML file
<HTML><BODY>
<applet code="myapplet" height="500" width="300"></applet>
</BODY></HTML>

No comments: