ip lab programs full cse vii sem

105
TABLE OF CONTENTS EXPT PAGE No DATE NAME OF THE EXPERIMENT NO SIGN 1 AWT COMPONENTS 2(a) FLOW LAYOUT 2(b) BORDER LAYOUT 2(c) GRID LAYOUT 2(d) CARD LAYOUT 3 COLOR PALETTE 4(a) DOWNLOAD THE HOME PAGE OF THE SERVER 4(b ) DISPALAY THE CONTENTS OF THE HOME PAGE 5(a) HTTP REQUEST 5(b) FILE TRANSFER PROTOCOL 6 UDP CHAT

Upload: maddy272631932

Post on 07-Apr-2015

1.353 views

Category:

Documents


4 download

TRANSCRIPT

Page 1: Ip Lab Programs Full Cse Vii Sem

TABLE OF CONTENTSEXPT PAGE No DATE NAME OF THE EXPERIMENT NO SIGN

1 AWT COMPONENTS

2(a) FLOW LAYOUT 2(b) BORDER LAYOUT

2(c) GRID LAYOUT

2(d) CARD LAYOUT

3 COLOR PALETTE

4(a) DOWNLOAD THE HOME PAGE OF THE SERVER

4(b ) DISPALAY THE CONTENTS OF THE HOME PAGE

5(a) HTTP REQUEST

5(b) FILE TRANSFER PROTOCOL

6 UDP CHAT

7 INVOKING SERVLETS FROM HTML

8(a) ONLINE EXAMINTAION USING SERVLETS

8(b) STUDENT MARKLIST USING SERVLETS

9 CREATING AND USING IMAGE MAPS

10 STYLE SHEETS

Page 2: Ip Lab Programs Full Cse Vii Sem

EXPT NO: 01 AWT COMPONENTS

AIM:

To demonstrate the working of AWT components using java programming

ALGORITHM:

Step 1: Import the necessary java classes lile awt,event that handle awt components

Step 2: In Applet classimplement the interfaces like ActionListener,ItemListener etc,

that handles interactions of the components.

Step 3: Create components like TextField,Buttons,Lists,Choices with appropriate

syntaxes

Step 4: Add all the components that was created in init()

Step 5: Specify the current object for all components in init()

Step 6: Inside the methods of interfaces( like actionPerformed..) check for the status of

components and display the current status.

Step 7: Include repaint() wherever necessary.

Step 8: Run the code and record the result

Page 3: Ip Lab Programs Full Cse Vii Sem

PROGRAM:

import java.applet.Applet;import java.awt.*;import java.awt.event.*;/*<applet code="AwtComponents.java" width=400 height=400></applet>*/

public class AwtComponents extends Applet implements ActionListener,ItemListener { List li=new List(); CheckboxGroup cg=new CheckboxGroup(); Checkbox c=new Checkbox("MALE",cg,false); Checkbox c1=new Checkbox("FEMALE",cg,false); TextField t=new TextField(10); Button b2=new Button("YES"); Button b=new Button("ENTER"); Button b1=new Button("EXIT"); Choice i=new Choice(); Scrollbar s=new Scrollbar(); String str,str1,str2,str3,str4; Boolean flag; public void init() { Font f=new Font("Comic Sans MS",Font.BOLD,14); setFont(f); Label l=new Label("COMPANY RECORD"); li.add("MANAGING DIRECTOR"); li.add("SENOIR OFFICER"); li.add("GENERAL EMPLOYEE"); li.add("DRIVERS"); li.add("VISITORS"); i.add("Permament Worker"); i.add("Temporary Worker"); add(l); add(li); add(c); add(c1); add(t); add(b2); add(i); add(b); add(b1); add(s); t.addActionListener(this); c.addItemListener(this); c1.addItemListener(this); li.addActionListener(this); b1.addActionListener(this); b.addActionListener(this); i.addItemListener(this); } public void actionPerformed(ActionEvent e) { str3=e.getActionCommand();

Page 4: Ip Lab Programs Full Cse Vii Sem

if(str3.equals("ENTER")) { showStatus("WELCOME"); } else if(str3.equals("EXIT")) { showStatus("THANK YOU!!!"); } repaint(); } public void paint(Graphics g) { str="POST:" +li.getSelectedItem(); g.drawString(str,180,180); str1="SEX:"+cg.getSelectedCheckbox().getLabel(); g.drawString(str1,180,200); str2="NAME:"+t.getText(); g.drawString(str2,180,225); str4="STATUS:"+i.getSelectedItem();//getSelectedText(); g.drawString(str4,180,250); } public void itemStateChanged(ItemEvent e) { repaint(); } public boolean action(Event e,Object o) { if(e.target==b2) { repaint(); } return flag=false; }}

Page 5: Ip Lab Programs Full Cse Vii Sem

OUTPUT: C:\jdk1.6.0_05\bin>javac AwtComponents.java C:\jdk1.6.0_05\bin>appletviewerAwtComponents.java

Page 6: Ip Lab Programs Full Cse Vii Sem

RESULT:

Thus the program is executed successfully and verified.

Page 7: Ip Lab Programs Full Cse Vii Sem

EXPT NO: 02(A) FLOW LAYOUT

AIM:

To demonstrate the Flow Layout using java program.

ALGORITHM:

Step 1: Import all necessary packages and classes.

Step 2: Define a class that extends Applet.

Step 3: Create a Flow layout and specify the position of buttons.

Step 4: Set the layout using its instance.

Step 5: Create the buttons and add it in the init function.

Page 8: Ip Lab Programs Full Cse Vii Sem

PROGRAM:

import java.awt.*;import java.awt.event.*;import java.applet.*;/*<applet code="FlowLayoutDemo" width=300 height=300></applet>*/public class FlowLayoutDemo extends Applet implementsItemListener {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);g.drawString("Red Hat Linux : " + chkRed.getState(),10, 190);g.drawString("Fedora : " + chkFed.getState(), 10,210);}}

Page 9: Ip Lab Programs Full Cse Vii Sem

OUTPUT:

C:\jdk1.6.0_05\bin>javac FlowLayoutDemo.java C:\jdk1.6.0_05\bin>appletviewer FlowLayoutDemo.java

Page 10: Ip Lab Programs Full Cse Vii Sem

RESULT:

Thus the program is executed successfully and verified.

Page 11: Ip Lab Programs Full Cse Vii Sem

EXPT NO: 02(B) BORDER LAYOUT

AIM:

To demonstrate the Border Layout using java program.

ALGORITHM:

Step 1: Import all necessary packages and classes.

Step 2: Define a class that extends Applet.

Step 3: Create a Border layout.

Step 4: Set the layout using its instance.

Step 5: Create Buttons, TextFields and add it in the border layout with specific

direction in the init function.

Page 12: Ip Lab Programs Full Cse Vii Sem

PROGRAM:

import java.awt.*;import java.applet.*;import java.util.*;/*<applet code="borderlayout" width=400 height=400></applet>*/public class borderlayout extends Applet{ public void init(){setLayout(new BorderLayout());add(new Button("RAJA RAJESWARI Engineering College"),BorderLayout.NORTH);add(new Label("A.C.S GROUP OF COLLEGES"),BorderLayout.SOUTH);add(new Button("Mission"), BorderLayout.EAST); add(new Button("Vision"), BorderLayout.WEST);String msg="Raja Rajeswari Engineering College was established \n" +"in the year 1997 under the A.C.S Group of Colleges\n"+"whose members have had consummate experience in the fields of \n" +"education and industry."; add(new TextArea(msg),BorderLayout.CENTER);}}

Page 13: Ip Lab Programs Full Cse Vii Sem

OUTPUT:

C:\jdk1.6.0_05\bin>javac BorderLayoutDemo.java C:\jdk1.6.0_05\bin>appletviewer BorderLayoutDemo.java

Page 14: Ip Lab Programs Full Cse Vii Sem

RESULT:

Thus the program is executed successfully and verified.

Page 15: Ip Lab Programs Full Cse Vii Sem

EXPT NO: 02(C) GRID LAYOUT

AIM:

To demonstrate the GridLayout using java program.

ALGORITHM:

Step 1: Import all necessary packages and classes.

Step 2: Define a class that extends Applet.

Step 3: Create a Grid layout with specific rows and columns.

Step 4: Set the layout using its instance.

Step 5: Create Buttons, TextFields and add it in the init function.

Page 16: Ip Lab Programs Full Cse Vii Sem

PROGRAM:

import java.awt.*;import java.applet.*;/*<applet code="gridlayoutdemo" width=400 height=400></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));}}}

Page 17: Ip Lab Programs Full Cse Vii Sem

OUTPUT:

C:\jdk1.6.0_05\bin>javac GridLayoutDemo.java C:\jdk1.6.0_05\bin>appletviewer GridLayoutDemo.java

Page 18: Ip Lab Programs Full Cse Vii Sem

RESULT:

Thus the program is executed successfully and verified.

Page 19: Ip Lab Programs Full Cse Vii Sem

EXPT NO: 02(D) CARD LAYOUT

AIM:

To write a java program to demonstrate the Card Layout

ALGORITHM:

Step 1: Import all necessary packages and classes

Step 2: Define a class that extends applet and implements action listener

Step 3: Declare buttons tiny, large, medium, and small

Step 4: Create panels for card layout and for cards of buttons

Step 5: In the init () method, do the following:

i) Create the card layout

ii) Create the card panel and set its layout to card layout

iii) Create other panels and set their layout to border layout

iv) Add action listener to the buttons and each button to one panel of

appropriate name

v) Add the panels to the card panel

vi) Set the layout of the applet to border layout and add card panel to the

applet

Step 6: In the actionPerformed() method, move to the next card in the card panel

Page 20: Ip Lab Programs Full Cse Vii Sem

PROGRAM:

import java.awt.*;import java.awt.event.*;import java.applet.*;/*<applet code="cardlay" width=400 height=400> </applet>*/public class cardlay 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");pnlTech.add(pnlJava, "Java");add(pnlTech);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) {

Page 21: Ip Lab Programs Full Cse Vii Sem

cardLO.show(pnlTech, "Microsoft");}else {cardLO.show(pnlTech, "Java");} } }

Page 22: Ip Lab Programs Full Cse Vii Sem

OUTPUT:

C:\jdk1.6.0_05\bin>javac CardLayoutDemo.java C:\jdk1.6.0_05\bin>appletviewer CardLayoutDemo.java

Page 23: Ip Lab Programs Full Cse Vii Sem

RESULT:

Thus the program is executed successfully and verified.

Page 24: Ip Lab Programs Full Cse Vii Sem

EXPT NO: 03 COLOR PALETTE

AIM:

To write a java program to create applets with the following features

Create a color palette with matrix of buttons.

a. Set background and foreground of the control text area by selecting a color

from color palette.

b. In order to select foreground or background use checkbox controls as

radio buttons.

c. To set background images.

ALGORITHM:

Step 1: Import all necessary packages and classesStep 2: Define a class that extends applet and implements action listener and item

listenerStep 3: Declare an array of buttons to set colors, two checkboxes for foreground and background colorsStep 4: Declare a text area to hold the text, a checkbox group for checkboxesStep 5: Add the array of buttons in the init function.Step 6: In the actionPerformed() method, do the following: i) Get the action command in the string, color ii) If foreground is checked then set the foreground color to the selected color

iii) If background is checked then set the background color to the selected color

Page 25: Ip Lab Programs Full Cse Vii Sem

PROGRAM:

import java.awt.*;import java.awt.event.*;import java.applet.*;/*<applet code="exp" width=400 height=400></applet>*/public class exp extends Applet implements ItemListener{int currcolor=5;int flag=1;String text="Click any of the buttons";Button buttons[]=new Button[5];String colours[]={"Red","Blue","Green","Yellow","Magenta"};Image img;CheckboxGroup cbg=new CheckboxGroup();Checkbox box1=new Checkbox("Background Color",cbg,true);Checkbox box2=new Checkbox("Text Color",cbg,false);Checkbox box3=new Checkbox("Loading Image",cbg,false);public void init(){for(int i=0;i<5;i++){buttons[i]=new Button(" ");add(buttons[i]);}buttons[0].setBackground(Color.red);buttons[1].setBackground(Color.blue);buttons[2].setBackground(Color.green);buttons[3].setBackground(Color.yellow);buttons[4].setBackground(Color.magenta);add(box1);add(box2);add(box3);box1.addItemListener(this);box2.addItemListener(this);box3.addItemListener(this);}public void itemStateChanged(ItemEvent ev){if(box1.getState()==true)flag=1;else if(box2.getState()==true){text="Default color is black";flag=2;}else if(box3.getState()==true)

Page 26: Ip Lab Programs Full Cse Vii Sem

{img=getImage(getDocumentBase(),"Water lilies.jpg");flag=3;}repaint();}public void paint(Graphics g){if(flag==2){g.drawString(text,30,100);switch(currcolor){case 0:g.setColor(Color.red);break;case 1:g.setColor(Color.blue);break;case 2:g.setColor(Color.green);break;case 3:g.setColor(Color.yellow);break;case 4:g.setColor(Color.magenta);break;case 5:g.setColor(Color.black);break;}g.drawString(text,30,100);}else if(flag==1){g.drawString(text,30,100);switch(currcolor){case 0:setBackground(Color.red);break;case 1:setBackground(Color.blue);break;case 2:setBackground(Color.green);break;case 3:setBackground(Color.yellow);break;case 4:setBackground(Color.magenta);break;case 5:

Page 27: Ip Lab Programs Full Cse Vii Sem

setBackground(Color.white);break;}}else if(flag==3){g.drawImage(img,20,90,this);}}public boolean action(Event e,Object o){for(int i=0;i<5;i++){if(e.target==buttons[i]){currcolor=i;text="You have chosen "+colours[i];repaint();return true;}}return false;}}

Page 28: Ip Lab Programs Full Cse Vii Sem

OUTPUT:

C:\jdk1.6.0_05\bin>javac ColorPalette.java C:\jdk1.6.0_05\bin>appletviewer ColorPalette.java

Page 29: Ip Lab Programs Full Cse Vii Sem

RESULT:

Thus the program is executed successfully and verified.

Page 30: Ip Lab Programs Full Cse Vii Sem

EXPT NO: 04(A) DOWNLOAD THE HOME PAGE OF THE SERVER

AIM:

To write a java program to download a page from a web site

ALGORITHM:

Step 1: Create a URL to any web site and open a URL Connection using

OpenConnection ().

Step 2: Download the web page from the server

Step 3: Open an input stream with the URL Connection

Step 4: If url is incorrect display “ url is not parseable “

Page 31: Ip Lab Programs Full Cse Vii Sem

PROGRAM:

import java.net.*;import java.io.*;public class mime1{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);} }}}

Page 32: Ip Lab Programs Full Cse Vii Sem

OUTPUT:

Page 33: Ip Lab Programs Full Cse Vii Sem

RESULT:

Thus the program is executed successfully and verified.

EXPT NO: 04(B) DISPLAY THE CONTENTS OF THE HOME PAGE

AIM:

To write a java program to display the properties of the web page.

ALGOTITHM:

Step 1: Create a URL to any web site and open a URL Connection using

OpenConnection ().

Step 2: Get the date, content type, last modified and length of the page and

display them

Step 3: Open an input stream with the URL Connection

Step 4: If no content is available then display “no content is available"

Page 34: Ip Lab Programs Full Cse Vii Sem

PROGRAM:

import java.net.*;import java.io.*;import java.util.*;public class mime2{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 e){System.err.println(args[i]+" is not a URL i understand");}catch(IOException e){System.err.println(e);}

Page 35: Ip Lab Programs Full Cse Vii Sem

System.out.println();}}}

OUTPUT:

Page 36: Ip Lab Programs Full Cse Vii Sem

RESULT: Thus the program is executed successfully and verified.

Page 37: Ip Lab Programs Full Cse Vii Sem

EXPT NO: 05(A) HTTP REQUEST

AIM:

To write a java socket program to demonstrate HTTP Request

ALGORITHM:

Step 1: Import all the necessary packagesStep 2: Create an URL to the server specifying the html page

Step 3: Get the host and port details from the URL

Step 4: Request the file from the server using GET method of HTTP Request

Step 5: Receive the response from the server

Step 6: Display the response on the console

Page 38: Ip Lab Programs Full Cse Vii Sem

PROGRAM:

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 = newBufferedInputStream(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);}}}}

Page 39: Ip Lab Programs Full Cse Vii Sem

OUTPUT:

Page 40: Ip Lab Programs Full Cse Vii Sem

RESULT:

Thus the program is executed successfully and verified.

Page 41: Ip Lab Programs Full Cse Vii Sem

EXPT NO: 05(B) FILE TRANSFER PROTOCOL

AIM:

To write a java program to demonstrate a simple FTP operation

ALGORITHM:

FTP Client:

Step 1: Establish a connection with the server at a particular portStep 2: Specify the name of the file to be readStep 3: Receive the contents of the file from the server

FTP Server:

Step 1: Accept the connection with the clientStep 2: Listen to the port for the name of the file to be sentStep 3: Send the file character by characterStep 4: Terminate the connection

Page 42: Ip Lab Programs Full Cse Vii Sem

PROGRAM:

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();}}}

Page 43: Ip Lab Programs Full Cse Vii Sem

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 = newBufferedWriter(new FileWriter("Recdfile.txt"));

do{

Page 44: Ip Lab Programs Full Cse Vii Sem

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();}}}

Page 45: Ip Lab Programs Full Cse Vii Sem

FileServant.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();}

Page 46: Ip Lab Programs Full Cse Vii Sem

catch (IOException e){e.printStackTrace();}}public static void main(String[] args){}}

Page 47: Ip Lab Programs Full Cse Vii Sem

OUTPUT:

Page 48: Ip Lab Programs Full Cse Vii Sem
Page 49: Ip Lab Programs Full Cse Vii Sem
Page 50: Ip Lab Programs Full Cse Vii Sem

RESULT:

Thus the program is executed successfully and verified.

EXPT NO: 06 UDP CHAT

AIM:

To write a java program to create a simple chat application with datagram sockets and packets

ALGORITHM:

Server Side

Step 1: Import necessary packages.Step 2: Create a datagram socket and datagram packetStep 3: While client send datagram packet to server listen to client portStep 4: Get the datagram packet into a stringStep 5: Display the string

Client Side

Step 1: Import necessary packages Step 2: Create a datagram socket and datagram packetStep 3: Get input from the user and convert the string into a datagram packetStep 4: send the datagram packet to the server through serve port

Page 51: Ip Lab Programs Full Cse Vii Sem

PROGRAM:

UDPServer.java

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;}

Page 52: Ip Lab Programs Full Cse Vii Sem

System.out.println("Client: " + str);String str1 = new String(dis.readLine());buf = str1.getBytes();serversocket.send(new DatagramPacket(buf,str1.length(), ia, cport));}}}

UDPClient.java

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));

Page 53: Ip Lab Programs Full Cse Vii Sem

clientsocket.receive(dp);String str2 = new String(dp.getData(), 0,dp.getLength());System.out.println("Server: " + str2);}}}

OUTPUT

Page 54: Ip Lab Programs Full Cse Vii Sem
Page 55: Ip Lab Programs Full Cse Vii Sem

RESULT:

Thus the program is executed successfully and verified.

EXPT NO: 07INVOKING SERVLETS FROM HTML

Page 56: Ip Lab Programs Full Cse Vii Sem

AIM:

To write html and servlet to demonstrate invoking a servlet from a html.

ALGORITHM:

Client:

Step1: In index.jsp on the client side declare the contents that you like to transfer to the server using html form and input type tags.Step2: create a submit button and close all the included tags.

Server:

Step1: In the servlet side using the parameter request get the stings declared in the client side (requst.getparameter)

Step2: Include necessary html coding that helps to display the content

PROGRAM:

Sevlet Code:

Page 57: Ip Lab Programs Full Cse Vii Sem

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();}}

HTML CODE:

<HTML> <head>

Page 58: Ip Lab Programs Full Cse Vii Sem

<TITLE>INVOKING SERVLET FROM HTML</TITLE> </head><BODY><CENTER><FORM name = "PostParam" method = "Post" action="http://localhost:8080/servlets-examples/servlet/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"></FORM></CENTER></body></html>

OUTPUT:

Page 59: Ip Lab Programs Full Cse Vii Sem
Page 60: Ip Lab Programs Full Cse Vii Sem

RESULT:

Thus the program is executed successfully and verified.

EXPT NO: 08 (A) ONLINE EXAMINATION USING SERVLETS

Page 61: Ip Lab Programs Full Cse Vii Sem

AIM:

To write java servlet programs to conduct online examination and to display student mark list available in a database

ALGORITHM:

Client:

Step1: In index.html on the client side declare the contents that you like to transfer to the server using html form and input type tags.Step2: create a submit button and close all the included tags.

Servlet:

Step 1: Import all necessary packagesStep 2: Define a class that extends servlet

Step 3: In the doPost() method, do the following: i) Set the content type of the response to "text/html" ii) Create a writer to the response iii) Get a paratmeter from the request iv) If its value is equal to right answer then add 5 to mark variable v) Similarly repeat step vi) for all parameters vii) Display the result in an html format using the writer

STUDENT MARK LIST DATABASE

Step 1: Import necessary to java packages and javax packages and classesStep 2: Create a class that extends HttpServlet and implements ServletException and IOExceptionStep 3: In the doGet() method, do the following:

i) Create a PrintWriter object ii) Open a connection with the data source name iii) Write a sql query and execute to get the resultset iv) Display the resultset information in html form

PROGRAM:

SERVLET CODE:

Page 62: Ip Lab Programs Full Cse Vii Sem

import java.io.*;import java.sql.*;import javax.servlet.*;import javax.servlet.http.*;public class StudentServlet3 extends HttpServlet{String message,Seat_no,Name,ans1,ans2,ans3,ans4,ans5;int Total=0;Connection connect;Statement stmt=null;ResultSet rs=null;public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{try{String url="jdbc:odbc:NEO";Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");connect=DriverManager.getConnection(url," "," ");message="Thank you for participating in online Exam";}catch(ClassNotFoundException cnfex){cnfex.printStackTrace();}catch(SQLException sqlex){sqlex.printStackTrace();}catch(Exception excp){ excp.printStackTrace();}

Seat_no=request.getParameter("Seat_no");Name=request.getParameter("Name");ans1=request.getParameter("group1");ans2=request.getParameter("group2");ans3=request.getParameter("group3");ans4=request.getParameter("group4");ans5=request.getParameter("group5");if(ans1.equals("True"))Total+=2;if(ans2.equals("False"))Total+=2;if(ans3.equals("True"))Total+=2;if(ans4.equals("False"))Total+=2;if(ans5.equals("False"))Total+=2;try{Statement stmt=connect.createStatement();String query="INSERT INTO student("+"Seat_no,Name,Total"+") VALUES('"+Seat_no+"','"+Name+"','"+Total+"')";

Page 63: Ip Lab Programs Full Cse Vii Sem

int result=stmt.executeUpdate(query);stmt.close();}catch(SQLException ex){}response.setContentType("text/html");PrintWriter out=response.getWriter();out.println("<html>");out.println("<head>");out.println("</head>");out.println("<body bgcolor=cyan>");out.println("<center>");out.println("<h1>"+message+"</h1>\n");out.println("<h3>Yours results stored in our database</h3>");out.print("<br><br>");out.println("<b>"+"Participants and their Marks"+"</b>");out.println("<table border=5>");try{Statement stmt=connect.createStatement();String query="SELECT * FROM student";rs=stmt.executeQuery(query);out.println("<th>"+"Seat_no"+"</th>");out.println("<th>"+"Name"+"</th>");out.println("<th>"+"Marks"+"</th>");while(rs.next()){out.println("<tr>");out.print("<td>"+rs.getInt(1)+"</td>");out.print("<td>"+rs.getString(2)+"</td>");out.print("<td>"+rs.getString(3)+"</td>");out.println("</tr>");}out.println("</table>");}catch(SQLException ex){ }finally{try{if(rs!=null)rs.close();if(stmt!=null)stmt.close();if(connect!=null)connect.close();}catch(SQLException e){ }}out.println("</center>");out.println("</body></html>");Total=0;} }

Page 64: Ip Lab Programs Full Cse Vii Sem

HTML CODE:

<html><head><title>Database Test</title></head><body><center><h1>Online Examination</h1></center><form action="StudentServlet3.view" method="POST"><div align="left"><br></div><b>Seat Number:</b> <input type="text" name="Seat_no"><div align="Right"><b>Name:</b> <input type="text" name="Name" size="50"><br></div><br><br><b>1. Every host implements transport layer.</b><br/><input type="radio" name="group1" value="True">True<input type="radio" name="group1" value="False">False<br>

<b>2. It is a network layer's responsibility to forward packets reliably from source to destination</b><br/><input type="radio" name="group2" value="True">True<input type="radio" name="group2" value="False">False<br>

<b>3. Packet switching is more useful in bursty traffic</b><br/><input type="radio" name="group3" value="True">True<input type="radio" name="group3" value="False">False<br>

<b>4. A phone network uses packet switching</b><br/><input type="radio" name="group4" value="True">True<input type="radio" name="group4" value="False">False<br>

<b>5. HTML is a Protocol for describing web contents</b><br/><input type="radio" name="group5" value="True">True<input type="radio" name="group5" value="False">False<br>

<br><br><br><center><input type="submit" value="Submit"><br><br></center></form></body></html>

OUTPUT:

Page 65: Ip Lab Programs Full Cse Vii Sem
Page 66: Ip Lab Programs Full Cse Vii Sem

RESULT:

Thus the program is executed successfully and verified.

EXPT NO: 8(B) STUDENT MARKLIST USING SERVLET

Page 67: Ip Lab Programs Full Cse Vii Sem

AIM:

To create a three tier application for displaying the student marklist

ALGORITHM:

Client:

Step1: In index.html on the client side declare the contents that you like to transfer to the server using html form and input type tags.Step2: create a submit button and close all the included tags.

Servlet:

Step 1: Import all necessary packagesStep 2: Define a class that extends servlet

Step 3: In the doPost() method, do the following: i) Set the content type of the response to "text/html" ii) connect with the database which has the student marklist iii) query the data to the database Step 4: Display the student marklist

PROGRAM:

Page 68: Ip Lab Programs Full Cse Vii Sem

SERVLET CODE:

import java.io.*;import java.sql.*;import javax.servlet.*;import javax.servlet.http.*;public class serv extends HttpServlet{String message,Reg_no; Connection connect;Statement stmt=null;ResultSet rs=null;public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{try{String url="jdbc:odbc:NEO";Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");connect=DriverManager.getConnection(url," "," ");message="Mark List";}catch(ClassNotFoundException cnfex){cnfex.printStackTrace();}catch(SQLException sqlex){sqlex.printStackTrace();}catch(Exception excp){ excp.printStackTrace();}Reg_no=request.getParameter("regno");response.setContentType("text/html");PrintWriter out=response.getWriter();out.println("<html>");out.println("<head>");out.println("</head>");out.println("<body bgcolor=cyan>");out.println("<center>");out.println("<h1>"+message+"</h1>\n");try{Statement stmt=connect.createStatement();

String query=new String("SELECT * FROM MarkList WHERE regno= "+Reg_no);rs=stmt.executeQuery(query);boolean b=rs.next();out.println("Regsitration No:"+rs.getInt(1));out.println("<br>"+"Name:"+rs.getString(2));out.println("<table border=5>");out.println("<th>"+"cs01"+"</th>");out.println("<th>"+"cs02 "+"</th>");out.println("<th>"+"cs03"+"</th>");out.println("<th>"+"status"+"</th>");

Page 69: Ip Lab Programs Full Cse Vii Sem

while(b){out.println("<tr>");out.print("<td>"+rs.getString(3)+"</td>");out.print("<td>"+rs.getString(4)+"</td>");out.print("<td>"+rs.getString(5)+"</td>");out.print("<td>"+rs.getString(6)+"</td>");out.println("</tr>");b=rs.next();}out.println("</table>");}catch(SQLException ex){ out.println("error in connection");}finally{try{if(rs!=null)rs.close();if(stmt!=null)stmt.close();if(connect!=null)connect.close();}catch(SQLException e){ }}out.println("</center>");out.println("</body></html>");}}

HTML CODE:

<html><head><title> mark sheet</title></head>

Page 70: Ip Lab Programs Full Cse Vii Sem

<body><center><h1>Student Mark Sheet</h1></center><form action="serv" method="POST">registration number:<input type="text" name="regno"><input type="submit" value="Submit"><br><br></form></body></html>

OUTPUT:

Page 71: Ip Lab Programs Full Cse Vii Sem
Page 72: Ip Lab Programs Full Cse Vii Sem

RESULT:

Thus the program is executed successfully and verified.

EXPT NO: 09 CREATING AND USING IMAGE MAPS

Page 73: Ip Lab Programs Full Cse Vii Sem

AIM:

To create a web page which includes a map and display the related information when a hot spot is clicked in the map

ALGOTITHM:

Step 1: Create a html file with map tagStep 2: Set the source attribute of the img tag to the location of the image and also set the usemap attributeStep 3: Specify an area with name, shape and href set to the appropriate valuesStep 4: Repeat step 3 as many hot spots you want to put in the mapStep 5: Create html files for each and every hot spots the user will select

PROGRAM:

ImageMap.html

Page 74: Ip Lab Programs Full Cse Vii Sem

<HTML> <HEAD> <TITLE>Image Map</TITLE> </HEAD><BODY><img src="india_map.jpg" usemap="#metroid" ismap="ismap" > <map name="metroid" id="metroid"> <area href='TamilNadu.html' shape='circle' coords='175,495,30' title='TamilNadu'/><area href = "Karnataka.html" shape = "rect" coords = "100,400,150,450" title = "Karnataka" /><area href = "AndhraPradesh.html" shape = "poly" coords = "150, 415, 175,348,265,360,190,420,190,440" title = "Andhra Pradesh" /><area href = "Kerala.html" shape = "poly" coords = "108,455,150,515,115,490,148,495,110,448,155,501" title = "Kerala" /></map> </BODY></HTML>

TamilNadu.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><hr><a href='ImageMap.html'>India Map</a></BODY></HTML>

Karnataka.html

<HTML><HEAD><TITLE>About Karnataka</TITLE>

Page 75: Ip Lab Programs Full Cse Vii Sem

</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><hr><a href='ImageMap.html'>India Map</a></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><hr><a href='ImageMap.html'>India Map</a></BODY></HTML>

Kerala.html

<HTML>

Page 76: Ip Lab Programs Full Cse Vii Sem

<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><hr><a href='ImageMap.html'>India Map</a></BODY></HTML>

OUTPUT:

Page 77: Ip Lab Programs Full Cse Vii Sem
Page 78: Ip Lab Programs Full Cse Vii Sem
Page 79: Ip Lab Programs Full Cse Vii Sem
Page 80: Ip Lab Programs Full Cse Vii Sem

RESULT:

Thus the program is executed successfully and verified.

Page 81: Ip Lab Programs Full Cse Vii Sem

EXPT NO: 10 STYLESHEETS

AIM:

To create a web page that displays college information using various style sheet

ALGORITHM:

Step 1: Create a web page with frame sets consisting two frames

Step 2: In the first frame include the links

Step 3: In the second frame set display the web page of the link

Step 4: create a external style sheets

Step 5: create a inline and internal style sheets and make it link to the external

style sheets

Page 82: Ip Lab Programs Full Cse Vii Sem

PROGRAM:

XYZ.CSS:

h3{font-family:arial;font-size:20;color:cyan}table{border-color:green}td{font-size:20pt;color:magenta}

HTML CODE:

<html><head><h1><center>ALL STYLE SHEETS</center></h1><title>USE of INTERNAL and EXTERNAL STYLESHEETS</title><link rel="stylesheet" href="xyz.css" type="text/css"><style type="text/css">.vid{font-family:verdana;font-style:italic;color:red;text-align:center}.ani{font-family:tahoma;font-style:italic;font-size:20;text-align:center;}font{font-family:georgia;color:blue;font-size:20}ul{list-style-type:circle}</style></head><body><ol style="list-style-type:lower-alpha"><b>A.C.S GROUP OF COLLEGES</b><br><br><br><li>Raja Rajeswari Engineering College<li>Dr. M.G.R University and Research Institute<li>Raja Rajeswari College of Engineering,Bangalore<li>Tamilnadu College of Arts and Science</ol><p style="font-size:20pt;color:purple">A.C.S GROUP OF COLLEGES</p><p class="ani">A.C.S Group of colleges is owned by A.C.Shanmugam.<br>It is approved byAICTE(All India Council for Technical Education).It is affliated to Anna University.<br></p><h2 class="vid">Raja Rajeswari Engineering College</h2><br><font>It is an ISO certified Institution</font><br><br><font><h2>List of Courses offered</h2><ul><li>Computer Science and Engineering</li><li>Ece</li><li>mech</li><li>eee</li></ul></font><h3>Results of cse students</h3><table width="100%" cellspacing="2" cellpadding="2" border="5"><tr><th>S.NAME</th><th>MARKS</th><th>RESULT</th>

Page 83: Ip Lab Programs Full Cse Vii Sem

</tr><tr><td align="center">Dinesh</td><td align="center">100</td><td align="center">pass</td></tr><tr><td align="center">Bala</td><td align="center">99</td><td align="center">pass</td></tr><tr><td align="center">Gopi</td><td align="center">98</td><td align="center">pass</td></tr></table></body></html>

Page 84: Ip Lab Programs Full Cse Vii Sem

OUTPUT:

Page 85: Ip Lab Programs Full Cse Vii Sem

RESULT:

Thus the program is executed successfully and verified.