You are on page 1of 6

PROGRAM

appservlet.java
import java.io.IOException;
import java.io.*;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class appservlet extends HttpServlet
{
public void doPost(HttpServletRequest req,HttpServletResponse res)throws
ServletException,IOException
{
try
{
res.setContentType("application/x-java-serialized-object");
InputStream in =req.getInputStream();
ObjectInputStream ois=new ObjectInputStream(in);
String echo=(String)ois.readObject();
OutputStream out=res.getOutputStream();
ObjectOutputStream oos=new ObjectOutputStream(out);
oos.writeObject(echo);
oos.flush();
oos.close();
}
catch(Exception e)

{
e.printStackTrace();
}
}
}

appreqservlet.java
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
public class appreqservlet extends Applet implements ActionListener
{
private TextField inputfield=new TextField(10);
private TextField outputfield=new TextField(10);
private TextArea exceptionArea= new TextArea();
public void init()
{
Label title=new Label("Invoking servlet from applet",Label.CENTER);
title.setFont(new Font("sanserif",Font.BOLD,14));
add(title);
add(new Label("Input",Label.RIGHT));
add(inputfield);
Button sendButton=new Button("send");
add(sendButton);

sendButton.addActionListener(this);
add(new Label("output",Label.RIGHT));
add(outputfield);
outputfield.setEditable(false);
add(new Label("Exception",Label.RIGHT));
add(exceptionArea);
exceptionArea.setEditable(false);
}
public void actionPerformed(ActionEvent e)
{
onSendData();
}
private URLConnection getServletConnection()throws
MalformedURLException,IOException
{
URL urlservlet=new URL("http://localhost:8080/examples/servlet/appservlet");
URLConnection con=urlservlet.openConnection();
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
con.setRequestProperty("Content-Type","application/x-java-Serialized-object");
return con;
}

private void onSendData()


{
try{

String input=inputfield.getText();
URLConnection con=getServletConnection();
OutputStream outstream=con.getOutputStream();
ObjectOutputStream oos=new ObjectOutputStream(outstream);
oos.writeObject(input);
oos.flush();
oos.close();
InputStream instr=con.getInputStream();
ObjectInputStream inputfromservlet=new ObjectInputStream(instr);
String result=(String)inputfromservlet.readObject();
inputfromservlet.close();
outputfield.setText(result);
}
catch(Exception ex)
{
ex.printStackTrace();
exceptionArea.setText(ex.toString());
}
}
}
//<applet code="appreqservlet" width="100" height="100"></applet>

OUTPUT

You might also like