R AJALAKSHMI E NGINEERING C OLLEGE
Rajalakshmi Nagar, Thandalam, Chennai – 602 105
Department of Computer Science & Engineering
CS1404 – Internet Programming Lab Lab Manual
Prepared by
B.BHUVANESWARAN
Lecturer / CSE
&
BB / REC - 2 CS1404 - INTERNET PROGRAMMING LABORATORY 0 0 3 100
LIST OF EXPERIMENTS
1. Write programs in Java to demonstrate the use of following components Text fields, buttons, Scrollbar, Choice, List and Check box
2. Write Java programs to demonstrate the use of various Layouts like Flow Layout, Border Layout, Grid layout, Grid bag layout and card layout
3. Write programs in Java to create applets incorporating the following features:
• Create a color palette with matrix of buttons
• Set background and foreground of the control text area by selecting a color from color palette.
• In order to select Foreground or background use check box control as radio buttons
• To set background images
4. Write programs in Java to do the following.
• Set the URL of another server.
• Download the homepage of the server.
• Display the contents of home page with date, content type, and Expiration date. Last modified and length of the home page.
5. Write programs in Java using sockets to implement the following:
• HTTP request
• FTP
• SMTP
• POP3
6. Write a program in Java for creating simple chat application with datagram sockets and datagram packets.
7. Write programs in Java using Servlets:
• To invoke servlets from HTML forms
• To invoke servlets from Applets
8. Write programs in Java to create three-tier applications using servlets
• for conducting on-line examination.
• for displaying student mark list. Assume that student information is available in a database which has been stored in a database server.
9. Create a web page with the following using HTML i. To embed a map in a web page
ii. To fix the hot spots in that map
iii. Show all the related information when the hot spots are clicked.
10. Create a web page with the following.
i. Cascading style sheets.
ii. Embedded style sheets.
iii. Inline style sheets.
iv. Use our college information for the web pages.
- x - x - x -
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="AWTControls" width=500 height=550>
</applet>
*/
public class AWTControls extends Applet implements ActionListener, ItemListener, AdjustmentListener {
String btnMsg = "";
String lstMsg = "";
Button btnHard, btnSoft;
Checkbox chkC, chkCpp, chkJava;
CheckboxGroup cbgCompany;
Checkbox optTcs, optInfosys, optSyntel;
Scrollbar horzCurrent, vertExpected;
TextField txtName, txtPasswd;
TextArea txtaComments = new TextArea("", 5, 30);
Choice chCity;
List lstAccompany;
public void init() {
Label lblName = new Label("Name : ");
Label lblPasswd = new Label("Password : ");
Label lblField = new Label("Field of Interest : ");
Label lblSkill = new Label("Software Skill(s) : ");
Label lblDreamComp = new Label("Dream Company : ");
Label lblCurrent = new Label("Current % : ");
Label lblExpected = new Label("Expected % : ");
Label lblCity = new Label("Preferred City : ");
Label lblAccompany = new Label("Accompanying Persons
% : ");
txtName = new TextField(15);
BB / REC - 4 btnHard = new Button("Hardware") ;
btnSoft = new Button("Software") ;
chkC = new Checkbox("C");
chkCpp = new Checkbox("C++");
chkJava = new Checkbox("Java");
cbgCompany = new CheckboxGroup();
optTcs = new Checkbox("Tata Consultancy Services", cbgCompany, true);
optInfosys = new Checkbox("Infosys", cbgCompany, false);
optSyntel = new Checkbox("Syntel India Ltd", cbgCompany, false);
horzCurrent = new Scrollbar(Scrollbar.VERTICAL, 0, 1, 1, 101);
vertExpected = new Scrollbar(Scrollbar.HORIZONTAL, 0, 1, 1, 101);
chCity = new Choice();
chCity.add("Chennai");
chCity.add("Bangalore");
chCity.add("Hyderabad");
chCity.add("Trivandrum");
lstAccompany = new List(4, true);
lstAccompany.add("Father");
lstAccompany.add("Mother");
lstAccompany.add("Brother");
lstAccompany.add("Sister");
add(lblName);
add(txtName);
add(lblPasswd);
add(txtPasswd);
add(lblField);
add(btnHard);
add(btnSoft);
add(lblSkill);
add(chkC);
add(chkCpp);
add(chkJava);
add(lblDreamComp);
add(optTcs);
add(optInfosys);
add(optSyntel);
add(lblCurrent);
add(horzCurrent);
add(vertExpected);
add(txtaComments);
add(lblCity);
add(chCity);
add(lblAccompany);
add(lstAccompany);
btnHard.addActionListener(this);
btnSoft.addActionListener(this);
chkC.addItemListener(this);
chkCpp.addItemListener(this);
chkJava.addItemListener(this);
optTcs.addItemListener(this);
optInfosys.addItemListener(this);
optSyntel.addItemListener(this);
horzCurrent.addAdjustmentListener(this);
vertExpected.addAdjustmentListener(this);
chCity.addItemListener(this);
lstAccompany.addItemListener(this);
}
public void actionPerformed(ActionEvent ae) { String str = ae.getActionCommand();
if(str.equals("Hardware")) { btnMsg = "Hardware";
}
else if(str.equals("Software")) { btnMsg = "Software";
}
repaint();
}
public void itemStateChanged(ItemEvent ie) { repaint();
}
public void adjustmentValueChanged(AdjustmentEvent ae) { repaint();
}
BB / REC - 6 g.drawString("Software Skill(s) : " , 10, 340);
g.drawString("C : " + chkC.getState(), 10, 360);
g.drawString("C++ : " + chkCpp.getState(), 10, 380);
g.drawString("Java : " + chkJava.getState(), 10, 400);
g.drawString("Dream Company : " +
cbgCompany.getSelectedCheckbox().getLabel(), 10, 420);
g.drawString("Current % : " + horzCurrent.getValue(), 10, 440);
g.drawString("Expected % : " + vertExpected.getValue(), 10, 460);
g.drawString("Name: " + txtName.getText(), 10, 480);
g.drawString("Password: " + txtPasswd.getText(), 10, 500);
g.drawString("Preferred City : " + chCity.getSelectedItem(), 10, 520);
int idx[];
idx = lstAccompany.getSelectedIndexes();
lstMsg = "Accompanying Persons : ";
for(int i=0; i<idx.length; i++)
lstMsg += lstAccompany.getItem(idx[i]) + " ";
g.drawString(lstMsg, 10, 540);
}
}
C:\IPLAB>javac AWTControls.java
C:\IPLAB>appletviewer AWTControls.java
BB / REC - 8 // Ex. No. 02 - A - FlowLayout
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="FlowLayoutDemo" width=300 height=300>
</applet>
*/
public class FlowLayoutDemo extends Applet implements ItemListener {
Checkbox chkWinXP, chkWin2003, chkRed, chkFed;
public void init() {
setLayout(new FlowLayout(FlowLayout.LEFT));
Label lblOS = new Label("Operating System(s) Knowledge :- ");
chkWinXP = new Checkbox("Windows XP");
chkWin2003 = new Checkbox("Windows 2003 Server");
chkRed = new Checkbox("Red Hat Linux");
chkFed = new Checkbox("Fedora");
add(lblOS);
add(chkWinXP);
add(chkWin2003);
add(chkRed);
add(chkFed);
chkWinXP.addItemListener(this);
chkWin2003.addItemListener(this);
chkRed.addItemListener(this);
chkFed.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie) { repaint();
}
public void paint(Graphics g) {
g.drawString("Operating System(s) Knowledge : ", 10, 130);
g.drawString("Windows Xp : " + chkWinXP.getState(), 10, 150);
g.drawString("Windows 2003 Server : " + chkWin2003.getState(), 10, 170);
10, 190);
g.drawString("Fedora : " + chkFed.getState(), 10, 210);
}
}
Output:-
C:\IPLAB>javac FlowLayoutDemo.java
C:\IPLAB>appletviewer FlowLayoutDemo.java
BB / REC - 10 // Ex. No. 02 - B - BorderLayout
import java.awt.*;
import java.applet.*;
import java.util.*;
/*
<applet code="BorderLayoutDemo" width=500 height=250>
</applet>
*/
public class BorderLayoutDemo extends Applet {
public void init() {
setLayout(new BorderLayout());
add(new Button("Rajalakshmi Engineering College"), BorderLayout.NORTH);
add(new Label("Rajalakshmi Nagar, Thandalam, Chennai - 602 105"),
BorderLayout.SOUTH);
add(new Button("Mission"), BorderLayout.EAST);
add(new Button("Vision"), BorderLayout.WEST);
String msg = "Rajalakshmi Engineering College was established \n" +
"in the year 1997 under the aegis of Rajalakshmi Educational Trust \n" +
"whose members have had consummate experience in the fields of \n" +
"education and industry.";
add(new TextArea(msg), BorderLayout.CENTER);
}
}
C:\IPLAB>javac BorderLayoutDemo.java
C:\IPLAB>appletviewer BorderLayoutDemo.java
BB / REC - 12 // Ex. No. 02 - C - GridLayout
import java.awt.*;
import java.applet.*;
/*
<applet code="GridLayoutDemo" width=400 height=200>
</applet>
*/
public class GridLayoutDemo extends Applet { public void init() {
setLayout(new GridLayout(4, 4));
setFont(new Font("SansSerif", Font.BOLD, 24));
for(int i = 1; i <=15 ; i++) { add(new Button("" + i));
} }
}
Output:-
C:\IPLAB>javac GridLayoutDemo.java
C:\IPLAB>appletviewer GridLayoutDemo.java
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="CardLayoutDemo" width=300 height=100>
</applet>
*/
public class CardLayoutDemo extends Applet implements ActionListener, MouseListener {
Checkbox chkVB, chkASP, chkJ2EE, chkJ2ME;
Panel pnlTech;
CardLayout cardLO;
Button btnMicrosoft, btnJava;
public void init() {
btnMicrosoft = new Button("Microsoft Products");
btnJava = new Button("Java Products");
add(btnMicrosoft);
add(btnJava);
cardLO = new CardLayout();
pnlTech = new Panel();
pnlTech.setLayout(cardLO);
chkVB = new Checkbox("Visual Basic");
chkASP = new Checkbox("ASP");
chkJ2EE = new Checkbox("J2EE");
chkJ2ME = new Checkbox("J2ME");
Panel pnlMicrosoft = new Panel();
pnlMicrosoft.add(chkVB);
pnlMicrosoft.add(chkASP);
Panel pnlJava = new Panel();
pnlJava.add(chkJ2EE);
pnlJava.add(chkJ2ME);
pnlTech.add(pnlMicrosoft, "Microsoft");
BB / REC - 14 btnMicrosoft.addActionListener(this);
btnJava.addActionListener(this);
addMouseListener(this);
}
public void mousePressed(MouseEvent me) { cardLO.next(pnlTech);
}
public void mouseClicked(MouseEvent me) { }
public void mouseEntered(MouseEvent me) { }
public void mouseExited(MouseEvent me) { }
public void mouseReleased(MouseEvent me) { }
public void actionPerformed(ActionEvent ae) { if(ae.getSource() == btnMicrosoft) {
cardLO.show(pnlTech, "Microsoft");
}
else {
cardLO.show(pnlTech, "Java");
} }
}
C:\IPLAB>javac CardLayoutDemo.java
C:\IPLAB>appletviewer CardLayoutDemo.java
BB / REC - 16 // Ex. No. 03 - Color Palette
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="ColorApplet" width=500 height=500>
<param name = "recmb" value = "recmb.jpg">
<param name = "recwsb" value = "recwsb.jpg">
</applet>
*/
public class ColorPalette extends Applet implements ActionListener, ItemListener {
Button btnRed, btnGreen, btnBlue;
String str = "";
CheckboxGroup cbgColor;
CheckboxGroup cbgImage;
Checkbox optFore, optBack;
Checkbox optMb, optWsb;
Image imgMb, imgWsb;
TextArea txtaComments = new TextArea("", 5, 30);
public void init() {
setLayout(new GridLayout(4, 3));
cbgColor = new CheckboxGroup();
cbgImage = new CheckboxGroup();
Label lblColor = new Label("Select the Area :") ; Label lblImage = new Label("Select the Image :") ;
optFore = new Checkbox("Foreground", cbgColor, true);
optBack = new Checkbox("Background", cbgColor, false);
optMb = new Checkbox("REC-Main Block", cbgImage, true);
optWsb = new Checkbox("REC-Workshop Block", cbgImage, false);
btnRed = new Button("Red");
btnGreen = new Button("Green");
btnBlue = new Button("Blue");
imgMb = getImage(getDocumentBase(), getParameter("recmb"));
imgWsb = getImage(getDocumentBase(), getParameter("recwsb"));
add(btnRed);
add(btnGreen);
add(btnBlue);
add(lblColor);
add(optFore);
add(optBack);
add(lblImage);
add(optMb);
add(optWsb);
add(txtaComments);
optFore.addItemListener(this);
optBack.addItemListener(this);
optMb.addItemListener(this);
optWsb.addItemListener(this);
btnRed.addActionListener(this);
btnGreen.addActionListener(this);
btnBlue.addActionListener(this);
}
public void actionPerformed(ActionEvent ae) {
str = cbgColor.getSelectedCheckbox().getLabel() ; if(ae.getSource() == btnRed &&
str.equals("Background")) {
txtaComments.setBackground(Color.red);
}
if(ae.getSource() == btnRed &&
str.equals("Foreground")) {
txtaComments.setForeground(Color.red);
}
if(ae.getSource() == btnGreen &&
str.equals("Background")) {
txtaComments.setBackground(Color.green);
}
if(ae.getSource() == btnGreen &&
str.equals("Foreground")) {
txtaComments.setForeground(Color.green);
}
BB / REC - 18 if(ae.getSource() == btnBlue &&
str.equals("Foreground")) {
txtaComments.setForeground(Color.blue);
}
}
public void itemStateChanged(ItemEvent ie) { repaint();
}
public void paint(Graphics g) { if(optMb.getState() == true)
g.drawImage(imgMb, 200, 400, this) ; if(optWsb.getState() == true)
g.drawImage(imgWsb, 200, 400, this) ; }
}
C:\IPLAB>javac ColorPalette.java
C:\IPLAB>appletviewer ColorPalette.java
BB / REC - 20 // Ex. No. 04 – B - Download the Home Page of the Server
import java.net.*;
import java.io.*;
public class SourceViewer {
public static void main (String[] args) { if (args.length > 0) {
try {
URL u = new URL(args[0]);
InputStream in = u.openStream( );
in = new BufferedInputStream(in);
Reader r = new InputStreamReader(in);
int c;
while ((c = r.read( )) != -1) {
System.out.print((char) c);
} }
catch (MalformedURLException ex) {
System.err.println(args[0] +
" is not a parseable URL");
}
catch (IOException ex) {
System.err.println(ex);
} } }
}
C:\IPLAB>javac SourceViewer.java
C:\IPLAB>java SourceViewer http://172.16.0.15
BB / REC - 22 // Ex. No. 04 – C - Display the Contents of Home Page
import java.net.*;
import java.io.*;
import java.util.*;
public class HeaderViewer {
public static void main(String args[]) { for (int i=0; i < args.length; i++) { try {
URL u = new URL(args[0]);
URLConnection uc = u.openConnection( );
System.out.println("Content-type: " + uc.getContentType( ));
System.out.println("Content-encoding: " + uc.getContentEncoding( ));
System.out.println("Date: " + new Date(uc.getDate( )));
System.out.println("Last modified: " + new Date(uc.getLastModified( )));
System.out.println("Expiration date: " + new Date(uc.getExpiration( )));
System.out.println("Content-length: " + uc.getContentLength( ));
}
catch (MalformedURLException ex) {
System.err.println(args[i] +
" is not a URL I understand");
}
catch (IOException ex) {
System.err.println(ex);
}
System.out.println( );
} }
}
C:\IPLAB>javac HeaderViewer.java
C:\IPLAB>javac HeaderViewer.java
C:\IPLAB>java HeaderViewer http://172.16.0.15/default.htm Content-type: text/html
Content-encoding: null
Date: Fri Sep 19 16:22:51 IST 2008
Last modified: Wed Sep 17 11:34:21 IST 2008 Expiration date: Thu Jan 01 05:30:00 IST 1970 Content-length: 16118
C:\IPLAB>
BB / REC - 24 // Ex. No. 05 – A – HTTP Request
import java.net.*;
import java.io.*;
import javax.swing.*;
import java.awt.*;
public class SourceViewer3 {
public static void main (String[] args) { for (int i = 0; i < args.length; i++) { try {
URL u = new URL(args[i]);
HttpURLConnection uc = (HttpURLConnection) u.openConnection( );
int code = uc.getResponseCode( );
String response = uc.getResponseMessage( );
System.out.println("HTTP/1.x " + code + " " + response);
for (int j = 1; ; j++) {
String header = uc.getHeaderField(j);
String key = uc.getHeaderFieldKey(j);
if (header == null || key == null) break;
System.out.println(uc.getHeaderFieldKey(j) + ": " + header);
}
InputStream in = new
BufferedInputStream(uc.getInputStream( ));
Reader r = new InputStreamReader(in);
int c;
while ((c = r.read( )) != -1) { System.out.print((char) c);
} }
catch (MalformedURLException ex) {
System.err.println(args[0] + " is not a parseable URL");
}
catch (IOException ex) { System.err.println(ex);
} } } }
C:\IPLAB>javac SourceViewer3.java
C:\IPLAB>java SourceViewer http://172.16.0.15/default.htm
HTTP/1.x 200 OK
Key Content-Length: 14895 Key Content-Type: text/html
Key Last-Modified: Sat, 20 Sep 2008 05:55:01 GMT Key Accept-Ranges: bytes
Key ETag: "80a87d6be51ac91:489"
Key Server: Microsoft-IIS/6.0 Key X-Powered-By: ASP.NET
Key Date: Mon, 06 Oct 2008 02:59:26 GMT
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
. . .
</html>
BB / REC - 26 // Ex. No. 05 – B - SMTP
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
public class Assimilator {
public static void main(String[] args) {
try {
Properties props = new Properties( );
props.put("mail.host", "mail.rajalakshmi.org");
Session mailConnection =
Session.getInstance(props, null);
Message msg = new MimeMessage(mailConnection);
Address billgates = new
InternetAddress("[email protected]",
"Bill Gates");
Address bhuvangates = new
InternetAddress("[email protected]"
);
msg.setContent("Wish You a Happy New Year 2008", "text/plain");
msg.setFrom(billgates);
msg.setRecipient(Message.RecipientType.TO, bhuvangates);
msg.setSubject("Greetings");
Transport.send(msg);
}
catch (Exception ex) {
ex.printStackTrace( );
} }
}
C:\IPLAB>javac Assimilator.java
C:\IPLAB>java Assimilator
BB / REC - 28
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
import java.io.*;
public class POP3Client {
public static void main(String[] args) { Properties props = new Properties( );
String host = "mail.rajalakshmi.org";
String username = "[email protected]";
String password = "reccse";
String provider = "pop3";
try {
Session session =
Session.getDefaultInstance(props, null);
Store store = session.getStore(provider);
store.connect(host, username, password);
Folder inbox = store.getFolder("INBOX");
if (inbox == null) {
System.out.println("No INBOX");
System.exit(1);
}
inbox.open(Folder.READ_ONLY);
Message[] messages = inbox.getMessages( );
for (int i = 0; i < messages.length; i++) { System.out.println("---
Message " + (i+1) + " ---");
messages[i].writeTo(System.out);
}
inbox.close(false);
store.close( );
}
catch (Exception ex) {
ex.printStackTrace( );
} }
}
BB / REC - 30 Output:-
C:\IPLAB>javac POP3Client.java
C:\IPLAB>java POP3Client
// FileServer.java
import java.net.*;
import java.io.*;
public class FileServer {
ServerSocket serverSocket;
Socket socket;
int port;
FileServer() {
this(9999);
}
FileServer(int port) {
this.port = port;
}
void waitForRequests() throws IOException {
serverSocket = new ServerSocket(port);
while (true)
{
System.out.println("Server Waiting...");
socket = serverSocket.accept();
System.out.println("Request Received From " + socket.getInetAddress()+"@"+socket.getPort());
new FileServant(socket).start();
System.out.println("Service Thread Started");
} }
public static void main(String[] args) {
try {
new FileServer().waitForRequests();
}
catch (IOException e) {
e.printStackTrace();
} }
}
BB / REC - 32 // FileClient.java
import java.net.*;
import java.io.*;
public class FileClient {
String fileName;
String serverAddress;
int port;
Socket socket;
FileClient() {
this("localhost", 9999, "Sample.txt");
}
FileClient(String serverAddress, int port, String fileName)
{
this.serverAddress = serverAddress;
this.port = port;
this.fileName = fileName;
}
void sendRequestForFile() throws UnknownHostException, IOException
{
socket = new Socket(serverAddress, port);
System.out.println("Connected to Server...");
PrintWriter writer = new PrintWriter(new
OutputStreamWriter(socket.getOutputStream()));
writer.println(fileName);
writer.flush();
System.out.println("Request Sent...");
getResponseFromServer();
socket.close();
}
void getResponseFromServer() throws IOException {
BufferedReader reader = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
String response = reader.readLine();
if(response.trim().toLowerCase().equals("filenotfound")) {
System.out.println(response);
return; }
else {
BufferedWriter fileWriter = new BufferedWriter(new
FileWriter("Recdfile.txt"));
do
fileWriter.write(response);
fileWriter.flush();
}while((response=reader.readLine())!=null);
fileWriter.close();
} }
public static void main(String[] args) {
try {
new FileClient().sendRequestForFile();
}
catch (UnknownHostException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
} }
}
BB / REC - 34 // FileServent.java
import java.net.*;
import java.io.*;
public class FileServant extends Thread {
Socket socket;
String fileName;
BufferedReader in;
PrintWriter out;
FileServant(Socket socket) throws IOException {
this.socket = socket;
in = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
out = new PrintWriter(new
OutputStreamWriter(socket.getOutputStream()));
}
public void run() {
try {
fileName = in.readLine();
File file = new File(fileName);
if (file.exists())
{
BufferedReader fileReader = new
BufferedReader(new FileReader(fileName));
String content = null;
while ((content = fileReader.readLine())
!=
null) {
out.println(content);
out.flush();
}
System.out.println("File Sent...");
}
else {
System.out.println("Requested File Not Found...");
out.println("File Not Found");
out.flush();
}
socket.close();
System.out.println("Connection Closed!");
}
catch (FileNotFoundException e)
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
} }
public static void main(String[] args) {
} }
BB / REC - 36 Output:
C:\IPLAB>javac FileServer.java C:\IPLAB>javac FileClient.java C:\IPLAB>javac FileServent.java
C:\IPLAB>copy con Sample.txt Welcome to FTP
C:\IPLAB>java FileServer
Server Waiting...
C:\IPLAB>java FileClient
Connected to Server...
Request Sent...
C:\IPLAB>java FileServer
Server Waiting...
Request Received From /127.0.0.1@2160 Service Thread Started
Server Waiting...
File Sent...
Connection Closed!
C:\IPLAB>type Recdfile.txt Welcome to FTP
import java.io.*;
import java.net.*;
class UDPServer {
public static DatagramSocket serversocket;
public static DatagramPacket dp;
public static BufferedReader dis;
public static InetAddress ia;
public static byte buf[] = new byte[1024];
public static int cport = 789,sport=790;
public static void main(String[] a) throws IOException {
serversocket = new DatagramSocket(sport);
dp = new DatagramPacket(buf,buf.length);
dis = new BufferedReader
(new InputStreamReader(System.in));
ia = InetAddress.getLocalHost();
System.out.println("Server is Running...");
while(true) {
serversocket.receive(dp);
String str = new String(dp.getData(), 0, dp.getLength());
if(str.equals("STOP")) {
System.out.println("Terminated...");
break;
}
System.out.println("Client: " + str);
String str1 = new String(dis.readLine());
buf = str1.getBytes();
serversocket.send(new
DatagramPacket(buf,str1.length(), ia, cport));
} }
}
BB / REC - 38 Output:-
C:\IPLAB>javac UDPServer.java
C:\IPLAB>java UDPServer
Server is Running...
Client: Hello
Welcome
Terminated...
import java.io.*;
import java.net.*;
class UDPClient {
public static DatagramSocket clientsocket;
public static DatagramPacket dp;
public static BufferedReader dis;
public static InetAddress ia;
public static byte buf[] = new byte[1024];
public static int cport = 789, sport = 790;
public static void main(String[] a) throws IOException {
clientsocket = new DatagramSocket(cport);
dp = new DatagramPacket(buf, buf.length);
dis = new BufferedReader(new
InputStreamReader(System.in));
ia = InetAddress.getLocalHost();
System.out.println("Client is Running... Type 'STOP' to Quit");
while(true) {
String str = new String(dis.readLine());
buf = str.getBytes();
if(str.equals("STOP")) {
System.out.println("Terminated...");
clientsocket.send(new
DatagramPacket(buf,str.length(), ia, sport));
break;
}
clientsocket.send(new DatagramPacket(buf, str.length(), ia, sport));
clientsocket.receive(dp);
String str2 = new String(dp.getData(), 0, dp.getLength());
System.out.println("Server: " + str2);
} }
}
BB / REC - 40 Output:-
C:\IPLAB>javac UDPClient.java
C:\IPLAB>java UDPClient
Client is Running... Type ‘STOP’ to Quit
Hello
Server: Welcome
STOP
Terminated...
<!-- PostParam.html -->
<HTML>
<BODY>
<CENTER>
<FORM name = "postparam" method = "post"
action="http://localhost:8080/PostParam/PostParam">
<TABLE>
<tr>
<td><B>Employee </B> </td>
<td><input type = "textbox" name="ename" size="25"
value=""></td>
</tr>
<tr>
<td><B>Phone </B> </td>
<td><input type = "textbox" name="phoneno" size="25"
value=""></td>
</tr>
</TABLE>
<INPUT type = "submit" value="Submit">
</body>
</html>
BB / REC - 42 // Ex. No. 07 – A - Invoking Servlets from HTML Forms
import java.io.*;
import java.util.*;
import javax.servlet.*;
public class PostParam extends GenericServlet { public void service(ServletRequest
request,ServletResponse response) throws ServletException, IOException {
PrintWriter pw = response.getWriter();
Enumeration e = request.getParameterNames();
while(e.hasMoreElements()) {
String pname = (String)e.nextElement();
pw.print(pname + " = ");
String pvalue = request.getParameter(pname);
pw.println(pvalue);
}
pw.close();
} }
D:\PostParam\WEB-INF\classes>javac PostParam.java
D:\PostParam\WEB-INF>type web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<display-name>Welcome to Tomcat</display-name>
<description>
Welcome to Tomcat </description>
<!-- JSPC servlet mappings start -->
<servlet>
<servlet-name>PostParam</servlet-name>
<servlet-class>PostParam</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>PostParam</servlet-name>
<url-pattern>/PostParam</url-pattern>
</servlet-mapping>
<!-- JSPC servlet mappings end -->
</web-app>
D:\PostParam>jar –cvf PostParam.war . added manifest
adding: PostParam.html(in = 410) (out= 220)(deflated 46%) adding: WEB-INF/(in = 0) (out= 0)(stored 0%)
adding: WEB-INF/classes/(in = 0) (out= 0)(stored 0%) adding: WEB-INF/classes/PostParam.class(in = 1156) (out=
643)(deflated 44%)
adding: WEB-INF/classes/PostParam.java(in = 519) (out=
272)(deflated 47%)
BB / REC - 44 Step 1: Open Web Browser and type
Step 2: http://localhost:8080 Step 3: Select Tomcat Manager
Step 4: Deploy the war file and Run
BB / REC - 46
<!-- Ex. No. 07 – B – invoking Servlets from Applets -->
<!—Ats.html -->
<HTML>
<BODY>
<CENTER>
<FORM name = "students" method = "post"
action="http://localhost:8080/Student/Student">
<TABLE>
<tr>
<td><B>Roll No. </B> </td>
<td><input type = "textbox" name="rollno" size="25"
value=""></td>
</tr>
</TABLE>
<INPUT type = "submit" value="Submit">
</FORM>
<CENTER>
</BODY>
</HTML>
AppletToServlet.java
import java.io.*;
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import java.net.*;
/* <applet code="AppletToServlet" width="300"
height="300"></applet> */
public class AppletToServlet extends Applet implements ActionListener {
TextField toSend;
TextField toGet;
Label l1;
Label l2;
Button send;
Intermediate s;
String value;
ObjectInputStream is;
ObjectOutputStream os;
public void init(){
toSend=new TextField(10);
add(toSend);
toGet=new TextField(10);
add(toGet);
l1=new Label("value sent");
l2=new Label("value received");
add(l1);
add(l2);
send=new Button("Click to send to servlet");
send.addActionListener(this);
add(send);
validate();
s=new Intermediate();
}
public void actionPerformed(ActionEvent e){
value=toSend.getText();
BB / REC - 48 public void sendToServlet(){
try {
URL url=new
URL("http://localhost:8080"+"/servlet/ServletToApple t");
URLConnection con=url.openConnection();
s.setFname(value);
writeStuff(con,s);
s=new Intermediate();
Intermediate p=readStuff(con);
if(p!=null){
value=p.getFname();
toGet.setText("value:"+value);
validate();
} }
catch(Exception e){
System.out.println(e);
} }
public void writeStuff(URLConnection connection, Intermediate value){
try{
connection.setUseCaches(false);
connection.setRequestProperty("CONTENT_TYPE",
"application/octet-stream");
connection.setDoInput(true);
connection.setDoOutput(true);
os=new
ObjectOutputStream(connection.getOutputStream());
os.writeObject(value);
os.flush();
os.close();
}
catch(Exception y){}
}
public Intermediate readStuff(URLConnection connection){
Intermediate s=null;
try{
is=new
ObjectInputStream(connection.getInputStream());
s=(Intermediate)is.readObject();
is.close();
}
catch(Exception e){}
return s;
} }
// Ex. No. 07 – B – Invoking Servlets from Applets – ServletToApplet.java
import java.util.*;
import java.io.*;
import javax.servlet.http.*;
import javax.servlet.*;
public class ServletToApplet extends HttpServlet {
String valueGotFromApplet;
public void init(ServletConfig config) throws ServletException
{
System.out.println("Servlet entered");
super.init();
}
public void service(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
try {
System.out.println("service entered");
ObjectInputStream ois=new
ObjectInputStream(request.getInputStream() );
Intermediate ss=(Intermediate)ois.readObject();
valueGotFromApplet=ss.getFname();
System.out.println(valueGotFromApplet);
response.setContentType("application/octet- stream");
ObjectOutputStream oos=new
ObjectOutputStream(response.getOutputStream());
oos.writeObject(ss);
oos.flush();
oos.close();
}
catch(Exception e){System.out.println(e);}
}
BB / REC - 50 // Ex. No. 07 – B – Invoking Servlets from Applets –
Intermediate.java import java.io.*;
public class Intermediate implements Serializable{
String fname;
public String getFname(){
return fname;
}
public void setFname(String s){
fname=s;
} }
D:\servlet\WEB-INF\classes>javac AppletToServlet.java
D:\servlet\WEB-INF\classes>javac ServlettoApplet.java
D:\servlet\WEB-INF>type web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<display-name>Welcome to Tomcat</display-name>
<description>
Welcome to Tomcat </description>
<!-- JSPC servlet mappings start -->
<servlet>
<servlet-name>ServletToApplet</servlet-name>
<servlet-class>ServletToApplet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServletToApplet</servlet-name>
<url-pattern>/ServletToApplet</url-pattern>
</servlet-mapping>
<!-- JSPC servlet mappings end -->
</web-app>
BB / REC - 52 D:\servlet>jar -cvf ServletToApplet.war .
added manifest
adding: ats.html(in = 97) (out= 76)(deflated 21%) adding: WEB-INF/(in = 0) (out= 0)(stored 0%)
adding: WEB-INF/classes/(in = 0) (out= 0)(stored 0%)
adding: WEB-INF/classes/AppletToServlet.class(in = 3055) (out=
1627)(deflated 46
%)
adding: WEB-INF/classes/AppletToServlet.java(in = 1952) (out=
776)(deflated 60%)
adding: WEB-INF/classes/Intermediate.class(in = 433) (out=
273)(deflated 36%)
adding: WEB-INF/classes/Intermediate.java(in = 188) (out=
126)(deflated 32%)
adding: WEB-INF/classes/ServletToApplet.class(in = 1660) (out=
859)(deflated 48%
)
adding: WEB-INF/classes/ServletToApplet.java(in = 975) (out=
424)(deflated 56%)
adding: WEB-INF/web.xml(in = 698) (out= 315)(deflated 54%)
Step 1: Open Web Browser and type Step 2: http://localhost:8080 Step 3: Select Tomcat Manager
Step 4: Deploy the war file and Run
<!—Student.html -->
<HTML>
<BODY>
<CENTER>
<FORM name = "students" method = "post"
action="http://localhost:8080/Student/Student">
<TABLE>
<tr>
<td><B>Roll No. </B> </td>
<td><input type = "textbox" name="rollno" size="25"
value=""></td>
</tr>
</TABLE>
<INPUT type = "submit" value="Submit">
</FORM>
<CENTER>
</BODY>
</HTML>
BB / REC - 54 // Ex. No. 08 – B – Displaying Student Details
import javax.servlet.http.*;
import java.io.*;
import javax.servlet.*;
import java.sql.*;
public class Student extends HttpServlet { Connection dbConn ;
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver") ; dbConn =
DriverManager.getConnection("jdbc:odbc:Student"
,"","") ; }
catch(ClassNotFoundException e) {
System.out.println(e);
}
catch(Exception e) {
System.out.println(e);
}
res.setContentType("text/html");
PrintWriter out = res.getWriter();
String mrollno = req.getParameter("rollno") ;
try {
PreparedStatement ps =
dbConn.prepareStatement("select * from stud where rollno = ?") ;
ps.setString(1, mrollno) ; ResultSet rs = ps.executeQuery() ; out.println("<html>");
out.println("<body>");
out.println("<head>");
out.println("<title>Hello World!</title>");
out.println("</head>");
out.println("<body>");
out.println("<table border = 1>");
{
out.println("<tr><td>Roll No. : </td>");
out.println("<td>" + rs.getString(1) +
"</td></tr>");
out.println("<tr><td>Name : </td>");
out.println("<td>" + rs.getString(2) +
"</td></tr>");
out.println("<tr><td>Branch : </td>");
out.println("<td>" + rs.getString(3) +
"</td></tr>");
out.println("<tr><td>10th Mark : </td>");
out.println("<td>" + rs.getString(4) +
"</td></tr>");
out.println("<tr><td>12th Mark : </td>");
out.println("<td>" + rs.getString(5) +
"</td></tr>");
}
out.println("</table>");
out.println("</body>");
out.println("</html>");
}
catch (Exception e) {
System.out.println(e);
} }
}
BB / REC - 56 Database Structure Æ Student.mdb
Records
D:\PostParam\WEB-INF>type web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<display-name>Welcome to Tomcat</display-name>
<description>
Welcome to Tomcat </description>
<!-- JSPC servlet mappings start -->
<servlet>
<servlet-name>Student</servlet-name>
<servlet-class>Student</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Student</servlet-name>
<url-pattern>/Student</url-pattern>
</servlet-mapping>
<!-- JSPC servlet mappings end -->
</web-app>
D:\PostParam>jar –cvf Student.war . D:\Student>jar -cvf Student.war . added manifest
adding: Student.html(in = 299) (out= 204)(deflated 31%) adding: WEB-INF/(in = 0) (out= 0)(stored 0%)
adding: WEB-INF/classes/(in = 0) (out= 0)(stored 0%) adding: WEB-INF/classes/Student.class(in = 2658) (out=
1358)(deflated 48%)
adding: WEB-INF/classes/Student.java(in = 1849) (out=
636)(deflated 65%)
adding: WEB-INF/classes/Student.mdb(in = 139264) (out=
BB / REC - 58 Step 1: Create ODBC connection for the database
Step 2: Open Web Browser and type Step 3: http://localhost:8080 Step 4: Select Tomcat Manager
Step 5: Deploy the war file and Run
BB / REC - 60
<!-- Ex. No. 09 - Creating and Using Image Maps -->
<!-- ImageMap.html -->
<HTML>
<HEAD>
<TITLE>Image Map</TITLE>
</HEAD>
<BODY>
<MAP id = "picture">
<AREA href = "TamilNadu.html" shape = "circle"
coords = "170, 490, 30" alt = "Tamil Nadu" />
<AREA href = "Karnataka.html" shape = "rect"
coords = "115, 390, 150, 450" alt = "Karnataka" />
<AREA href = "AndhraPradesh.html" shape = "poly"
coords = "165, 355, 200, 355, 220, 380, 170, 425, 165, 355" alt = "Andhra Pradesh" />
<AREA href = "Kerala.html" shape = "poly"
coords = "115, 455, 160, 470, 140, 485, 150, 505, 150, 530, 135, 500, 115, 455" alt = "Kerala" />
</MAP>
<IMG src = "India.Jpg" alt = "India" usemap = "#picture" />
</BODY>
</HTML>
<HTML>
<HEAD>
<TITLE>About Tamil Nadu</TITLE>
</HEAD>
<BODY>
<CENTER><H1>Tamil Nadu</H1></CENTER>
<HR>
<UL>
<LI>Area : 1,30,058 Sq. Kms.</LI>
<LI>Capital : Chennai</LI>
<LI>Language : Tamil</LI>
<LI>Population : 6,21,10,839</LI>
</UL>
</BODY>
</HTML>
<!-- AndhraPradesh.html -->
<HTML>
<HEAD>
<TITLE>About Andhra Pradesh</TITLE>
</HEAD>
<BODY>
<CENTER><H1>Andhra Pradesh</H1></CENTER>
<HR>
<UL>
<LI>Area : 2,75,068 Sq. Kms</LI>
<LI>Capital : Hyderabad</LI>
<LI>Language : Telugu</LI>
<LI>Population : 7,57,27,541</LI>
</UL>
</BODY>
BB / REC - 62
<!-- Kerala.html -->
<HTML>
<HEAD>
<TITLE>About Kerala</TITLE>
</HEAD>
<BODY>
<CENTER><H1>Kerala</H1></CENTER>
<HR>
<UL>
<LI>Area : 38,863 Sq. Kms.</LI>
<LI>Capital : Thiruvananthapuram</LI>
<LI>Language : Malayalam</LI>
<LI>Population : 3,18,38,619</LI>
</UL>
</BODY>
</HTML>
<!-- Karnataka.html -->
<HTML>
<HEAD>
<TITLE>About Karnataka</TITLE>
</HEAD>
<BODY>
<CENTER><H1>Karnataka</H1></CENTER>
<HR>
<UL>
<LI>Area : 1,91,791 Sq. Kms</LI>
<LI>Capital : Bangalore</LI>
<LI>Language : Kannada</LI>
<LI>Population : 5,27,33,958</LI>
</UL>
</BODY>
</HTML>
BB / REC - 64
BB / REC - 66
<!-- Ex. No. 10 – Cascading Style Sheets -->
<!-- Main.html -->
<HTML>
<HEAD>
<TITLE>Cascading Style Sheets</TITLE>
</HEAD>
<FRAMESET rows = "200, *" frameborder = "no" framespacing =
"0">
<FRAME name = "top" src = "top.html">
<FRAMESET cols = "150, *" frameborder = "no" framespacing =
"0">
<FRAME name = "left" src = "left.html" scrolling = "no">
<FRAME name = "right" src = "right.html">
</FRAMESET>
</FRAMESET>
<NOFRAMES>
YOUR BROWSER DOESN'T SUPPORT FRAMES
</NOFRAMES>
</HTML>
<HTML>
<HEAD>
<STYLE type = "text/css">
body { background-color : cyan}
a:link {
text-decoration: none;
color: #435161;
}
a:hover {
text-decoration: none;
cursor: hand;
font-weight: bold;
}
a:visited {
text-decoration: none;
color: blue;
}
a:active {
text-decoration: none;
}
</STYLE>
</HEAD>
<BODY>
<A href = "aboutus.html" target = "right">About Us</A>
<BR><BR>
<A href = "faculties.html" target = "right">Faculties</A>
<BR><BR>
<A href = "labs.html" target = "right">Lab Facilities</A>
<BR><BR>
</BODY>
</HTML>
BB / REC - 68
<!-- Right.html -->
<HTML>
<HEAD>
<LINK rel = "stylesheet" type = "text/css" href = "style.css"
</HEAD>
<BODY>
REC Welcomes you to the Department of Computer Science and Engineering...
</BODY>
</HTML>
<!-- Aboutus.html -->
<HTML>
<HEAD>
<LINK rel = "stylesheet" type = "text/css" href = "style.css"
</HEAD>
<BODY>
<P class = "margin01">
Since its inception in 1997, the Department of Computer
Science and Engineering has been continuously making progress in teaching and R&D activities. Started with an intake of 60 students, the sanctioned intake was increased to 90 seats in 2001 and to 120 seats in 2005. The Post Graduate programme viz. M.E. – Computer Science and Engineering was introduced in the year 2004-05 and in 2006 the Department was recognized as Collaborative Research Centre by Anna University to offer M.S.
(By Research) and Ph.D. programmes. The Department has been maintaining an active interaction with the industries
particularly with the Computer Society of India. The IT major Tata Consultancy Services has accredited the college for
faculty and students development programmes, campus interview etc.
</P>
</BODY>
</HTML>
<HTML>
<HEAD>
<LINK rel = "stylesheet" type = "text/css" href = "style.css"
</HEAD>
<BODY>
<P class = "caps16"> Faculty Members </P>
<TABLE border = 1>
<tr><th>No.</th> <th>Name</th> <th>Designation</th></tr>
<td>1</td><td>Prof.K.Veeraraghavan</td><td>Professor &
Head</td></tr>
<td>3</td><td>Prof.S.Muthukumar</td><td>Professor</td></tr>
<td>4</td><td>Mr.B.Swaminathan</td><td>Assistant Professor</td></tr>
<td>5</td><td>Ms.S.Poonkuzhali</td><td>Assistant Professor</td></tr>
</TABLE>
</BODY>
</HTML>
<!-- Labs.html -->
<HTML>
<HEAD>
<LINK rel = "stylesheet" type = "text/css" href = "style.css"
</HEAD>
<BODY>
<P class = "Caps16">LAB FACILITIES</P>
The department has the following well equipped laboratories.
<BR>
<BR>
1 Data Structures Lab
<BR>
2 Linux Lab
<BR>
3 C and Office Suite Lab
<BR>
4 RDBMS and CASE Tools Lab
<BR>
BB / REC - 70
</HTML>
Style.css
body { background-color : silver}
a:link {
text-decoration: none;
color: #435161;
}
a:hover {
text-decoration: none;
cursor: hand;
font-weight: bold;
}
a:visited {
text-decoration: none;
color: blue;
}
a:active {
text-decoration: none;
}
.Margin01 {
padding: 10px;
}
.BodyTextNoColor {
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 11px;
line-height: 18px;
}
.BodyTextBigNoColor {
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 13px;
line-height: 18px;
}
.Margin02 {
padding: 5px 5px 5px 15px;
}
.BodyTextSmlNoColor {
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 10px;
line-height: 18px;
}
.Caps16 {
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 20px;
font-weight: normal;
letter-spacing: 6px;
}
Output:
BB / REC - 72