You are on page 1of 101

LAB MANUAL

CS506PC: COMPUTER NETWORKS AND WEB TECHNOLOGIES LAB

III B. Tech I Semester (JNTUH-R18)

Computer Science and Engineering

Vignan’s Institute of Management and Technology for Women


2019-20
COMPUTER NETWORKS AND WEB TECHNOLOGIES LAB
(AS PER JNTU SYLLABUS)

Course Objectives

1.To understand the working principle of various communication protocols.

2.To understand the network simulator environment and visualize a network topology and

observe its performance

3.To analyze the traffic flow and the contents of protocol frames

Course Outcomes

1.Implement data link layer farming methods

2.Analyze error detection and error correction codes.

3.Implement and analyze routing and congestion issues in network design.

4.Implement Encoding and Decoding techniques used in presentation layer

5.To be able to work with different network tools

List of Experiments

1.Implement the data link layer framing methods such as character, character-stuffing

and bit stuffing.

2.Write a program to compute CRC code for the polynomials CRC-12, CRC-16 and CRC CCIP

3.Develop a simple data link layer that performs the flow control using the sliding window

protocol, and loss recovery using the Go-Back-N mechanism.

4.Implement Dijsktra’s algorithm to compute the shortest path through a network

5.Take an example subnet of hosts and obtain a broadcast tree for the subnet.

6.Implement distance vector routing algorithm for obtaining routing tables at each node.

7.Implement data encryption and data decryption

8.Write a program for congestion control using Leaky bucket algorithm.

9.Write a program for frame sorting technique used in buffers.

10.Wireshark
i.Packet Capture Using Wire shark

ii.Starting Wire shark

iii.Viewing Captured Traffic

iv.Analysis and Statistics & Filters.

11.How to run Nmap scan

12.Operating System Detection using Nmap

13.Do the following using NS2 Simulator

i.NS2 Simulator-Introduction

ii.Simulate to Find the Number of Packets Dropped

iii.Simulate to Find the Number of Packets Dropped by TCP/UDP

iv.Simulate to Find the Number of Packets Dropped due to Congestion

v.Simulate to Compare Data Rate& Throughput.

vi.Simulate to Plot Congestion for Different Source/Destination

vii.Simulate to Determine the Performance with respect to Transmission of Packets

Web Technologies Experiments

1.Write a PHP script to print prime numbers between 1-50.

2.PHP script to

a.Find the length of a string. b.Count no of words in a string. c. Reverse a string.

d.Search for a specific string.

3.Write a PHP script to merge two arrays and sort them as numbers, in descending order.

4.Write a PHP script that reads data from one file and write into another file.
5.Develop static pages (using Only HTML) of an online book store. The pages should resemble:

www.amazon.com. The website should consist the following pages.

a)Home page

b)Registration and user Login

c)User Profile Page

d)Books catalog

e)Shopping Cart

f)Payment By credit card

g)Order Conformation

6.Validate the Registration, user login, user profile and payment by credit card pages

using JavaScript.

7.Create and save an XML document on the server, which contains 10 users information. Write

a program, which takes User Id as an input and returns the user details by taking the

user information from the XML document.

8.Install TOMCAT web server. Convert the static web pages of assignments 2 into dynamic

web pages using servlets and cookies. Hint: Users information (user id, password, credit

card number) would be stored in web.xml. Each user should have a separate Shopping Cart.

9.Redo the previous task using JSP by converting the static web pages of assignments 2 into

dynamic web pages. Create a database with user information and books information.

The books catalogue should be dynamically loaded from the database. Follow the MVC

architecture while doing the website


1. Implement the data link layer framing methods such as character, character-stuffing
and bit stuffing.
#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 100

int main()
{
  char *p,*q;
  char temp;
  char in[MAXSIZE];
  char stuff[MAXSIZE];
  char destuff[MAXSIZE];
  
  int count=0;
  
  printf("enter the input character string (0‘s & 1‘s only):\n");
  scanf("%s",in);
  
  p=in;
  q=stuff;
  
  while(*p!='\0')
 {
    if(*p=='0')
  {
      *q=*p;
      q++;
      p++;
  }
    else
  {
      while(*p=='1' && count!=5)
   {
        count++;
        *q=*p;
        q++;
        p++;
   }
      
      if(count==5)
   {
        *q='0';
        q++;
   }
      count=0;
  }
 }
  *q='\0';
  printf("\nthe stuffed character string is");
  printf("\n%s",stuff);
  
  p=stuff;
  q=destuff;
  while(*p!='\0')
 {
    if(*p=='0')
  {
      *q=*p;
      q++;
      p++;
  }
    else
  {
      while(*p=='1' && count!=5)
   {
        count++;
        *q=*p;
        q++;
        p++;
   }
      if(count==5)
   {
        p++;
   }
      count=0;
  }
 }
  *q='\0';
  printf("\nthe destuffed character string is");
  printf("\n%s\n",destuff);
  return 0;

Output:
enter the input character string (0‘s & 1‘s only):
1010111111

the stuffed character string is


10101111101

the destuffed character string is

1 0 1 0 1 1 1 1 1 1 
C code for character stuffing

#include<stdio.h>

#include<conio.h>

void ins(char,int);

void del(int,int);

char fr[50];

main()

 int i,cnt=0,ch;

 clrscr();

 printf("Enter the frame:\t");

 gets(fr);

 /*Charecter Stuffing*/

            ins('s',0);

            ins('e',5);

            //printf("%s",fr);

            for(i=0;i<strlen(fr);i++)

            {

             if(fr[i]=='d'&&fr[i+1]=='l'&&fr[i+2]=='e'&&i!=3&&i!=strlen(fr)-3)

             {

              ins('m',i+3);i+=6;

             }

            }

            printf("\n\nStuffed bit is \t%s\t",fr);getch();

            /*Destuffing*/

            cnt=0;

            del(0,6);

            del(strlen(fr)-6,6);
            for(i=0;i<strlen(fr);i++)

            {

             if(fr[i]=='d'&&fr[i+1]=='l'&&fr[i+2]=='e')

             {

             cnt+=1;

             if(cnt==1)

             {         del(i,3);}

             }else

             {cnt=0;}

            }

            printf("\n\nDestuffed bit is \t%s",fr);getch();

            return 0;

 }

void ins(char in,int p)

 char dup[50];

 int i;

 strcpy(dup,fr);

            if(in=='s')

            {

             fr[p]='s';

             fr[p+1]='t';

             fr[p+2]='x';

             fr[p+3]='d';

             fr[p+4]='l';

             fr[p+5]='e';

            for(i=p+6;i<strlen(fr)+6;i++)

            {
             fr[i]=dup[i-6];

            }

            }

            if(in=='e')

            {

             strcat(fr,"etxdle");return;

            }

            if(in=='m')

            {

             fr[p]='d';

             fr[p+1]='l';

             fr[p+2]='e';

             for(i=p+3;i<strlen(fr)+3;i++)

             {

             fr[i]=dup[i-3];

             }

            }

            }

void del(int q,int n)

 int i;

            for(i=q;i<strlen(fr);i++)

            {

             fr[i]=fr[i+n];

            }

OUTPUT:
2. This Cyclic Redundancy Check is the most powerful and easy to implement
technique.Unlike checksum scheme, which is based on addition, CRC is based on binary
division. In CRC,a sequence of redundant bits, called cyclic redundancy check bits, are
appended to the end ofdata unit so that the resulting data unit becomes exactly divisible
by a second, predeterminedbinary number. At the destination, the incoming data unit is
divided by the same number. If atthis step there is no remainder, the data unit is assumed
to be correct and is therefore accepted.A remainder indicates that the data unit has been
damaged in transit and therefore must berejected.1. Bit strings are created as
representation of polynomials with coefficients ‘0’ and ‘1’only.2. A k-bit frame is regarded
as coefficients list for a polynomial with ‘k’ terms (xk-1 to x0 )Eg: x5 + x4 +x0 = 110001
When this method is used, the sender and the receiver should agree upon a
generatorpolynomial, G(x) in advance.Both the high and low order bits of G(x) must be
‘1’To compute checksum for some frame with ‘m’ bits ( polynomial = M(x), append ‘r’
zerobits to the lower end of the frame (r = degree of the generator polynomial) so that
thischeck summed frame is divisible by G(x).Divide M(x) by G(x) using modulo-2 division
and subtract the remainder from M(x) usingmodulo-2subtraction. let the resultant be
called as T(x)T(x) is passed to the receiver and the receiver divides it by G(x).If there is a
remainder, there has been a transmission error.
Eg: frame = 1101011011
G(x) = x4 +x +1 = 10011
è degree = 4
Therefore, frame = 1101011011 + 0000
èM(x) = 11010110110000
Commonly used divisor polynomials are:
CRC 12 : x12 + x11 + x3 + x2 + x + 1
CRC 16 : x16 + x15 + x2 + 1CRC
CCITT : x16 + x12 + x5 + 1

#define N strlen(g)

char t[28],cs[28],g[28];
int a,e,c,b;
void xor()
{
for(c=1;c<N;c++)
cs[c]=((cs[c]==g[c])?'0':'1');
}
void crc()
{
for(e=0;e<N;e++)
cs[e]=t[e];
do
{
if(cs[0]=='1')
xor();
for(c=0;c<N-1;c++)
cs[c]=cs[c+1];
cs[c]=t[e++];
}while(e<=a+N-1);
} int main()
{ int flag=0;
do{
printf("\n1.crc12\n2.crc16\ncrc ccit\n4.exit\n\nEnter your option.");
scanf("%d",&b);
switch(b)
{ case 1:strcpy(g,"1100000001111");
break;
case 2:strcpy(g,"11000000000000101");
break;
case 3:strcpy(g,"10001000000100001");
break;
case 4:return 0;
}
printf("\n enter data:");
scanf("%s",t);
printf("\n-----------------------\n");
printf("\n generating polynomial:%s",g);
a=strlen(t);
for(e=a;e<a+N-1;e++)
t[e]='0';
printf("\n--------------------------\n");
printf("mod-ified data is:%s",t);
printf("\n-----------------------\n");
crc();
printf("checksum is:%s",cs);
for(e=a;e<a+N-1;e++)
t[e]=cs[e-a];
printf("\n-----------------------\n");
printf("\n final codeword is : %s",t);
printf("\n------------------------\n");
printf("\ntest error detection 0(yes) 1(no)?:");
scanf("%d",&e);
if(e==0)
{
do{
printf("\n\tenter the position where error is to be inserted:");
scanf("%d",&e);
}
while(e==0||e>a+N-1);
t[e-1]=(t[e-1]=='0')?'1':'0';
printf("\n-----------------------\n");
printf("\n\terroneous data:%s\n",t);
} crc();
for(e=0;(e<N-1)&&(cs[e]!='1');e++);
if(e<N-1)
printf("error detected\n\n");
else
printf("\n no error detected \n\n");
printf("\n-----------------------");
}while(flag!=1);
} crc();
for(e=0;(e<N-1)&&(cs[e]!='1');e++);
if(e<N-1)
printf("error detected\n\n");
else
printf("\n no error detected \n\n");
printf("\n-----------------------");
}while(flag!=1);
Out Put
Output:
1.crc12
2.crc16
3.crc ccit
4.exit
Enter your option.1
enter data:1100110011100011
-----------------------
generating polynomial:1100000001111
-------------------------
mod-ified data is:11001100111000110000000000001100000001111
-----------------------
checksum is:1101110110001
-----------------------
final codeword is : 11001100111000111101110110001100000001111
------------------------
test error detection 0(yes) 1(no)?:1
no error detected
-----------------------
1.crc12
2.crc16
3.crc ccit
4.exit
Enter your option.2
enter data:11001100111000
-----------------------
generating polynomial:11000000000000101
------------------------
mod-ified data is:110011001110000000000000000000000000000000101
3. Develop a simple data link layer that performs the flow control using the sliding window
protocol
In computer networks sliding window protocol is a method to transmit data on a network.
Sliding window protocol is applied on the Data Link Layer of OSI model. At data link layer
data is in the form of frames. In Networking, Window simply means a buffer which has data
frames that needs to be transmitted.
Both sender and receiver agrees on some window size. If window size=w then after sending w
frames sender waits for the acknowledgement (ack) of the first frame.
As soon as sender receives the acknowledgement of a frame it is replaced by the next frames to
be transmitted by the sender. If receiver sends a collective or cumulative acknowledgement to
sender then it understands that more than one frames are properly received, for eg:- if ack of
frame 3 is received it understands that frame 1 and frame 2 are received properly.

In sliding window protocol the receiver has to have some memory to compensate any loss in
transmission or if the frames are received unordered.
Efficiency of Sliding Window Protocol
η = (W*tx)/(tx+2tp)
W = Window Size
tx = Transmission time
tp = Propagation delay
Sliding window works in full duplex mode
It is of two types:-
1. Selective Repeat: Sender transmits only that frame which is erroneous or is lost.
2. Go back n: Sender transmits all frames present in the window that occurs after the error bit
including error bit also.
Sliding Window Protocol Program in C
#include<stdio.h>
 
int main()
{
    int w,i,f,frames[50];
 
    printf("Enter window size: ");
    scanf("%d",&w);
 
    printf("\nEnter number of frames to transmit: ");
    scanf("%d",&f);
 
    printf("\nEnter %d frames: ",f);
 
    for(i=1;i<=f;i++)
        scanf("%d",&frames[i]);
 
    printf("\nWith sliding window protocol the frames will be sent in the following manner
(assuming no corruption of frames)\n\n");
    printf("After sending %d frames at each stage sender waits for acknowledgement sent by the
receiver\n\n",w);
 
    for(i=1;i<=f;i++)
    {
        if(i%w==0)
        {
            printf("%d\n",frames[i]);
            printf("Acknowledgement of above frames sent is received by sender\n\n");
        }
        else
            printf("%d ",frames[i]);
    }
 
    if(f%w!=0)
        printf("\nAcknowledgement of above frames sent is received by sender\n");
 
    return 0;
}

Output

Enter window size: 3


Enter number of frames to transmit: 5
Enter 5 frames: 12 5 89 4 6
With sliding window protocol the frames will be sent in the following manner (assuming no
corruption of frames)
After sending 3 frames at each stage sender waits for acknowledgement sent by the receiver
12 5 89
Acknowledgement of above frames sent is received by sender
46
Acknowledgement of above frames sent is received by sender
4. Implement Dijsktra’s algorithm to compute the shortest path through a network

/* Dijkstra's Algorithm in C */
#include<stdio.h>
#include<conio.h>
#include<process.h>
#include<string.h>
#include<math.h>
#define IN 99
#define N 6
int dijkstra(int cost[][N], int source, int target);
int main()
{
    int cost[N][N],i,j,w,ch,co;
    int source, target,x,y;
    printf("\t The Shortest Path Algorithm ( DIJKSTRA'S ALGORITHM in C \n\n");
    for(i=1;i< N;i++)
    for(j=1;j< N;j++)
    cost[i][j] = IN;
    for(x=1;x< N;x++)
    {
        for(y=x+1;y< N;y++)
        {
            printf("Enter the weight of the path between nodes %d and %d: ",x,y);
            scanf("%d",&w);
            cost [x][y] = cost[y][x] = w;
        }
        printf("\n");
    }
    printf("\nEnter the source:");
    scanf("%d", &source);
    printf("\nEnter the target");
    scanf("%d", &target);
    co = dijsktra(cost,source,target);
    printf("\nThe Shortest Path: %d",co);
}
int dijsktra(int cost[][N],int source,int target)
{
    int dist[N],prev[N],selected[N]={0},i,m,min,start,d,j;
    char path[N];
    for(i=1;i< N;i++)
    {
        dist[i] = IN;
        prev[i] = -1;
    }
    start = source;
    selected[start]=1;
    dist[start] = 0;
    while(selected[target] ==0)
    {
        min = IN;
        m = 0;
        for(i=1;i< N;i++)
        {
            d = dist[start] +cost[start][i];
            if(d< dist[i]&&selected[i]==0)
            {
                dist[i] = d;
                prev[i] = start;
            }
            if(min>dist[i] && selected[i]==0)
            {
                min = dist[i];
                m = i;
            }
        }
        start = m;
        selected[start] = 1;
    }
    start = target;
    j = 0;
    while(start != -1)
    {
        path[j++] = start+65;
        start = prev[start];
    }
    path[j]='\0';
    strrev(path);
    printf("%s", path);
    return dist[target];
}
5. Take an example subnet of hosts and obtain a broadcast tree for the subnet.
#include<stdio.h>
int a[10][10],n;
main()
{
int i,j,root;
clrscr();
printf(“Enter no.of nodes:”);
scanf(“%d”,&n);
printf(“Enter adjacent matrix\n”);
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
printf(“Enter connecting of %d–>%d::”,i,j);
scanf(“%d”,&a[i][j]);
}
printf(“Enter root node:”);
scanf(“%d”,&root);
adj(root);
}
adj(int k)
{
int i,j;
printf(“Adjacent node of root node::\n”);
printf(“%d\n\n”,k);
for(j=1;j<=n;j++)
{
if(a[k][j]==1 || a[j][k]==1)
printf(“%d\t”,j);
}
printf(“\n”);
for(i=1;i<=n;i++)
{
if((a[k][j]==0) && (a[i][k]==0) && (i!=k))
printf(“%d”,i);
}
}
OUTPUT
Enter no.of nodes:5
Enter adjacent matrix
Enter connecting of 1–>1::0
Enter connecting of 1–>2::1
Enter connecting of 1–>3::1
Enter connecting of 1–>4::0
Enter connecting of 1–>5::0
Enter connecting of 2–>1::1
Enter connecting of 2–>2::0
Enter connecting of 2–>3::1
Enter connecting of 2–>4::1
Enter connecting of 2–>5::0
Enter connecting of 3–>1::1
Enter connecting of 3–>2::1
Enter connecting of 3–>3::0
Enter connecting of 3–>4::0
Enter connecting of 3–>5::0
Enter connecting of 4–>1::0
Enter connecting of 4–>2::1
Enter connecting of 4–>3::0
Enter connecting of 4–>4::0
Enter connecting of 4–>5::1
Enter connecting of 5–>1::0
Enter connecting of 5–>2::0
Enter connecting of 5–>3::0
Enter connecting of 5–>4::1
Enter connecting of 5–>5::0
Enter root node:2

Adjacent node of root node::

2
134
5
6. Implement distance vector routing algorithm for obtaining routing tables at each node
/*
Distance Vector Routing in this program is implemented using Bellman Ford Algorithm:-
*/
#include<stdio.h>
struct node
{
unsigned dist[20];
unsigned from[20];
}rt[10];
int main()
{
int costmat[20][20];
int nodes,i,j,k,count=0;
printf("\nEnter the number of nodes : ");
scanf("%d",&nodes);//Enter the nodes
printf("\nEnter the cost matrix :\n");
for(i=0;i<nodes;i++)
{
for(j=0;j<nodes;j++)
{
scanf("%d",&costmat[i][j]);
costmat[i][i]=0;
rt[i].dist[j]=costmat[i][j];//initialise the distance equal to cost matrix
rt[i].from[j]=j;
}
}
do
{
count=0;
for(i=0;i<nodes;i++)//We choose arbitary vertex k and we calculate the direct distance
from the node i to k using the cost matrix
//and add the distance from k to node j
for(j=0;j<nodes;j++)
for(k=0;k<nodes;k++)
if(rt[i].dist[j]>costmat[i][k]+rt[k].dist[j])
{//We calculate the minimum distance
rt[i].dist[j]=rt[i].dist[k]+rt[k].dist[j];
rt[i].from[j]=k;
count++;
}
}while(count!=0);
for(i=0;i<nodes;i++)
{
printf("\n\n For router %d\n",i+1);
for(j=0;j<nodes;j++)
{
printf("\t\nnode %d via %d Distance %d ",j+1,rt[i].from[j]+1,rt[i].dist[j]);
}
}
printf("\n\n");
getch();
}
/*
A sample run of the program works as:-
Enter the number of nodes :
3
Enter the cost matrix :
027
201
710
For router 1
node 1 via 1 Distance 0
node 2 via 2 Distance 2
node 3 via 3 Distance 3
For router 2
node 1 via 1 Distance 2
node 2 via 2 Distance 0
node 3 via 3 Distance 1
For router 3
node 1 via 1 Distance 3
node 2 via 2 Distance 1
node 3 via 3 Distance 0
*/
7. Implement data encryption and data decryption

#include<stdio.h>
int main()
{
int i, cnt=0, p8[8]={6,7,8,9,1,2,3,4};
int p10[10]={6,7,8,9,10,1,2,3,4,5};

char input[11], k1[10], k2[10], temp[11];


char LS1[5], LS2[5];
//k1, k2 are for storing interim keys
//p8 and p10 are for storing permutation key

//Read 10 bits from user...


printf("Enter 10 bits input:");
scanf("%s",input);
input[10]='\0';

//Applying p10...
for(i=0; i<10; i++)
{
cnt = p10[i];
temp[i] = input[cnt-1];
}
temp[i]='\0';
printf("\nYour p10 key is    :");
for(i=0; i<10; i++)
{ printf("%d,",p10[i]); }

printf("\nBits after p10     :");


puts(temp);
//Performing LS-1 on first half of temp
for(i=0; i<5; i++)
{
if(i==4)
temp[i]=temp[0];
else
temp[i]=temp[i+1];
}
//Performing LS-1 on second half of temp
for(i=5; i<10; i++)
{
if(i==9)
temp[i]=temp[5];
else
temp[i]=temp[i+1];
}
printf("Output after LS-1  :");
puts(temp);

printf("\nYour p8 key is     :");


for(i=0; i<8; i++)
{ printf("%d,",p8[i]); }
//Applying p8...
for(i=0; i<8; i++)
{
cnt = p8[i];
k1[i] = temp[cnt-1];
}
printf("\nYour key k1 is     :");
puts(k1);
//This program can be extended to generate k2 as per DES algorithm.
}

Output of program

Enter 10 bits input:1100011100

Your p10 key is    :6,7,8,9,10,1,2,3,4,5,


Bits after p10     :1110011000
Output after LS-1  :1100110001

Your p8 key is     :6,7,8,9,1,2,3,4,


Your key k1 is     :10001100
8. Write a program for congestion control using Leaky bucket algorithm.
#include<stdio.h>

#include<stdlib.h>

struct packet

int time;

int size;

}p[50];

int main()

int i,n,m,k=0;

int bsize,bfilled,outrate;

printf("Enter the number of packets: ");

scanf("%d",&n);

printf("Enter packets in the order of they are arrival time\n");

for(i=0;i<n;i++)

printf("Enter the time and size: ");

scanf("%d%d",&p[i].time,&p[i].size);

printf("Enter the bucket size: ");

scanf("%d",&bsize);
printf("Enter the output rate: ");

scanf("%d",&outrate);

m=p[n-1].time;

i=1;

k=0;

bfilled=0;

while(i<=m || bfilled!=0)

printf("\n\nAt time %d",i);

if(p[k].time==i )

if(bsize>=bfilled + p[k].size)

bfilled=bfilled + p[k].size;

printf("\n%d byte packet is inserted",p[k].size);

k=k+1;

else

printf("\n%d byte packet is discarded",p[k].size);

k=k+1;

}
if(bfilled==0)

printf("\nNo packets to transmitte");

else if(bfilled>=outrate)

bfilled=bfilled-outrate;

printf("\n%d bytes transfered",outrate);

else

printf("\n%d bytes transfered",bfilled);

bfilled=0;

printf("\nPackets in the bucket %d byte",bfilled);

i++;

} return o; }

9. Write a program for frame sorting technique used in buffers.

#include<stdio.h>
#include<string.h>
#define FRAM_TXT_SIZ 3
#define MAX_NOF_FRAM 127
char str[FRAM_TXT_SIZ*MAX_NOF_FRAM];
struct frame // structure maintained to hold frames
{ char text[FRAM_TXT_SIZ];
int seq_no;
}fr[MAX_NOF_FRAM], shuf_ary[MAX_NOF_FRAM];
int assign_seq_no() //function which splits message
{ int k=0,i,j; //into frames and assigns sequence no
for(i=0; i < strlen(str); k++)
{ fr[k].seq_no = k;
for(j=0; j < FRAM_TXT_SIZ && str[i]!='\0'; j++)
fr[k].text[j] = str[i++];
}
printf("\nAfter assigning sequence numbers:\n");
for(i=0; i < k; i++)
printf("%d:%s ",i,fr[i].text);
return k; //k gives no of frames
}
void generate(int *random_ary, const int limit) //generate array of random nos
{ int r, i=0, j;
while(i < limit)
{ r = random() % limit;
for(j=0; j < i; j++)
if( random_ary[j] == r )
break;
if( i==j ) random_ary[i++] = r;
} }
void shuffle( const int no_frames ) // function shuffles the frames
{
int i, k=0, random_ary[no_frames];
generate(random_ary, no_frames);
for(i=0; i < no_frames; i++)
shuf_ary[i] = fr[random_ary[i]];
printf("\n\nAFTER SHUFFLING:\n");
for(i=0; i < no_frames; i++)
printf("%d:%s ",shuf_ary[i].seq_no,shuf_ary[i].text);
}
void sort(const int no_frames) // sorts the frames
{
int i,j,flag=1;
struct frame hold;
for(i=0; i < no_frames-1 && flag==1; i++) // search for frames in sequence
{
flag=0;
for(j=0; j < no_frames-1-i; j++) //(based on seq no.) and display
if(shuf_ary[j].seq_no > shuf_ary[j+1].seq_no)
{
hold = shuf_ary[j];
shuf_ary[j] = shuf_ary[j+1];
shuf_ary[j+1] = hold;
flag=1;
}
}
}
int main()
{
int no_frames,i;
printf("Enter the message: ");
gets(str);
no_frames = assign_seq_no();
shuffle(no_frames);
sort(no_frames);
printf("\n\nAFTER SORTING\n");
for(i=0;i<no_frames;i++)
printf("%s",shuf_ary[i].text);
printf("\n\n");
}
10. Wireshark
1. Packet Capture Using Wire shark

Activity 1 - Start Wireshark[edit]


Two different methods for starting Wireshark are available. These include the Start menu and
the Run command box.
Method 1 - Start Menu[edit]
To start Wireshark using the Start menu:

1. Open the Start menu.
2. Select All Programs.
3. Select Wireshark.
Method 2 - Run Command[edit]
To start Wireshark using the Run command box:
1. Open the Start menu or press the Windows key + R.
2. Type Wireshark in the Run command box.
3. Press Enter.
Activity 2 - Open the Capture Interfaces Dialog Box[edit]
Three different methods for opening the Capture Interfaces dialog box are available. These
include the Capture menu, the Capture Interfaces toolbar button, and the Capture Interfaces
keyboard shortcut.
Method 1 - Capture Menu[edit]
To open the Capture Interfaces dialog box using the Capture menu:
1. Select the Capture menu.
2. Select Interfaces.
Method 2 - Capture Interfaces Toolbar Button[edit]
To open the Capture Interfaces dialog box using the Capture interfaces Toolbar button:
1. Locate the toolbar button with the help text List the available capture interfaces. This
should be the first toolbar button on the left.
2. Click the Capture Interfaces toolbar button.
Method 3 - Capture Interfaces Keyboard Shortcut[edit]
To open the Capture Interfaces dialog box using the Capture interfaces keyboard shortcut:
1. Press <Ctrl> + I.
Activity 3 - Start a Wireshark Capture[edit]
To start a Wireshark capture from the Capture Interfaces dialog box:
1. Observe the available interfaces. If you have multiple interfaces displayed, look for the
interface with the highest packet count. This is your most active network interface.
2. Select the interface you want to use for the capture using the check box on the left.
3. Select Start to begin the capture.

11. How to Run Nmap Scan


What is Nmap?
Nmap (or “network mapper”) is one of the most popular free network discovery tools on the
market. Over the past decade or so the program has emerged as a core program for network
administrators looking to map out their networks and conduct extensive network inventories. It
allows the user to find live hosts on their network as well as scanning for open ports and
operating systems. In this guide, you will learn how to install and use Nmap.
Nmap runs centered around a command line similar to Windows Command Prompt, but a GUI
interface is available for more experienced users. When using Nmap, the user simply enters
commands and runs scripts via the text-driven interface. They can navigate through firewalls,
routers, IP filters, and other systems. At its core, Nmap was designed for enterprise-scale
networks and can scan through thousands of connected devices.
Some of Nmap’s main uses include port scanning, ping sweeps, OS detection, and version
detection. The program works by using IP packets to identify available hosts on a network as
well as what services and operating systems they run. Nmap is available on many different
operating systems from Linux to Free BSD and Gentoo. Nmap also has an extremely active and
vibrant user support community. In this article, we break down the fundamentals of Nmap to
help you hit the ground running.

Network Analysis and Packet Sniffing with Nmap


Network analyzers like Nmap are essential to network security for a number of reasons. They
can identify attackers and test for vulnerabilities within a network. When it comes to
cybersecurity, the more you know about your packet traffic, the better prepared you are for an
attack. Actively scanning your network is the only way to ensure that you stay prepared for
potential attacks.
As a network analyzer or packet sniffer, Nmap is extremely versatile. For example, it
allows the user to scan any IP active on their network. If you spot an IP you haven’t seen
before, you can run an IP scan to identify whether it is a legitimate service or an outside attack.
Nmap is the go-to network analyzer for many administrators because it offers a wide range of
functions for free.

Nmap Use Cases


For example, you can use Nmap to:

 Identify live hosts on your network


 Identify open ports on your network
 Identify the operating system of services on your network
 Address vulnerabilities in your network infrastructure

How to Run a Ping Scan


One of the basics of network administration is taking the time to identify active hosts on your
network. On Nmap, this is achieved through the use of a ping scan. A ping scan (also referred to
as a discover IP’s in a subnet command) allows the user to identify whether IP addresses are
online. It can also be used as a method of host discovery.  ARP ping scans are one of the best
ways to detect hosts within LAN networks.
To run an ARP ping scan, type the following command into the command line:
# nmap -sp 192.100.1.1/24
Nmap GUI Tools

Zenmap
As an alternative to the command line interface, NMap also offers a GUI called Zenmap. On
Zenmap you can create and execute commands and scans. The GUI is much more user-friendly
than the command line interface, making it ideal for newer users. The GUI can also show
graphical comparisons of service test results, for example:

How to Run a Simple Nmap Scan


Are you worried about the security of your network or the security of someone else's? Ensuring
that your router is protected from unwanted intruders is one of the foundations of a secure
network. One of the basic tools for this job is Nmap, or Network Mapper. This program will
scan a target and report which ports are open and which are closed, among other things.
Security specialists use this program to test the security of a network.
Method1

Using Zenmap
1 Download the Nmap installer. This can be found for free from the developer’s website. It is
highly recommended that you download directly from the developer to avoid any potential
viruses or fake files. Downloading the Nmap installer includes Zenmap, the graphical interface
for Nmap which makes it easy for newcomers to perform scans without having to learn
command lines.
 The Zenmap program is available for Windows, Linux, and Mac OS X. You can find
the installation files for all operating systems on the Nmap website.

2 Install Nmap. Run the installer once it is finished downloading. You will be asked which
components you would like to install. In order to get the full benefit of Nmap, keep all of these
checked. Nmap will not install any adware or spyware.
2.

3 Run the “Nmap – Zenmap” GUI program. If you left your settings at default during
installation, you should be able to see an icon for it on your desktop. If not, look in your Start
menu. Opening Zenmap will start the program.

3.
4 Enter in the target for your scan. The Zenmap program makes scanning a fairly simple
process. The first step to running a scan is choosing your target. You can enter a domain
(example.com), an IP address (127.0.0.1), a network (192.168.1.0/24), or a combination of
those.
 Depending on the intensity and target of your scan, running an Nmap scan may be
against the terms of your internet service provider, and may land you in hot water.
Always check your local laws and your ISP contract before performing Nmap scans on
targets other than your own network.

4.

5 Choose your Profile. Profiles are preset groupings of modifiers that change what is scanned.
The profiles allow you to quickly select different types of scans without having to type in the
modifiers on the command line. Choose the profile that best fits your needs:[1]
 Intense scan - A comprehensive scan. Contains Operating System (OS) detection,
version detection, script scanning, traceroute, and has aggressive scan timing. This is
considered an intrusive scan.
 Ping scan - This scan simply detects if the targets are online, it does not scan any ports.
 Quick scan - This is quicker than a regular scan due to aggressive timing and only
scanning select ports.
 Regular scan - This is the standard Nmap scan without any modifiers. It will
return ping and return open ports on the target.

5.

6 Click Scan to start scanning. The active results of the scan will be displayed in the Nmap
Output tab. The time the scan takes will depend on the scan profile you chose, the physical
distance to the target, and the target’s network configuration.

6.

7Read your results. Once the scan is finished, you’ll see the message “Nmap done” at the
bottom of the Nmap Output tab. You can now check your results, depending on the type of scan
you performed. All of the results will be listed in the main Nmap Output tab, but you can use
the other tabs to get a better look at specific data.[2]
 Ports/Hosts - This tab will show the results of your port scan, including the services for
those ports.

 Topology - This shows the traceroute for the scan you performed. You can see how
many hops your data goes through to reach the target.

 Host Details - This shows a summary of your target learned through scans, such as the
number of ports, IP addresses, hostnames, operating systems, and more.

 Scans - This tab stores the commands of your previously-run scans. This allows you to
quickly re-scan with a specific set of parameters.
12. Operating System Detection using Nmap

OS Detection Process

Before we get into the actual command and performing an OS Detection we should cover some
details about what is happening during this scan.

There are five separate probes being performed. Each probe may consist of one or more packets.
The response to each packet by the target system helps to determine the OS type.

The five different probes are:

1. Sequence Generation
2. ICMP Echo
3. TCP Explicit Congestion Notification
4. TCP
5. UDP

Now we can look at these individually to see what they are doing.

Sequence Generation

The Sequence Generation Probe consists of six packets. The six packets are sent 100 ms apart
and are all TCP SYN packets.

The result of each TCP SYN packet will help NMAP determine the OS type.

ICMP Echo

Two ICMP Request packets are sent to the target system with varying settings in the packet.

The resulting responses will help verify the OS type by NMAP.

TCP Explicit Congestion Notification

When a lot of packets are being generated and passing through a router causing it to be
burdened is known as congestion. The result is that systems slow down to reduce congestion so
the router is not dropping packets.

The packet being sent is only to get a response from the target system. Specific values returned
are used to determine the specific OS since each OS handles the packets in different ways.

TCP
Six packets are sent during this probe.

Some packets are sent to open or closed ports with specific packet settings. Again, the results
will vary depending on the target OS.

The TCP Packets are all sent with varying flags as follows:

1. no flags
2. SYN, FIN, URG and PSH
3. ACK
4. SYN
5. ACK
6. FIN, PSH, and URG

UDP

This probe consists of a single packet sent to a closed port.

If the port used on the target system is closed and an ICMP Port Unreachable message is
returned then there is no Firewall.

NMAP OS Detection Command

Now we need to run the actual command to perform an OS Detection. If you have read any of
the other of my NMAP articles then it is best not to perform a PING. To skip the PING we use
the parameter ‘-Pn’. To see the extra information we may require you should use the ‘-v’
parameter for adding verbosity. Specifically to get the OS Detection the parameter ‘-O’ is
needed.

For the command to complete properly and perform the TCP SYN Scan you need to perform
the command as ROOT. In my case, I will perform the scan on one system only and not the
whole network so the command would be:

sudo nmap -v -Pn -O 192.168.0.63

The results of the scan are shown in Figure 2. The scan shows that there are seven open ports
using a SYN Stealth Scan.

FIGURE 2
The open ports are:

1. 21/tcp ftp
2. 22/tcp ssh
3. 111/tcp rpcbind
4. 139/tcp netbios-ssn
5. 445/tcp microsoft-ds
6. 2049/tcp nfs
7. 54045/tcp unknown

The MAC Address of the system is 00:1E:4F:9F F:7F.

The final portion shows the OS type:

Device type: general purpose


Running: Linux 3.X|4.X
OS CPE: cpe:/o:linux:linux_kernel:3 cpe:/o:linux:linux_kernel:4
OS details: Linux 3.2 - 4.6
The system is running Ubuntu Server 16.10 and the Linux Kernel is 4.8.

13. Do the following using NS2 Simulator


i. NS2 Simulator-Introduction
ii. Simulate to Find the Number of Packets Dropped
iii. Simulate to Find the Number of Packets Dropped by TCP/UDP
iv. Simulate to Find the Number of Packets Dropped due to Congestion
v. Simulate to Compare Data Rate& Throughput.
vi. Simulate to Plot Congestion for Different Source/Destination
vii. Simulate to Determine the Performance with respect to Transmission of Packets

i) NS2 Simulator-Introduction
1. What is NS2
NS2 stands for Network Simulator Version 2. It is an open-source event-driven simulator
designed specifically for research in computer communication networks.

2. Features of NS2
1. It is a discrete event simulator for networking research.
2. It provides substantial support to simulate bunch of protocols like TCP, FTP, UDP, https and
DSR.
3. It simulates wired and wireless network.
4. It is primarily Unix based.
5. Uses TCL as its scripting language.
6. Otcl: Object oriented support
7. Tclcl: C++ and otcl linkage
8. Discrete event scheduler
3. Basic Architecture
NS2 consists of two key languages: C++ and Object-oriented Tool Command Language (OTcl).
While the C++ defines the internal mechanism (i.e., a backend) of the simulation objects, the
OTcl sets up simulation by assembling and configuring the objects as well as scheduling
discrete events. The C++ and the OTcl are linked together using TclCL
ii) Simulate to Find the Number of Packets Dropped

set ns [ new Simulator ]

set tf [ open abc.tr w ]


$ns trace-all $tf

set nf [ open exp1.nam w ]


$ns namtrace-all $nf

 The below code is used to create the nodes. set n0


[$ns node]

set n1 [$ns node] set


n2 [$ns node]
set n3 [$ns node]

#This is used to give color to the packets.


$ns color 1 "red"
$ns color 2 "blue"
$n0 label "Source/udp0"

$n1 label "Source/udp1"


$n2 label "Router"
$n3 label "Destination/Null"

#Vary the below Bandwidth and see the number of packetsdropped. $ns duplex-
link $n0 $n2 100Mb 300ms DropTail

$ns duplex-link $n1 $n2 10Mb 300ms DropTail $ns


duplex-link $n2 $n3 1Mb 300ms DropTail

#The below code is used to set the queue size b/w the nodes $ns set
queue-limit $n0 $n2 1 $ns set queue-limit $n1 $n2 1
$ns set queue-limit $n2 $n3 1

#The below code is used to attach an UDP agent to n0, UDP #agent to
n1 and null agent to n3. set udp0 [new Agent/UDP]
$ns attach-agent $n0 $udp0
set cbr0 [new Application/Traffic/CBR]
$cbr0 attach-agent $udp0
set null3 [new Agent/Null]
$ns attach-agent $n3 $null3
set udp1 [new Agent/UDP]
$ns attach-agent $n1 $udp1
set cbr1 [new Application/Traffic/CBR]
$cbr1 attach-agent $udp1
#The below code sets the udp0 packets to red and udp1 #packets
to blue color
$udp0 set class_ 1
$udp1 set class_ 2

#The below code is used to connect the agents.

$ns connect $udp0 $null3


$ns connect $udp1 $null3

#The below code is used to set the packet size to 500 $cbr1
set packetSize_ 500Mb

#The below code is used to set the interval of the packets,


#i.e., Data rate of the packets. if the data rate is high
#then packets drops are high.

$cbr1 set interval_ 0.005


proc finish { } {
global ns nf tf
$ns flush-trace

exec nam exp1.nam &


close $tf
close $nf
exit 0
}
$ns at 0.1 "$cbr0 start"
$ns at 0.1 "$cbr1 start"
$ns at 10.0 "finish"
$ns run

awk script
BEGIN{
#include<stdio.h>
count=0;
}
{
if($1=="d") #d stands for the packets drops.
count++

}
END{
printf("The Total no of Packets Dropped due to Congestion :%d\n\n", count)
}
4. Simulate to Find the Number of Packets Dropped due to Congestion

set ns [new Simulator]


set tf [open exp2.tr w]
$ns trace-all $tf
set nf [open exp2.nam w]
$ns namtrace-all $nf
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]
set n5 [$ns node]
set n6 [$ns node]
$n0 label "Ping0"
$n4 label "Ping4"
$n5 label "Ping5"
$n6 label "Ping6"
$n2 label "Router"
$ns color 1 "red"
$ns color 2 "green"
$ns duplex-link $n0 $n2 100Mb 300ms DropTail
$ns duplex-link $n2 $n6 1Mb 300ms DropTail
$ns duplex-link $n5 $n2 100Mb 300ms DropTail
$ns duplex-link $n2 $n4 1Mb 300ms DropTail
$ns duplex-link $n3 $n2 1Mb 300ms DropTail
$ns duplex-link $n1 $n2 1Mb 300ms DropTail

$ns queue-limit $n0 $n2 5


$ns queue-limit $n2 $n6 2
$ns queue-limit $n2 $n4 3
$ns queue-limit $n5 $n2 5

#The below code is used to connect between the ping agents #to the
node n0, n4 , n5 and n6.
set ping0 [new Agent/Ping]
$ns attach-agent $n0 $ping0

set ping4 [new Agent/Ping]


$ns attach-agent $n4 $ping4
set ping5 [new Agent/Ping]
$ns attach-agent $n5 $ping5

set ping6 [new Agent/Ping]


$ns attach-agent $n6 $ping6

$ping0 set packetSize_ 50000


$ping0 set interval_ 0.0001
$ping5 set packetSize_ 60000
$ping5 set interval_ 0.00001
$ping0 set class_ 1
$ping5 set class_ 2

$ns connect $ping0 $ping4


$ns connect $ping5 $ping6

#The below function is executed when the ping agent receives


#a reply from the destination
Agent/Ping instproc recv {from rtt} {
$self instvar node_
puts " The node [$node_ id] received an reply from $from with round trip
time of $rtt"
}
proc finish {} {
global ns nf tf
exec nam exp2.nam &
$ns flush-trace
close $tf
close $nf
exit 0
}
#The below code makes the link down(failure) at 0.9 from n2 #to n6 and
when the time becomes 1.5 the link between n2 to #n6 is enabled.
$ns rtmodel-at 0.9 down $n2 $n6
$ns rtmodel-at 1.5 up $n2 $n6
$ns at 0.1 "$ping0 send"
$ns at 0.2 "$ping0 send"
$ns at 0.3 "$ping0 send"
$ns at 0.4 "$ping0 send"
$ns at 0.5 "$ping0 send"
$ns at 0.6 "$ping0 send"
$ns at 0.7 "$ping0 send"
$ns at 0.8 "$ping0 send"
$ns at 0.9 "$ping0 send"
$ns at 1.0 "$ping0 send"
$ns at 1.1 "$ping0 send"
$ns at 1.2 "$ping0 send"
$ns at 1.3 "$ping0 send"
$ns at 1.4 "$ping0 send"
$ns at 1.5 "$ping0 send"
$ns at 1.6 "$ping0 send"
$ns at 1.7 "$ping0 send"
$ns at 1.8 "$ping0 send"
$ns at 0.1 "$ping5 send"
$ns at 0.2 "$ping5 send"
$ns at 0.3 "$ping5 send"
$ns at 0.4 "$ping5 send"
$ns at 0.5 "$ping5 send"
$ns at 0.6 "$ping5 send"
$ns at 0.7 "$ping5 send"
$ns at 0.8 "$ping5 send"
$ns at 0.9 "$ping5 send"
$ns at 1.0 "$ping5 send"
$ns at 1.1 "$ping5 send"
$ns at 1.2 "$ping5 send"
$ns at 1.3 "$ping5 send"
$ns at 1.4 "$ping5 send"
$ns at 1.5 "$ping5 send"
$ns at 1.6 "$ping5 send"
$ns at 1.7 "$ping5 send"
$ns at 1.8 "$ping5 send"
$ns at 5.0 "finish"
$ns run

awk script

BEGIN{
#include<stdio.h>
count=0;
}
{
if($1=="d")
count++
}
END{
printf("The Total no of Packets Dropped due toCongestion:%d \n", count)
}
Web Technologies Experiments
1. Write a PHP script to print prime numbers between 1-50.

<?php
$number=2 ;
echo "Prime Numbers between 1 – 50 are : <br>";
while($number < 50 )
{
$div_count=0;
for( $i=2;$i<=$number/2;$i++)
{
if(($number%$i)==0)
{
$div_count++;
}
}
if($div_count<3)
{
echo $number." , ";
}
$number=$number+1;
}
?>
Output:
Prime Numbers between 1 – 50 are :
2 , 3 , 5 , 7 , 11 , 13 , 17 , 19 , 23 , 29 , 31 , 37 , 41 , 43 , 47

2. PHP script to
a. Find the length of a string.
b. Count no of words in a string.
c. Reverse a string.
d. Search for a specific string

a) Find the length of a string


<?php
echo “Length of string Hello is : “.strlen("Hello");
?>
Output: Length of string Hello is : 5

b.) Count the number of words found in the string "Hello World!":
<?php
echo “ No.of words found in string Hello World! is : “.str_word_count("Hello world!");
?>
Output: . No.of words found in string Hello World! is : 2
c.)Reverse a string.
Reverse the string "Hello World!":
<?php
echo "Reverse of given String Hello World <br>";
echo strrev("Hello World!");
?>
Output: Reverse of given String Hello World
!dlroW olleH
d). Search for a specific string
<?php
$word = "fox";
$mystring = "The quick brown fox jumps over the lazy dog";
if(strpos($mystring, $word) !== false){
echo " Given String = ".$mystring;
echo "<br> Search string = ".$word;
echo "<br> Seach key ".$word." found at ".strpos($mystring, $word)." th Position in the given
string ";
} else{
echo $word."Not Found!";
}
?>
Output:
Given String = The quick brown fox jumps over the lazy dog
Search string = fox
Search string fox found at 16 th Position in the given string
3.Write a PHP script to merge two arrays and sort them as numbers, in descending order.
<?php
$a1=array(1,3,15,7,5);
$a2=array(4,3,20,1,6);
echo " elements in Array A are ";
print_r($a1);
echo "<br>";
echo " elements in Array B are ";
print_r($a2);
echo "<br>";
echo " array elements after merging are <br>";
$num=array_merge($a1,$a2);
print_r($num);
echo "<br> Array elements after sorting in Descending Order is <br>";
array_multisort($num,SORT_DESC,SORT_NUMERIC);
print_r($num);
?>

Output:
Elements in Array A are Array ( [0] => 1 [1] => 3 [2] => 15 [3] => 7 [4] => 5 )
Elements in Array B are Array ( [0] => 4 [1] => 3 [2] => 20 [3] => 1 [4] => 6 )
array elements after merging are
Array ( [0] => 1 [1] => 3 [2] => 15 [3] => 7 [4] => 5 [5] => 4 [6] => 3 [7] => 20 [8] => 1 [9] =>
6)
Array elements after sorting in Descending Order is
Array ( [0] => 20 [1] => 15 [2] => 7 [3] => 6 [4] => 5 [5] => 4 [6] => 3 [7] => 3 [8] => 1 [9] =>
1)
4. Write a PHP script that reads data from one file and write into another file
<?php
$filename = "sample.txt";
$file = fopen( $filename, "r" );
if( $file == false ) {
echo ( "Error in opening file" );
exit();
}
echo " <br> Contents of file sample.txt is <br>";
while(!feof($file))
echo fgets($file);
fclose($file);
$file=fopen("sample.txt","r");
$f2="write.txt";
$file1=fopen($f2,"w");
while(!feof($file))
{
$str=fgets($file);
fwrite($file1,$str);
}
fclose($file);
fclose($file1);
echo " <br> Contents of file write.txt is <br>";
$file1=fopen("write.txt","r");
while(!feof($file1))
echo fgets($file1);
fclose($file1);
?>

Output:
Contents of file sample.txt is
Hello Welcome to VMTW WT Lab
Contents of file write.txt is
Hello Welcome to VMTW WT Lab
5. Develop static pages (using only HTML) of an online Book store. The pages should
resemble: www.amazon.com. The website should consist the following pages.

• Home page
• Registration and user Login
• User profile page
• Books catalog
• Shopping cart
• Payment by credit card Order Conformation

PROCEDURE:

Home page

Main.html:

<html>

<head>

<title>Amazon</title>

</head>

<body bgcolor="cyan"> <center>

<strong><h1>Welcome to AMAZON</h1></strong>

<form method="post" action="login.html" target=_blank >

<h4>for books</h4><input type="submit" value="click here">

</form>

</center>

</body>

</html>

Registration and user Login


Login.html:

<html>

<head>

<title>login page</title>

</head>

<body bgcolor="cyan"> <center>

<strong><h1> AMAZON </h1></strong></center> <right>

<table align="right">

<tr>

<td><h4>user name</td>

<td><input type="text" ></td>

<td></td>

</tr>

<tr>

<td><h4>password</td>

<td><input type="password"></td>

<td></td>

</tr>

<tr>

<td>

<form method="post" action="catalog.html" >

<input type="submit" value="submit" >

</form>

</td>

<td>

<form method="post" action="userpro.html" >

<input type="submit" value="register" >

&nbsp;&nbsp;
<input type="reset" value="reset"></form></td> </tr>

</table>

</body>

</html>

User profile page

Userpro.html:

<html>

<head>

<title>

login page</title>

</head>

<body bgcolor="cyan">

<center><strong><h1> AMAZON </h1></strong></center> <form method="post"


action="catalog.html" > <right>

<table align="left">

<tr>

<td><h4>user name</td>

<td><input type="text" ></td>

<tr>

<tr>

<td><h4>password</td>

<td><input type="password"></td>

</tr>

<tr>

<td><h4>confirm password</td>

<td><input type="password"></td>

</tr>

<tr>

<td><h4>male &nbsp;&nbsp;
<option >

<input type="radio" name="sex" id="male"></td> <td><h4>female &nbsp; &nbsp;

<input type="radio" name="sex" id="female" ></td>

</option>

</tr>

<tr>

<td>Address</td>

<td><textarea name="address" rows=5 cols=19>

</textarea>

</td>

<tr>

<td>

<input type="submit" value="submit" ></td>

<td>

<input type="reset" value="reset"></td>

</tr>

</form>

</body>

</html>
Books catalog

Catalog.html:

<html>

<head>

<title>

books catalog</title>

</head>

<body bgcolor="cyan">

<center><h1>AMAZON</h1></center>

<form method="post" action="shopping.html">

<left>

<table>

<tr>

<td><b><h3>frontend books</td>

<td></td></tr>

<tr>

<td></td>

<td><h4>C&Ds</td>

</tr>

<tr>

<td></td>

<td><h4>Ads</td>

</tr>

<tr>

<td></td>

<td><h4>JAVA

</td></tr>

<tr>
<td><b><h3>backend books</td>

<td></td>

</tr>

<tr>

<td></td>

<td><h4>Oracle</td>

</tr>

<tr>

<td></td>

<td><h4>Ms SQL Server

</td></tr>

<tr>

<td></td>

<td><h4>MySql </td>

</tr>

</table>

</h4>

<center>

<b>for buy one of these books

<br>

</b><input type="submit" value="click here">

</center>

</form>

</body>

</html>
Shopping cart

Shopping.html:

<html>

<head><title>shopping cart</title>

</head>

<body bgcolor="cyan">

<center><h1>

Shopping Cart</h1></center>

<br><br><br><br><br>

<table align="center">

<tr>

<td>Text Books</td>

<td>

<select >

<optgroup label="select the book">

<option value="C&Ds">C&Ds

<option value="Ads">Ads

<option value="Java">Java

<option value="Oracle">Oracle

<option value="Ms SQL Server">Ms SQL Server <option value="MySql">MySql </optgroup>

</select>

</td></tr>

<tr>

<td>

Quantity</td>

<td>

<input type="text" id="q">

</td></tr>
<tr>

<td></td>

<td>

<form method=post action="payment.html">

<input type="submit" value=ok />

</form>

</td></tr>

</table>

<center>

<pre>Cost of one book is"500" + shipping "100"</pre>

</center>

<body>

</html>
Payment by credit card

Payment.html:

<html>

<head><title>payment</title></head>

<body bgcolor="cyan">

<center><h1>Payment By Credit Card</h1></center>

<form method=post action="ordrconform.html">

<br><br><br><br><br>

<table align="center">

<tr>

<td>

<h4>Total Amount</h4></td>

<td><input type="text">

</td>

</tr>

<tr>

<td><h4>Credit Card Number</td>

<td><input type="text"></td>

</tr>

<tr>

<td>

</td>

<td><input type="submit" value=OK>

</td>

</tr>

</table>

</form></body>

</html>
Order Conformation

Ordrconform.html

<html>

<head><title>order conformation</title><M/head>

<body bgcolor="cyan">

<center>

<h1><b>BOOK SHOPPING</h1>

<pre><strong>

<b>Your order Is Conformed

</strong></pre>

<h2><b>THANK YOU</h2>

</center>

</body></html>

OUTPUT:
6. Validate the Registration, user login, user profile and payment by credit card pages
using
JavaScript.
Main.html:

<html>

<frameset rows="25%,*">

<frame src="top.html" name="top" scrolling ="no" frameborder ="0">

<frameset cols="25%,75%">

<frame src="left.html" name="left" scrolling ="no" frameborder ="0">

<frame src="right.html" name="right" scrolling ="auto" frameborder ="0">

</frameset>

</frameset>

</html>

Top.html:

<html>

<body bgcolor="pink">

<br><br>

<marquee><h1 align=”center”><b><u>ONLINE BOOK


STORAGE</u></b></h1></marquee>

</body>

</html>

Right.html:

<html>

<body>

<br><br><br><br><br>

<h2 align="center">

<b><p> welcome to online book storage. Press login if you are

having id otherwise press registration.

</p></b></h2>

</body> </html>
Left.html:

<html>

<body bgcolor="pink">

<h3>

<ul>

<li><a href="login.html" target="right"><font color="black">

LOGIN</font></a></li><br><br>

<li><a href="profile.html" target="right"><font color="black">

USER PROFILE</font></a></li><br><br>

<li><a href="catalog.html" target="right"><font color="black">

BOOKS CATALOG</font></a></li><br><br>

<li><a href="scart.html" target="right"><font color="black">

SHOPPINGCART</font></a></li><br><br>

<li><a href="payment.html" target="right"><font color="black">

PAYMENT</font></a></li><br><br>

<br><br>

</ul>

</body>

</html>
Login.html:

<html>

<body bgcolor="pink"><br><br><br>

<script language="javascript">

function validate()

var flag=1;

if(document.myform.id.value==""||

document.myform.pwd.value=="")

alert("LoginId and Password must be filled")

flag=0;

if(flag==1)

alert("VALID INPUT");

window.open("catalog.html","right");

else

alert("INVALID INPUT");

//document.myform.focus();

</script>

<form name="myform">

<div align="center"><pre>

LOGIN ID:<input type="text" name="id"><br>


PASSWORD:<input type="password" name="pwd"><br><br>

</pre>

<input type="button" value="ok" onClick="validate()">&nbsp;&nbsp;&nbsp;&nbsp;

<input type="reset" value="clear" >

</div>

</form>

</body>

</html>

Profile.html

<html>

<body bgcolor="pink"><br><br>

<script type="text/javascript">

function validate()

var flag=1;

if(document.myform.name.value==""||

document.myform.addr.value==""||

document.myform.phno.value==""||

document.myform.id.value==""||

document.myform.pwd.value=="")

alert("Enter all the details");

flag=0;

var str=document.myform.phno.value;

var x=new RegExp("\\d","g");

if(!(str.match(x)))

{
if(!(str.length==10))

flag=0;

var str1=document.myform.id.value;

var x1=new RegExp("^[A-Z][a-zA-Z]+$","g");

if(!(str1.match(x1)))

flag=0;

alert("Invalid UserID");

var str1=document.myform.pwd.value;

var x1=new RegExp("^[A-Z][a-zA-Z]+$","g");

if(!(str1.match(x1)))

flag=0;

alert("Invalid password");

if(flag==1)

alert("VALID INPUT");

window.self.location.href="login.html";

else

alert("INVALID INPUT");

document.myform.focus();

}
</script>

<form name="myform">

<div align="center"><pre>

NAME :<input type="text" name="name"><br>

ADDRESS :<input type="type" name="addr"><br>

CONTACT NUMBER:<input type="text" name="phno"><br>

LOGINID :<input type="text" name="id"><br>

PASSWORD :<input type="password" name="pwd"></pre><br><br>

</div>

<br><br>

<div align="center">

<input type="button" value="ok" onClick="validate()">&nbsp;&nbsp;&nbsp;

<input type="reset" value="clear">

</form></body></html>

Scart.html:

<html>

<body bgcolor="pink"><br><br><br>

<script language="javascript">

function validate()

var flag=1;

if(document.myform.title.value=="")

flag=0;

str=document.myform.title.value;

if(str=="c"||str=="C")

{
document.myform.t1.value="C";

document.myform.t2.value=444;

else if(str=="jsp"||str=="JSP")

document.myform.t1.value="JSP";

document.myform.t2.value=555;

else

flag=0;

if(flag==1)

alert("VALID INPUT");

else

alert("INVALID INPUT");

document.myform.focus();

</script>

<form name="myform" action="payment.html" target="right">

<div align="center"><pre>BOOK TITLE :<input type="text" name="title"><br>

</pre><br><br>Book Title: <input type="text" name="t1" disabled>

Book Cost: <input type="text" name="t2" disabled>

</div>
<br><br>

<div align="center">

<input type="submit" value="ok" onClick="validate()">&nbsp;&nbsp;&nbsp;&nbsp;

<input type="reset" value="clear">

<input type="submit" value="Purchase">

</form>

</body>

</html>

•Shopping cart:
Catalog.html:
<html>
<body bgcolor="pink"><br><br><br>
<script language="javascript">
function validate()
{
var flag=1;
if(document.myform.id.value==""||
document.myform.title.value==""||
document.myform.no.value==""||
document.myform.cost.value=="")
{
flag=0;
}
str=document.myform.title.value;
var str1=document.myform.cost.value;
if(!((str=="c"&& str1==444) || (str=="jsp" && str1==555)))
{
flag=0;
}
if(flag==1)
{
alert("VALID INPUT");
else }
{

alert("INVALID INPUT");
document.myform.focus();
} }

</script>
<form name="myform"action="scart.html" target="right">
<div align="center"><pre>
LOGIN ID :<input type="text" name="id"><br>
TITLE :<input type="text" name="title"><br>
NO.OF BOOKS :<input type="text" name="no"><br>
COST OF BOOK:<input type="text"name="cost"><br>
</pre><br><br>
</div>
<br><br>
<div align="center">
<input type="submit" value="ok" onClick="validate()"> &nbsp;&nbsp;&nbsp;&nbsp;
<input type="reset" value="clear">
</form>
</body>
</html>
• Payment by credit card
Payment.html:
<html>
<body bgcolor="pink"><br><br><br>
<script language="javascript">
function validate()
{
var flag=1;
if(document.myform.id.value==""|| document.myform.pwd.value==""||
document.myform.amount.value==""|| document.myform.num.value=="") {

flag=0;
}
var str=document.myform.amount.value;
var x=new RegExp("\\d","g");
if(!(str.match(x)))
{
flag=0;
}
var str1=document.myform.num.value;
var x1=new RegExp("\\d","g");

if(!(str.match(x1)))
{
flag=0;
}
if(flag==1)
{
alert("VALID INPUT");
window.self.location.href="order.html";
}
else
{
alert("INVALID INPUT");
document.myform.focus();
}
}
</script>
<form name="myform">
<div align="center"><pre>
LOGIN ID :<input type="text" name="id"><br>
PASSWORD :<input type="password" name="pwd"><br>
AMOUNT :<input type="text" name="amount"><br>
CREDITCARDNUMBER :<input type="PASSWORD" name="num"><br></pre><br><br>
</div>
<br><br>
<div align="center">
<input type="button" value="ok" onClick="validate()">&nbsp;&nbsp;&nbsp;&nbsp;
<input type="reset" value="clear" >
</form>
</body>
</html>

•Order Conformation
Order.html:

<html>
<head><title>order conformation</title><M/head>
<body bgcolor="cyan">
<center>
<h1><b>AMAZON</h1>
<pre><strong>
<b>Your order Is Conformed
</strong></pre>
<h2><b>THANK YOU</h2>
</center>
</body>
</html>
7. Create and save an XML document on the server, which contains 10 users information.
Write
a program, which takes User Id as an input and returns the user details by taking the user
information from the XML document.

User.xml

<?xml version="1.0" encoding="UTF-8"?>


<employees>
<employee id="501">
<firstName>Sunil</firstName>
<lastName>Yadav</lastName>
<location>Hyd</location>
</employee>
<employee id="502">
<firstName>Trilok</firstName>
<lastName>Reddy</lastName>
<location>Chevella</location>
</employee>
<employee id="503">
<firstName>Mallikarjun</firstName>
<lastName>Tiger</lastName>
<location>Forest</location>
</employee>
<employee id="504">
<firstName>Neelima</firstName>
<lastName>Lakshmi</lastName>
<location>MP</location>
</employee>
<employee id="505">
<firstName>Abhi</firstName>
<lastName>Shambu</lastName>
<location>LD</location>
</employee>
<employee id="506">
<firstName>Nikitha</firstName>
<lastName>Reddy</lastName>
<location>UP</location>
</employee>
<employee id="507">
<firstName>Ashwini</firstName>
<lastName>Reddy</lastName>
<location>ADB</location>
</employee>
<employee id="508">
<firstName>Vinod</firstName>
<lastName>Kumar</lastName>
<location>MGD</location>
</employee>
<employee id="509">
<firstName>Raghu</firstName>
<lastName>Reddy</lastName>
<location>MBD</location>
</employee>
<employee id="510">
<firstName>Uma Shankar</firstName>
<lastName>Kommana</lastName>
<location>DSNR</location>
</employee>
</employees>
EmployeeParsing.java
import org.w3c.dom.*;
import javax.xml.parsers.*;
import java.io.*;
public class EmployeeParsing {
public static void main(String[] args)throws Exception {
//Get Document Builder
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
//Build Document
Document document = builder.parse(new File("User.xml"));
Element root = document.getDocumentElement();
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter User Id");
String id=br.readLine();
//Get all employees
NodeList nList = document.getElementsByTagName("employee");
System.out.println(root.getNodeName());
System.out.println("============================");
for (int temp = 0; temp < nList.getLength(); temp++)
{
Node node = nList.item(temp);
System.out.println(""); //Just a separator
if (node.getNodeType() == Node.ELEMENT_NODE)
{
//Print employee's details of given id
Element eElement = (Element) node;
if(eElement.getAttribute("id").equals(id))
{
System.out.println("Employee id : " + eElement.getAttribute("id"));
System.out.println("First Name : "
+eElement.getElementsByTagName("firstName").item(0).getTextContent());
System.out.println("Last Name : "
+eElement.getElementsByTagName("lastName").item(0).getTextContent());
System.out.println("Location : "
+eElement.getElementsByTagName("location").item(0).getTextContent()); } } } }
Output:

C:\>javac EmployeeParsing.java
C:\>java EmployeeParsing
Enter User Id :
503
employees
==============
Employee Id: 503
First name: Mallikarjun
Last name:Tiger
Location : Forest
8. Install TOMCAT web server. Convert the static web pages of assignments 2 into
dynamic web pages using servlets and cookies. Hint: Users information (user id, password,
credit card number) would be stored in web.xml. Each user should have a separate
Shopping Cart.
PROCEDURE:
First install the tomcat into the system.
Then make a subdirectory(eg., tr) in the \tomcat\webapps.
Under tr create WEB-INF directory and also place the html files in this tr directory only.
Next under WEB-INF create two subclasses lib,classes and web.xml
Next place all the class files under the classes and jar files(servlet-api.jar,classes12.jar etc…)
under lib subdirectories.
After this start tomcat by giving the following command at the instll_dir>tomcat>bin
Catalina.bat run
At the I.E(web browser) give the url as http;//localhost:8080//tr/htmlfile or servlet url pattern
Portno 8080 is assigned for the tomcat.
Web.xml
<?xml version="1.0" encoding="iso-8859-1"?>
<servlet>
<servlet-name>reg</servlet-name>
<servlet-class>reg</servlet-class>
</servlet>
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>login</servlet-class>
</servlet>
<servlet>
<servlet-name>profile</servlet-name>
<servlet-class>profile</servlet-class>
</servlet>
<servlet>
<servlet-name>catalog</servlet-name>
<servlet-class>catalog</servlet-class>
<servlet-mapping>
<servlet-name>order</servlet-name>
<url-p</servlet>
<servlet>
<servlet-name>order</servlet-name>
<servlet-class>order</servlet-class>
</servlet>
attern>order</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>catalog</servlet-name>
<url-pattern>catalog</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>profile</servlet-name>
<url-pattern>profile</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>login</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>reg</servlet-name>
<url-pattern>reg</url-pattern>
</servlet-mapping>
</web-app>

Main.html

<html xmlns="http://www.w3.org/1999/xhtml">
<body bgcolor="pink">
<br /><br /><br /><br /><br />
<h1 align="center"><U>ONLINE BOOK STORAGE</U></h1><br /><br /><br />
<h2 align="center"><pre>
<b>Welcome to online book storage.
Press LOGIN if you are having id
otherwise press REGISTRATION
</b></pre></h2>
<br /><br /><pre>
<div align="center"><a href="/tr/login.html">LOGIN</a> <a href="/tr/reg.html">
REGISTRATION</a></div></pre>
</body>
</html>

Login.html

<html>
<body bgcolor="pink"><br /><br /><br />
<form name="myform" method="post" action="/tr/login">
<div align="center"><pre>
LOGIN ID :<input type="text" name="id" /><br />
PASSWORD :<input type="password" name="pwd" /></pre><br /><br />
</div>
<br /><br />
<div align="center">
<input type="submit" value="ok" onclick="validate()" />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="reset" value="clear" />
</div>
</form>
</body>
</html>

Reg.html

<html xmlns="http://www.w3.org/1999/xhtml">
<body bgcolor="pink"><br /><br />
<form name="myform" method="post" action="/tr/reg">
<div align="center"><pre>
NAME :<input type="text" name="name" /><br />
ADDRESS :<input type="text" name="addr" /><br />
CONTACT NUMBER :<input type="text" name="phno" /><br />
LOGINID :<input type="text" name="id" /><br />
PASSWORD :<input type="password" name="pwd" /></pre><br /><br />
</div>
<br /><br />
<div align="center">
<input type="submit" value="ok" onclick="validate()" />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="reset" value="clear" />
</div>
</form>
</body>
</html>

Profile.html

<html xmlns="http://www.w3.org/1999/xhtml">
<body bgcolor="pink"><br /><br /><br />
<form name="myform" method="post" action="/tr/profile">
<div align="center"><pre>
LOGIN ID :<input type="text" name="id" /><br />
</pre><br /><br />
</div>
<br /><br />
<div align="center">
<input type="submit" value="ok" onclick="validate()" />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="reset" value="clear" />
</div></form></body></html>

Catalog.html
<html xmlns="http://www.w3.org/1999/xhtml">
<body bgcolor="pink"><br /><br /><br />
<form method="post" action="/tr/catalog">
<div align="center"><pre>
BOOK TITLE :<input type="text" name="title" /><br />
</pre><br /><br />
</div>
<br /><br />
<div align="center">
<input type="submit" value="ok"
name="button1"/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<input type="reset" value="clear" name="button2"/>
</div>
</form>
</body></html>

Order.html

<html xmlns="http://www.w3.org/1999/xhtml">
<body bgcolor="pink"><br /><br />
<form method="post" action="/tr/reg">
<div align="center"><pre>
NAME :<input type="text" name="name" /><br />
PASSWORD :<input type="password" name="pwd" />
TITLE :<input type="text" name="title" /><br />
NO. OF BOOKS :<input type="text" name="no" /><br />
DATE :<input type="text" name="date" /><br />
CREDIT CARD NUMBER:<input type="password" name="cno" /><br /></pre><br /><br />
</div>
<br /><br />
<div align="center">
<input type="submit" value="ok" name="button1"/>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="reset" value="clear"
name="button2"/>
</div>
</form>
</body>
</html>
Login.java

import java.sql.*;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class login extends HttpServlet
{
public void service(HttpServletRequest req,HttpServletResponse resp)
throws ServletException,IOException
{ PrintWriter pw=resp.getWriter();
pw.println("<html><body bgcolor=\"pink\");
String id=req.getParamenter("id");
String pwd=req.getParameter("pwd");
try
{
Class.forName(“com.mysql.jdbc.Driver”);
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/orcl","root","");
Statement stmt=con.createStatement();
String sqlstmt="select id,password from login";
ResultSet rs=stmt.executeQuery(sqlstmt);
int flag=0;
while(rs.next())
{
if(id.equal(rs.getString(1))&&pwd.equals(rs.getString(2)))
{
flag=1;
}
}
if(flag==0)
{
pw.println("SORRY INVALID ID TRY AGAIN ID<br><br>");
pw.println("<a href=\"/tr/login.html\">press LOGIN to RETRY</a>");
}
else
{
pw.println("VALID LOGIN ID<br><br>");
pw.println("<h3><ul>");
pw.println("<li><ahref=\"profile.html\"><fontcolor=\"black\">USER
PROFILE</font> </a></li><br><br>");
pw.println("<li><ahref=\"catalog.html\"><fontcolor=\"black\">BOOKS
CATALOG</font></a></li><br><br>");
pw.println("<li><ahref=\"order.html\"><fontcolor=\"black\">ORDER
CONFIRMATION</font> </a></li><br><br>");
}
pw.println("</body></html>");
}
catch(Exception e)
{ resp.sendError(500,e.toString());
}
}
Reg.html
import java.sql.*;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class login extends HttpServlet
{
public void service(HttpServletRequest req,HttpServletResponse resp)
throws ServletException,IOException
{
PrintWriter pw=resp.getWriter();
pw.println("<html><body bgcolor=\"pink\");
String name=req.getParamenter("name");
String addr=req.getParameter("addr");
String phno=req.getParameter("phno");
String id=req.getParamenter("id");
String pwd=req.getParameter("pwd");
int no=Integer.parseInt(phno);
try
{
Class.forName(“com.mysql.jdbc.Driver”);
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/orcl","root","");
Statement stmt=con.createStatement();
String sqlstmt="select id,password from login";
ResultSet rs=stmt.executeQuery(sqlstmt);
int flag=0;
while(rs.next())
{
if(id.equal(rs.getString(1))&&pwd.equals(rs.getString(2)))
{
flag=1;
}}
if(flag==1)
{
pw.println("SORRY INVALID ID ALREADY EXITS TRY AGAIN WITH NEW
ID<br><br>");
pw.println("<a href=\"/tr/reg.html\">press REGISTER to RETRY</a>");
}
else
{ Statement stmt1=con.createStatement();
stmt1.executeUpdate("insertintologin
values("+names","+addr+","+no+","+id+","+pwd+")");
pw.println("YOUR DETAILS ARE ENTERED<br><br>");
pw.println("<a href=\"/tr/login.html\">press LOGIN to login</a>");
}
pw.println("</body></html>");
}
catch(Exception e)
{ resp.sendError(500,e.toString());
} }}

Catlog.java
import java.sql.*;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class login extends HttpServlet
{
public void service(HttpServletRequest req,HttpServletResponse resp)
throws ServletException,IOException
{
PrintWriter pw=resp.getWriter();
pw.println("<html><body bgcolor=\"pink\");
String title=req.getParameter("title");
try
{
Class.forName(“com.mysql.jdbc.Driver”);
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/orcl","root","");
Statement stmt=con.createStatement();
String sqlstmt="select id,password from login";
ResultSet rs=stmt.executeQuery(sqlstmt);
int flag=0;
while(rs.next())
{
pw.println(",div align=\"center\">");
pw.println("TITLE :"+rs.getString(1)+"<br>");
pw.println("AUTHOR :"+rs.getString(2)+"<br>");
pw.println("VERSION :"+rs.getString(3)+"<br>");
pw.println("PUBLISHER :"+rs.getString(4)+"<br>");
pw.println("COST :"+rs.getString(5)+"<br>");
pw.println("</div");
flag=1;
}
if(flag==0)
{
pw.println("SORRY INVALID TITLE TRY AGAIN <br><br>");
pw.println("<a href=\"/tr/catalog.html\">press HERE to RETRY</a>");
}
pw.println("</body></html>");
}
catch(Exception e)
{
resp.sendError(500,e.toString());
}
}
}

Profile.java
import java.sql.*;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class login extends HttpServlet
{
public void service(HttpServletRequest req,HttpServletResponse resp)
throws ServletException,IOException
{
PrintWriter pw=resp.getWriter();
pw.println("<html><body bgcolor=\"pink\");
String id=req.getParamenter("id");
try
{
Class.forName(“com.mysql.jdbc.Driver”);
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/orcl","root","");
Statement stmt=con.createStatement();
String sqlstmt="select * from login where id="+id+"";
ResultSet rs=stmt.executeQuery(sqlstmt);
int flag=0;
pw.println("<br><br><br>");
while(rs.next())
{
pw.println("<div align=\"center\">");
pw.println("NAME :"+rs.getString(1)+"<br>");
pw.println("ADDRESS :"+rs.getString(2)+"<br>");
pw.println("PHONE NO :"+rs.getString(3)+"<br>");
pw.println("</div>");
flag=1;
}
if(flag==0)
{
pw.println("SORRY INVALID ID TRY AGAIN ID<br><br>");
pw.println("<a href=\"/tr/profile.html\">press HERE to RETRY</a>");
}
pw.println("</body></html>");
}
catch(Exception e)
{
resp.sendError(500,e.toString());
}
}
}

Order.java

import java.sql.*;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class login extends HttpServlet
{
public void service(HttpServletRequest req,HttpServletResponse resp)
throws ServletException,IOException
{
PrintWriter pw=resp.getWriter();
pw.println("<html><body bgcolor=\"pink\");
String id=req.getParamenter("id");
String pwd=req.getParameter("pwd");
String title=req.getParameter("title");
String count1=req.getParameter("no");
String date=req.getParameter("date");
String cno=req.getParameter("cno");
int count=Integer.parseInt(count1);
try
{
Class.forName(“com.mysql.jdbc.Driver”);
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/orcl","root","");
Statement stmt=con.createStatement();
String sqlstmt="select id,password from login";
ResultSet rs=stmt.executeQuery(sqlstmt);
int flag=0,amount,x;
while(rs.next())
{
if(id.equals(rs.getString(1))&&pwd.equals(rs.getString(2)))
{
flag=1;
}
}
if(flag==0)
{
pw.println("SORRY INVALID ID TRY AGAIN ID<br><br>");
pw.println("<a href=\\"/tr/order.html\\">press HERE to RETRY</a>");
}
else
{
Statement stmt2=con.createStatement();
String s="select cost from book where title="+title+"";
ResultSet rs1=stmt2.executeQuery(s);
int flag1=0;
while(rs1.next())
{
flag1=1;
x=Integer.parseInt(rs1.getString(1));
amount=count*x;
pw.println("AMOUNT :"+amount+"<br><br><br><br>");
Statement stmt1=con.createStatement();
stmt1.executeUpdate("insertintodetails
values('"+id+",'"+title+"'+amount+'","'+cno+'")"');
pw.println("YOUR ORDER has taken<br>");
}
if(flag1==0)
{
pw.println("SORRY INVALID ID TRY AGAIN ID<br><br>");
pw.println("<a href=\\"/tr/order.html\\">press HERE to RETRY</a>");
}
}
pw.println("</body></html>");
con.close();
}
catch(Exception e)
{
resp.sendError(500,e.toString());
}
}
9. Redo the previous task using JSP by converting the static web pages of assignments 2
into dynamic web pages. Create a database with user information and books information
and books information. The books catalogue should be dynamically loaded from the
database. Follow the MVC architecture while doing the website.
PROCEDURE:
1) Create your own directory under tomcat/webapps (e.g. tr1)
2) Copy the html files in tr1
3) Copy the jsp files also into tr1
4) Start tomcat give the following command
Catalina.bat run
At install‐dir/bin
5) at I.E give url as http://localhost:8081/tr1/main.html

Main.html:

<html>
<body bgcolor=”pink”>
<br><br><br><br><br><br>
<h1 align=”center”>>U>ONLINE BOOK STORAGE</u></h1><br><br><br>
<h2 align=”center”><PRE>
<b> Welcome to online book storage.
Press LOGIN if you are having id
Otherwise press REGISTRATION
</b></PRE></h2>
<br><br><pre>
<div align=”center”><a href=”/tr/login.html”>LOGIN</a>
href=”/tr/login.html”>REGISTRATION</a></div></pre>
</body></html>

Login.html:

<html>
<body bgcolor=”pink”><br><br><br>
<form name="myform" method="post" action=/tr1/login.jsp">
<div align="center"><pre>
LOGIN ID : <input type="passwors" name="pwd"></pre><br><br>
PASSWORD : <input type="password" name="pwd"></pre><br><br>
</div>
<br><br>
<div align="center">
<inputtype="submit"value="ok"
onClick="validate()">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="reset"
value="clear">
</form>
</body>
</html>

Reg.html:
<html>
<body bgcolor="pink"><br><br>
<form name="myform" method="post" action="/tr1/reg.jsp">
<div align="center"><pre>
NAME :<input type="text" name="name"><br>
ADDRESS :<input type="text" name="addr"><br>
CONTACT NUMBER : <input type="text" name="phno"><br>
LOGIN ID : <input type="text" name="id"><br>
PASSWORD : <input type="password" name="pwd"></pre><br><br>
</div>
<br><br>
<div align="center">
<inputtype="submit"value="ok"
onClick="validate()">()">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="reset"
value="clear">
</form>
</body>
</html>

Profile.html:

<html>
<body bgcolor="pink"><br><br>
<form name="myform" method="post" action="/tr1/profile.jsp">
<div align="center"><pre>
LOGIN ID : <input type="text" name="id"><br>
</pre><br><br>
</div>
<br><br>
<div align="center">
<inputtype="submit"value="ok"
onClick="validate()">()">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="reset"
value="clear">
</form>
</body>
</html>

Catalog.html:

<html>
<body bgcolor="pink"><br><br><br>
<form method="post" action="/tr1/catalog.jsp">
<div align="center"><pre>
BOOK TITLE : <input type="text" name="title"><br>
</pre><br><br>
</div>
<br><br>
<div align="center">
<inputtype="submit"value="ok"
name=”button1”>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<inputtype="reset"value="clear"
name=”button2”>
</form>
</body>
</html>

Order.html:

<html>
<body bgcolor="pink"><br><br><br>
<form method="post" action="/tr1/order.jsp">
<div align="center"><pre>
LOGIN ID :<input type="text" name="id"><br>
PASSWORD : <input type="password" name="pwd"><br>
TITLE :<input type="text" name="title"><br>
NO. OF BOOKS : <input type="text" name="no"><br>
DATE : <input type="text" name="date"><br>
CREDIT CARD NUMBER : <input type="password" name="cno"><br></pre><br><br>
</div>
<br><br>
<div align="center">
<input type="submit" value="ok" name=”button1”>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input
type="reset"
value="clear" name=”button2”>
</form>
</body>
</html>

Login.jsp:
%@page import=”java.sql.*”%
%@page import=”java.io.*”%
<%
out.println(“<html><body bgcolor=\”pink\”>”);
String id=request.getParameter(“id”);
String pwd=request.getParameter(“pwd”);
Class.forName(“com.mysql.jdbc.Driver”);
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/orcl","root","");
Statement stmt=con.createStatement();
String sqlstmt=”select id,password from login where id=”+id+” and password=”+pwd+””;
ResultSet rs=stmt.executeQuery(sqlstmt);
int flag=0;
while(rs.next())
{
flag=1;
}
if(flag==0)
{
out.println(“SORRY INVALID ID TRY AGAIN ID<br><br>”);
out.println(“ <a href=\”/tr1/login.html\”>press LOGIN to RETRY</a>”);
}
else
{
out.println(“VALID LOGIN ID<br><br>”);
out.println(“<h3><ul>”);
out.println(“<li><ahref=\”profile.html\”><fontcolor=\”black\”>USER
PROFILE</font></a></li><br><br>”);
out.println(“<li><ahref=\”catalog.html\”><fontcolor=\”black\”>BOOKS
CATALOG</font></a></li><br><br>”);
out.println(“<li><ahref=\”order.html\”><fontcolor=\”black\”>ORDER
CONFIRMATION</font></a></li><br><br>”);
out.println(“</ul>”);
}
out.println(“<body></html>”);
%>

Reg.jsp:
%@page import=”java.sql.*”%
%@page import=”java.io.*”%
<%
out.println(“<html><body bgcolor=\”pink\”>”);
String name=request.getParameter(“name”);
String addr=request.getParameter(“addr”);
String phno=request.getParameter(“phno”);
String id=request.getParameter(“id”);
String pwd=request.getParameter(“pwd”);
int no=Integer.parseInt(phno);
Class.forName(“com.mysql.jdbc.Driver”);
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/orcl","root","");
Statement stmt=con.createStatement();
String sqlstmt=”select id from login”;
ResultSet rs=stmt.executeQuery(sqlstmt);
int flag=0;
while(rs.next())
{
if(id.equals(rs.getString(1)))
{
flag=1;
}
}
if(flag==1)
{
out.println(“SORRY LOGIN ID ALREADY EXISTS TRY AGAIN WITH NEW ID
<br><br>”);
out.println(“<a href=\”/tr1/reg.html\”>press REGISTER to RETRY</a>”);
}
else
{
Statement stmt1=con.createStatement ();
stmt1.executeUpdate (“insert into login values
(“+name+”,”+addr+”,”+no+”,”+id+”,”+pwd+”)”);
out.println (“YOU DETAILS ARE ENTERED <br><br>”);
out.println (“<a href =\”/tr1/login.html\”>press LOGIN to login</a>”);
}
out.println (“</body></html>”);
%>

Profile.jsp:
<%@page import=”java.sql.*”%>
<%@page import=”java.io.*”%>
<%
out.println (“<html><body bgcolor=\”pink\”>”);
String id=request.getParameter(“id”);
Class.forName(“com.mysql.jdbc.Driver”);
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/orcl","root","");
Statement stmt=con.createStatement ();
String sqlstmt=”select * from login where id=”+id+””;
ResultSet rs=stmt.executeQuery (sqlstmt);
int flag=0;
while(rs.next())
{
out.println (“<div align=\”center\”>”);
out.println (“NAME :”+rs.getString(1)+”<br>”);
out.println (“ADDRESS :”+rs.getString(2)+”<br>”);
out.println (“PHONE NO :”+rs.getString(3)+”<br>”);
out.println (“</div>”);
flag=1;
}
if(flag==0)
{
out.println(“SORRY INVALID ID TRY AGAIN ID <br><br>”);
out.println(“<a href=\”/tr1/profile.html\”>press HERE to RETRY </a>”);
}
out.println (“</body></html>”);
%>

Catalog.jsp:

<%@page import=”java.sql.*”%>
<%@page import=”java.io.*”%>
<%
out.println (“<html><body bgcolor=\”pink\”>”);
String title=request.getParameter (“title”);
Driver d=new oracle.jdbc.driver.OracleDriver ();
Class.forName(“com.mysql.jdbc.Driver”);
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/orcl","root","");
Statement stmt=con.createStatement ();
String sqlstmt=”select * from book where title=”+title+””;
ResultSet rs=stmt.executeQuery (sqlstmt);
int flag=0;
while(rs.next())
{
out.println (“<div align=\”center\”>”);
out.println (“TITLE :”+rs.getString(1)+”<br>”);
out.println (“AUTHOR :”+rs.getString(2)+”<br>”);
out.println (“VERSION:”+rs.getString(3)+”<br>”);
out.println (“PUBLISHER :” +rs.getString(4)+”<br>”);
out.println (“COST :” +rs.getString(5)+”<br>”);
out.println (“</div>”);
flag=1;
}
if(flag==0)
{
out.println(“SORRY INVALID ID TRY AGAIN ID <br><br>”);
out.println(“<a href=\”/tr1/catalog.html\”>press HERE to RETRY </a>”);
}
out.println (“</body></html>”);
%>

Order.jsp:

<%@page import=”java.sql.*”%>
<%@page import=”java.io.*”%>
<%
out.println (“<html><body bgcolor=\”pink\”>”);
String id=request.getParameter (“id”);
String pwd=request.getParameter (“pwd”);
String title=request.getParameter (“title”);
String count1=request.getParameter (“no”);
String date=request.getParameter (“date”);
String cno=request.getParameter (“cno”);
int count=Integer.parseInt(count1);
Class.forName(“com.mysql.jdbc.Driver”);
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/orcl","root","");
Statement stmt=con.createStatement ();
String sqlstmt=”select id, password from login”;
ResultSet rs=stmt.executeQuery (sqlstmt);
int flag=0,amount,x;
while(rs.next())
{
if(id.equals(rs.getString(1))&& pwd.equals(rs.getString(2)))
{
flag=1;
}
}
if(flag==0)
{
out.println(“SORRY INVALID ID TRY AGAIN ID <br><br>”);
out.println(“<a href=\”/tr1/order.html\”>press HERE to RETRY </a>”);
}
else
{
Statement stmt2=con.createStatement();
String s=”select cost from book where title=”+title+””;
ResultSet rs1=stmt2.executeQuery(s);
int flag1=0;
while(rs1.next())
{
flag1=1;
x=Integer.parseInt(rs1.getString(1));
amount=count*x;
out.println(“AMOUNT :”+amount+”<br><br><br><br>”);
Statement stmt1=con.createStatement ();
stmt1.executeUpdate (“insert into details (“+id+”,”+title+”,”+amount+”,”+date+”,”+cno+”)”);
out.println (“YOU ORDER HAS TAKEN<br>”);
}
if(flag1==0)
{
out.println(“SORRY INVALID BOOK TRY AGAIN <br><br>”);
out.println(“<a href=\”/tr1/order.html\”>press HERE to RETRY </a>”);
}
}
out.println (“</body>
</html>”);
%>

You might also like