Sei sulla pagina 1di 124

B V RAJU INSTITUTE OF TECHNOLOGY

(UGC Autonomous, NBA and NAAC Accredited)


Vishnupur, Narsapur, Medak, T.S- 502313

Lab Record
of

WEB TECHNOLOGIES LAB

Name: ________________________________
Roll NO: _______________________________
Year: _______________ Sem: _____________
Branch:_____________ Section____________
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

CERTIFICATE

Certified that this is a bonafide record of lab work done by

Mr./Ms. _____________________ bearing Roll No ______________ of Year ____

Semester____ B.Tech ____ in the ______________________________________

during the academic year 20 - 20

Number of Programs done:

Date:

Internal Examiner External Examiner


B.V.RAJU INSTITUTE OF TECHNOLOGY
Vishnupur, Narsapur, Medak, TS-502313.
www.bvrit.ac.in

STUDENT PROFILE

NAME

ROLL NO

YEAR

SEMESTER

B.TECH

BATCH

LAB NAME

TOTAL NO. OF PROGRAMS

TOTAL NO.OFPROGRAMS DONE

TOTAL CONDUCTED LAB CLASSES

ATTENDED NO. OF LAB CLASSES

ACADEMIC YEAR

Signature of Staff – І Signature of HOD


INDEX

Signature/
S.No. Name of the Program Date PageNo.
Remarks
I. Installation of XAMPP
1
Write a HTML page that has one input, which
can take multi line text and a submit button.
1 Once the user clicks the submit it should
show the number of characters, words and
lines in an alert box.
3
Write a HTML page that contains selection box
with a list of five countries. When a user
2
selects a country its capital should be printed
next to the line.
5
Create a XML document that contains 10
users information. Write a Java program
3
which takes user id as input and returns the
user details
7
Write an XML Schema for creating the user
4
details.
15
Write an XSLT program to convert the XML
5
document into HTML page.
17
Implement the following using PHP, Servlets
and JSP.
a. A user validation application using
user name and password matching with
database information.
b. Modify the above program using Xml
6
file instead of database.
c. A simple calculator web application
that takes two values and an arithmetic
operator from an HTML page and return s the
result.
d. A web application takes user name as
19
input and on submit it shows <Hello>
<username>. The start time at top right corner
of the page. A log out at the bottom of the page
and clicking on Logout it should show <Thank
You><User name>.
e. A user validation application using user
name and password matching with database
information.
f. A user validation application using user
name and password matching with database
information.
Write a program for storing cookies on client
and it should read the same when the user
7
visiting the page next time using PHP,
Servlets.
47
Write a program for session tracking using
8
PHP and JSP
51
Create an employee table in database with
employee information. Write a program to
connect with database and get results from
database for following operations.
9
a. Retrieving the results in a tabular form
b. Updating of employee information
c. Adding new employee information
d. Deleting an employee information
57
Write a program for reading and writing
10
parameters using servlets
94
11 Vivavoce and Lab Assignment
107
12 Additional Content
112
Web Technologies Lab Manual Roll No:

I. OBJECTIVE:

To Install XAMPP Stack Server.

RESOURCES:

XAMPP Stack Software, 1GB RAM, Hard Disk 80 GB.

PROCEDURE:

1. Run the XAMPP setup software.

2. In the next Screen, Select the path if required and then click on the Next Button.

B. V. R. I. T Dept of CSE Page No:1


Web Technologies Lab Manual Roll No:

3. In the next screen select Apache and MySQL. You may optionally select FileZilla (FTP Client)
if needed. Click Install.

4. On successful completion of installation, the following window will appear.

5. Click on Finish button

B. V. R. I. T Dept of CSE Page No:2


Web Technologies Lab Manual Roll No:

1. Write a HTML page that has one input, which can take multi line text and a submit button.
Once the user clicks the submit it should show the number of characters, words and lines in
an alert box.

<html>
<head>
<title>NO. OF CHARACTERS COUNT</title>
<script type="text/JavaScript">
function count1()
{
var str=document.getElementById('atext').value;
var result='';
result+='The number of characters are= '+str.length+'\n';
var arr=str.split(/\b\S+\b/g).length-1;
result+='The number of words are= '+arr+'\n';
var a=str.split('\n').length;
result+='The number of lines are= '+a;
alert(result);
}//count1
</script>
</head>

<body>
<form>
<textarea rows='30' cols='50' id='atext'>
</textarea>
<br>
<center><input type="submit" value="submit" onclick="count1()"></center>
</form>
</body>
</html>

STEP-1: OPEN THE WEB BROWSER & TYPE THE C:/xampp/htdocs/p/p1.html FOR RUNNING
THE p1.html file

B. V. R. I. T Dept of CSE Page No:3


Web Technologies Lab Manual Roll No:

B. V. R. I. T Dept of CSE Page No:4


Web Technologies Lab Manual Roll No:

2. Write a HTML page that contains selection box with a list of five countries. When a user
selects a country its capital should be printed next to the line.

<html>
<title>COUNTRY SELECTION</title>
<head>
<script type="text/javascript">
function OnDropDownChange(dropDown)
{
var selectedValue = dropDown.options[dropDown.selectedIndex].value;
document.getElementById("txtSelectedCapital").innerHTML = selectedValue;
}
</script>
</head>
<body>
<form action = "">
<select name = "Countries" onChange="OnDropDownChange(this);">
<option value="">--Select a country--</option>
<option value="New Delhi">India</option> <option
value="Wellington">New Zealand</option> <option
value="Paris">France</option> <option
value="Athens">Greece</option>
<option value="Madrid">Spain</option>
</select>
<h1 style="color:blue;font-family:verdana;font-size:300%;" id="txtSelectedCapital"
type="text"></h1>
</form>
</body>
</html>

STEP-1: OPEN THE WEB BROWSER & TYPE THE C:/xampp/htdocs/p/p2.html FOR RUNNING
THE p2.html file

B. V. R. I. T Dept of CSE Page No:5


Web Technologies Lab Manual Roll No:

B. V. R. I. T Dept of CSE Page No:6


Web Technologies Lab Manual Roll No:

3. Create a XML document that contains 10 users information. Write a Java program which
takes user id as input and returns the user details.

DOM PARSER

STEP-1: SAVE THE PROGRAM LIKE C:/lp/ReadXMLFile.java

STEP-1:

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import java.io.*;
import java.util.*;
import java.lang.*;

public class ReadXMLFile


{
public static void main(String args[])
{
System.out.println("\nWELCOME TO DOM XML PARSER\n");
Scanner sc=new Scanner(System.in);
System.out.println("Enter the file name of xml document: ");
String xfn=sc.next();
File xmlfile = new File(xfn);
if(xmlfile.exists())
{
System.out.println(xmlfile +" FILE FOUNDED");
}//if
else
{
System.out.println(xmlfile +" FILE NOT FOUNDED");
System.exit(1);
}//else
try
{

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();


DocumentBuilder db=dbf.newDocumentBuilder();
Document dom = db.parse(xmlfile);

Element de=dom.getDocumentElement();
System.out.println("Enter the element tag name of xml document: ");
String xtn=sc.next();

NodeList nList = dom.getElementsByTagName(xtn);


int c=nList.getLength();
System.out.println("\n" +xfn +" FILE IS WELL-FORMED");
System.out.println("count= " +c);
System.out.println("Root element :" + de.getNodeName());
System.out.println("-------------------------------------------------");
System.out.println("Enter the user id: ");
String uid=sc.next();
int l=0;
for (int i = 0; i < nList.getLength(); i++)
{

B. V. R. I. T Dept of CSE Page No:7


Web Technologies Lab Manual Roll No:

l++;
//Node nNode = nList.item(i);
Element eElement = (Element)nList.item(i);
if(uid.equals(eElement.getElementsByTagName("*").item(0).getTextContent()))
{
//System.out.println("USER ID : " + eElement.getAttribute("id"));
System.out.println("\nCurrent Element :" + eElement.getNodeName());
System.out.println("USER ID : " + eElement.getElementsByTagName("id").item(0).getTextContent());
System.out.println("FIRST NAME : " +
eElement.getElementsByTagName("fn").item(0).getTextContent());
System.out.println("DOB : " + eElement.getElementsByTagName("dob").item(0).getTextContent());
System.out.println("SALARY : " + eElement.getElementsByTagName("sal").item(0).getTextContent());
System.out.println("ADDRESS : " +
eElement.getElementsByTagName("addr").item(0).getTextContent());
}//if
}//loop
//System.out.println("length= " +l);
if(c==l)
{
System.out.println("\nUSER ID MATCHED SUCCESSFULLY");
}//if
else
{
System.out.println("\nUSER ID MISMATCHED");
}//else
}//try

catch (Exception e)
{
System.out.println("FILE IS NOT WELL-FORMED");
e.printStackTrace();
}//catch

}//main
}//class

STEP-2: SAVE THE PROGRAM LIKE C:/lp/info.xml

STEP-2:

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


<company>
<user>
<id>101</id>
<fn>om</fn>
<dob>10-01-1982</dob>
<sal>10500.56</sal>
<addr>BHEL</addr>
</user>

<user>
<id>102</id>
<fn>sai</fn>
<dob>20-02-1982</dob>
<sal>20500.56</sal>
<addr>BDL</addr>
</user>

<user>
<id>103</id>
<fn>ram</fn>
<dob>30-03-1982</dob>
<sal>30500.56</sal>
<addr>BEL</addr>

B. V. R. I. T Dept of CSE Page No:8


Web Technologies Lab Manual Roll No:

</user>
<user>
<id>104</id>
<fn>om</fn>
<dob>10-01-1982</dob>
<sal>10500.56</sal>
<addr>BHEL</addr>
</user>

<user>
<id>105</id>
<fn>sai</fn>
<dob>20-02-1982</dob>
<sal>20500.56</sal>
<addr>BDL</addr>
</user>

<user>
<id>106</id>
<fn>ram</fn>
<dob>30-03-1982</dob>
<sal>30500.56</sal>
<addr>BEL</addr>
</user>
<user>
<id>107</id>
<fn>om</fn>
<dob>10-01-1982</dob>
<sal>10500.56</sal>
<addr>BHEL</addr>
</user>

<user>
<id>108</id>
<fn>sai</fn>
<dob>20-02-1982</dob>
<sal>20500.56</sal>
<addr>BDL</addr>
</user>

<user>
<id>109</id>
<fn>ram</fn>
<dob>30-03-1982</dob>
<sal>30500.56</sal>
<addr>BEL</addr>
</user>
<user>
<id>110</id>
<fn>om</fn>
<dob>10-01-1982</dob>
<sal>10500.56</sal>
<addr>BHEL</addr>
</user>

</company>

STEP-3: NOW RUN THE JAVA PROGRAM IN COMMAND PROMPT

B. V. R. I. T Dept of CSE Page No:9


Web Technologies Lab Manual Roll No:

B. V. R. I. T Dept of CSE Page No:10


Web Technologies Lab Manual Roll No:

SAX PARSER

STEP-1: SAVE THE PROGRAM LIKE C:/lp/SAXElementAttribute.java

STEP-1:

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.InputStream;
import java.io.*;
import java.util.*;
import java.lang.*;

class Person{
String id;
String name;
String age;
}//Person

public class SAXElementAttribute


{
String ui,xfn;
public static String ele;
public static int c=0;
public static void main(String[] args)
{
System.out.println("\nWELCOME TO SAX XML PARSER\n");
SAXElementAttribute demo = new SAXElementAttribute();
demo.run();

}//main

private void run()


{
//
// Get an InputStream to the elements.xml file and parse
// its contents using the SAXHandler.
//
Scanner sc=new Scanner(System.in);

System.out.println("Enter the file name of xml document: ");


String xfn=sc.next();
File xmlfile = new File(xfn);
if(xmlfile.exists())
{
System.out.println(xmlfile +" FILE FOUNDED");
}//if
else
{
System.out.println(xmlfile +" FILE NOT FOUNDED");
System.exit(1);
}//else

try
{

//
// Create SAXParserFactory instance and a SAXParser
//

B. V. R. I. T Dept of CSE Page No:11


Web Technologies Lab Manual Roll No:

SAXParserFactory factory = SAXParserFactory.newInstance();


SAXParser parser = factory.newSAXParser();
System.out.print("Enter the element tag name of xml document:");
ele = sc.next();
System.out.println("Enter the user id: ");
String uid=sc.next();
this.ui=uid;
SAXHandler handler = new SAXHandler();
parser.parse(xfn, handler);

System.out.println("\n" +xfn +" FILE IS WELL-FORMED");

System.out.println("\nTotal Count= " +c);


if(c>0)
{
System.out.println("\nUSER ID MATCHED SUCCESSFULLY");
}//if
else
{
System.out.println("\nUSER ID MISMATCHED");
}//else

}//try

catch (Exception e)
{
System.out.println(xfn +" FILE IS NOT WELL-FORMED");
e.printStackTrace();
}//catch
}//run

class SAXHandler extends DefaultHandler


{
Person p = null;
String content = null;

public void startElement(String uri, String localName,String qName, Attributes attributes) throws
SAXException
{

if (qName.equals(ele))
{
c++;
}//if

switch(qName)
{
case "persons":
p = new Person();
p.id = attributes.getValue("id");
break;
}//switch
}//startElement

public void endElement(String uri,String localName, String qName) throws SAXException


{
switch(qName)
{
case "persons":
if(ui.equals(p.id))
{
System.out.println("ID:"+p.id);
System.out.println("Name:"+p.name);

B. V. R. I. T Dept of CSE Page No:12


Web Technologies Lab Manual Roll No:

System.out.println("age:"+p.age);
}//if
break;
case "id":
p.id = content;
break;
case "name":
p.name = content;
break;
case "age":
p.age = content;
break;
}//switch
}//endElement

public void characters(char ch[], int start, int length) throws SAXException
{
content = String.copyValueOf(ch, start, length).trim();
}//characters

}//SAXHandler

}//SAXElementAttribute

STEP-2: SAVE THE PROGRAM LIKE C:/lp/p1.xml

STEP-2:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<persons>
<id>101</id>
<name>Foo</name>
<age>25</age>
</persons>
<persons>
<id>102</id>
<name>Bar</name>
<age>22</age>
</persons>
<persons>
<id>103</id>
<name>Chai</name>
<age>23</age>
</persons>
<persons>
<id>104</id>
<name>Dhanu</name>
<age>27</age>
</persons>
<persons>
<id>105</id>
<name>Kart</name>
<age>21</age>
</persons>
</root>

STEP-3: NOW RUN THE JAVA PROGRAM IN COMMAND PROMPT

B. V. R. I. T Dept of CSE Page No:13


Web Technologies Lab Manual Roll No:

B. V. R. I. T Dept of CSE Page No:14


Web Technologies Lab Manual Roll No:

4. Write an XML Schema for creating the user details.

STEP-1: SAVE THE PROGRAM LIKE C:\xampp\htdocs\p\employee.xs

STEP-1:

<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" >

<xs:element name="Employee_Info" type="EmployeeInfoType" />


<xs:complexType name="EmployeeInfoType">
<xs:sequence>
<xs:element ref="Employee" minOccurs="0" maxOccurs="unbounded" />
</xs:sequence>
</xs:complexType>

<xs:element name="Employee" type="EmployeeType" />


<xs:complexType name="EmployeeType">
<xs:sequence >
<xs:element ref="Name" />
<xs:element ref="Department" />
<xs:element ref="Telephone" />
<xs:element ref="Email" />
</xs:sequence>
<xs:attribute name="Employee_Number" type="xs:int" use="required"/>
</xs:complexType>

<xs:element name="Name" type="xs:string" />


<xs:element name="Department" type="xs:string" />
<xs:element name="Telephone" type="xs:string" />
<xs:element name="Email" type="xs:string" />

</xs:schema>

STEP-2: SAVE THE PROGRAM LIKE C:\xampp\htdocs\p\Employee_Info-p4.xml


STEP-2:

<?xml version="1.0"?>
<Employee_Info
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="employee.xs">
<Employee Employee_Number="101">
<Name>SAIRAM</Name>
<Department>CSE Department</Department>
<Telephone>08458-222-000</Telephone>
<Email>sairam@bvrit.ac.in</Email>
</Employee>
<Employee Employee_Number="103">
<Name>RAMSAI</Name>
<Department>IT Department</Department>
<Telephone>08458-222-005</Telephone>
<Email>ramsai@bvrit.ac.in</Email>
</Employee>
</Employee_Info>

STEP-3: OPEN THE WEB BROWSER LIKE INTERNET EXPLORER & TYPE THE
C:/xampp/htdocs/p/Employee_Info-p4.xml FOR RUNNING THE Employee_Info-p4.xml file

B. V. R. I. T Dept of CSE Page No:15


Web Technologies Lab Manual Roll No:

B. V. R. I. T Dept of CSE Page No:16


Web Technologies Lab Manual Roll No:

5. Write an XSLT program to convert the XML document into HTML page.

STEP-1: SAVE THE PROGRAM LIKE C:\xampp\htdocs\p\p5.xsl

STEP-1:

<?xml version="1.0" encoding="ISO-8859-1"?>

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

<xsl:output method="html"/>

<xsl:template match="/">

<html><body>

<xsl:apply-templates/>

</body></html>

</xsl:template>

<xsl:template match="/PAGE/HEADING">

<h1 align="center"> <xsl:apply-templates/> </h1>

</xsl:template>

<xsl:template match="/PAGE/ARTICLE">

<div style="float:left;width:70%;"><xsl:apply-templates/> </div>

</xsl:template>

<xsl:template match="/PAGE/ARTICLE/TITLE">

<h3> <xsl:apply-templates/> </h3>

</xsl:template>

<xsl:template match="/PAGE/ARTICLE/DESCRIPTION">

<p> <xsl:apply-templates/> </p>

</xsl:template>

<xsl:template match="/PAGE/ASIDE/TITLE">

<div style="float:left;width:30%;"><h3> <xsl:apply-templates/> </h3></div>

</xsl:template>

<xsl:template match="ITEM">

<p> <xsl:apply-templates/> </p>

</xsl:template>

<xsl:template match="/PAGE/FOOTER">

<div style="clear:both;"></div>

<h1 align="center"> <xsl:apply-templates/> </h1>

</xsl:template>

B. V. R. I. T Dept of CSE Page No:17


Web Technologies Lab Manual Roll No:

</xsl:stylesheet>

STEP-2: SAVE THE PROGRAM LIKE C:\xampp\htdocs\p\page.xml

STEP-2:

<?xml version="1.0"?>

<?xml-stylesheet type="text/xsl" href="c:\xampp\htdocs\p\p5.xsl"?>

<PAGE>

<HEADING>page heading</HEADING>

<ARTICLE>

<TITLE>article title</TITLE>

<DESCRIPTION>article description</DESCRIPTION>

</ARTICLE>

<ASIDE>

<TITLE>side widget bar</TITLE>

<ITEM>sidebar item</ITEM>

</ASIDE>

<FOOTER>page footer</FOOTER>

</PAGE>

STEP-3: OPEN THE WEB BROWSER LIKE INTERNET EXPLORER & TYPE THE
C:/xampp/htdocs/p/page.xml FOR RUNNING THE page.xml file

B. V. R. I. T Dept of CSE Page No:18


Web Technologies Lab Manual Roll No:

6. Implement the following using PHP, Servlets and JSP.


a. A user validation application using user name and password matching with database
information.

STEP-1: CREATE A FOLDER UNDER C:\xampp\htdocs & MY FOLDER IS LP, HERE I


WILL SAVE THE PROGRAM LIKE C:\xampp\htdocs\LP\p6a.html

<!-- A user validation application using user name and password


matching with database information using PHP & MYSQL DATABASE-->

<html>
<head>
<title>USER VALIDATION using PHP & MYSQL DATABASE WITH using HTML
FORMS</title>
</head>
<body>
<form enctype="multipart/form-data" action="http://localhost:81/lp/database.php"
method="post">
<table>
<tr>
<td>USERNAME</td>
<td><input type="text" name="username" size="35" /></td>
</tr>
<tr>
<td>PASSWORD</td>
<td><input type="password" name="password" size="35" maxlength="10" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="submit" value="SUBMIT"/></td>
</tr>
</table>
</body>
</html>

STEP-2: CREATE A FOLDER UNDER C:\xampp\htdocs & MY FOLDER IS LP, HERE I


WILL SAVE THE PROGRAM LIKE C:\xampp\htdocs\LP\database.php

<html>
<head>
<title>USER VALIDATION USING PHP & DATABASE(MySQL)</title>
</head>
<body>
<?php
$name=$_REQUEST['username'];
$pass=$_REQUEST['password'];
//MAKE A MYSQL CONNECTION
$conn=mysql_connect("localhost","root","yes") or die(mysql_error());
if(!$conn)
{
die('ERROR IN CONNECTION' .mysql_error());
}
else
{
print "CONNECTED<br/>";
}
//CREATING A DATABASE
if(mysql_query("create database USERS_DB",$conn))
{
echo "CREATED THE DATABASE USERS_DB IN MYSQL<br/>";
}
else

B. V. R. I. T Dept of CSE Page No:19


Web Technologies Lab Manual Roll No:

{
print "ERROR CREATING DATABASE: " .mysql_error();
}

//BEFORE CREATING THE TABLE, SELECT THE DATABASE


mysql_query("use USERS_DB",$conn);
mysql_select_db("USERS_DB",$conn) or die(mysql_error());
echo "CONNECTED TO THE DATABASE USERS_DB IN MYSQL <br/>";

//CREATING A TABLE
mysql_query("create table user_table_details(username varchar(20),password varchar(20))")
or die(mysql_error());
print "<br/>";
echo "TABLE user_table_details CREATED<br/>";

//INSERTING A ROW
mysql_query("insert into user_table_details(username,password) values('om','bvrit')") or
die(mysql_error());
mysql_query("insert into user_table_details(username,password) values('sai','sai')") or
die(mysql_error());
mysql_query("insert into user_table_details(username,password) values('ram','ram3')") or
die(mysql_error());
print "<br/>";
echo "ROWS INSERTED<br/>";

//RETERIVING A ROW FROM TABLE


$result=mysql_query("select * from user_table_details") or die(mysql_error());
$c=0;
print "<br/>";
while($row = mysql_fetch_array($result))
{
if($name==$row['username'] && $pass==$row['password'])
{
$c=1;
break;
}
}//while
if($c==1)
{
echo("<br/><b><font color=green> LOGIN SUCCESSFULLY WITH THE GIVEN USERNAME
& PASSWORD </font></b><br/>");
}
else
{
echo("<br/><b><font color=red> INVALID USERNAME & PASSWORD </font></b><br/>");
}

//DROP THE TABLE


mysql_query("drop table user_table_details") or die(mysql_error());
print "<br/>";
echo "TABLE user_table_details DROPPED<br/>";
print "<br/>";
echo "<b>USERS_DB DATABASE</b>";

//DROP THE DATABASE


mysql_query("drop database USERS_DB",$conn);
echo "<br/>DATABASE USERS_DB IN MYSQL DROPPED<br/>";

//CLOSING THE CONNECTION OF THE DATABASE MYSQL


mysql_close($conn);
print "CLOSE CONNECTION<br/>";

B. V. R. I. T Dept of CSE Page No:20


Web Technologies Lab Manual Roll No:

?>
</body>
</html>

STEP-3: RUN THE APACHE & MySQL SERVER UNDER XAMPP CONTROL PANEL

STEP-4: OPEN THE WEB BROWSER & TYPE THE C:/xampp/htdocs/lp/p6a.html FOR
RUNNING THE p6a.html file

B. V. R. I. T Dept of CSE Page No:21


Web Technologies Lab Manual Roll No:

B. V. R. I. T Dept of CSE Page No:22


Web Technologies Lab Manual Roll No:

b. Modify the above program using Xml file instead of database.

STEP-1: CREATE A FOLDER UNDER C:\xampp\htdocs & MY FOLDER IS LP, HERE I


WILL SAVE THE PROGRAM LIKE C:\xampp\htdocs\LP\p6b.html

<!-- A user validation application using user name and password


matching with database information using XML FILE & PHP -->

<html>
<head>
<title>USER VALIDATION using XML FILE WITH using HTML FORMS & PHP</title>
</head>
<body>
<form name="form1" enctype="multipart/form-data"
action="http://localhost:81/lp/ps1.php" method="post">
<table>
<tr>
<td>USERNAME</td>
<td><input type="text" name="username" size="35" /></td>
</tr>
<tr>
<td>PASSWORD</td>
<td><input type="password" name="password" size="35" maxlength="10" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="submit" value="SUBMIT" /></td>
</tr>
</table>
</form>
</body>
</html>

STEP-2: CREATE A FOLDER UNDER C:\xampp\htdocs & MY FOLDER IS LP, HERE I


WILL SAVE THE PROGRAM LIKE C:\xampp\htdocs\LP\ user_xml_details.xml

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

<userdetails>

<user_xml_details>
<username>user1</username>
<password>pass1</password>
</user_xml_details>

<user_xml_details>
<username>user2</username>
<password>pass2</password>
</user_xml_details>

<user_xml_details>
<username>user3</username>
<password>pass3</password>
</user_xml_details>

</userdetails>

STEP-3: CREATE A FOLDER UNDER C:\xampp\htdocs & MY FOLDER IS LP, HERE I


WILL SAVE THE PROGRAM LIKE C:\xampp\htdocs\LP\ps1.php

<html>
<head>
<title>USER VALIDATION using XML FILE WITH using HTML FORMS & PHP</title>

B. V. R. I. T Dept of CSE Page No:23


Web Technologies Lab Manual Roll No:

</head>
<body>
<?php
$name=$_REQUEST['username'];
$pass=$_REQUEST['password'];
$flag=0;
$xml=simplexml_load_file("user_xml_details.xml")or die("Error:cannot create object");
foreach($xml->children() as $u)
{
if(strcmp($name,$u->username)==0 && strcmp($pass,$u->password)==0)
$flag=1;
}
if($flag)
{
echo("<br/><b><font color=green> LOGIN SUCCESSFULLY WITH THE GIVEN USERNAME
& PASSWORD </font></b><br/>");
return true;
}
else
{
echo("<br/><b><font color=red> INVALID USERNAME & PASSWORD </font></b><br/>");
return false;
}
?>
</body>
</html>
STEP-4: RUN THE APACHE SERVER UNDER XAMPP CONTROL PANEL

STEP-5: OPEN THE WEB BROWSER & TYPE THE C:/xampp/htdocs/lp/p6b.html FOR
RUNNING THE p6b.html file

B. V. R. I. T Dept of CSE Page No:24


Web Technologies Lab Manual Roll No:

B. V. R. I. T Dept of CSE Page No:25


Web Technologies Lab Manual Roll No:

c. A simple calculator web application that takes two values and an arithmetic operator
from an HTML page and return s the result.

STEP-1: CREATE A FOLDER UNDER C:\xampp\htdocs & MY FOLDER IS P, HERE I


WILL SAVE THE PROGRAM LIKE C:\xampp\htdocs\p\p6c.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Calculator</title>
</head>
<body>
<form method="post" action="http://localhost:81/p/cal1.php">
NUMBER 1:
<input type="text" name="num1" id="num1">
<br>
NUMBER 2:
<input type="text" name="num2" id="num2">
<br>
<select name="operator" id="operator">
<option value="+">Add [+]</option>
<option value="-">Subtract[-]</option>
<option value="*">Multiple[*]</option>
<option value="/">Divide[/]</option>
<option value="%">Modulus[%]</option>
<!--<option value="**">Exponenatation[**]</option>-->
</select>
<br>
<input type="submit" name="submit" value="submit" id="submit">
</form>
</body>
</html>

STEP-2: I WILL SAVE THE PROGRAM LIKE C:\xampp\htdocs\p\cal1.php

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Answer</title>
</head>
<body>
<?php
$n1 = $_POST['num1'];
$n2 = $_POST['num2'];
$opr = $_POST['operator'];
if(is_numeric($n1) && is_numeric($n2))
{
if($opr != NULL)
{
switch($opr)
{
case "+" : $r=$n1+$n2;break;
case "-" : $r=$n1-$n2;break;
case "*" : $r=$n1*$n2;break;
case "/" : $r=$n1/$n2;break;
case "%" : $r=$n1%$n2;break;
//case "**" : $r=$n1**$n2; break;
default : echo("You need to select any operator"); break;
}//switch
echo("CALCULATION RESULT: " .$r);
}//if
}//if

B. V. R. I. T Dept of CSE Page No:26


Web Technologies Lab Manual Roll No:

?>
</body>
</html>

STEP-3: RUN THE APACHE SERVER UNDER XAMPP CONTROL PANEL

STEP-4: OPEN THE WEB BROWSER & TYPE THE C:/xampp/htdocs/p/p6c.html FOR
RUNNING THE p6c.html file

B. V. R. I. T Dept of CSE Page No:27


Web Technologies Lab Manual Roll No:

d. A web application takes user name as input and on submit it shows <Hello>
<username>. The start time at top right corner of the page. A log out at the bottom of
the page and clicking on Logout it should show <Thank You><User name>.

STEP-1: CREATE A FOLDER UNDER C:\xampp\htdocs & MY FOLDER IS LP, HERE I


WILL SAVE THE PROGRAM LIKE C:\xampp\htdocs\LP\login.html

<html>
<head>
<title>LOGIN PAGE</title>
</head>
<body>
<form name="form1" enctype="multipart/form-data"
action="http://localhost:81/lp/home.php" method="post">
<br/><br/><br/>
<center>
<table>
<tr>
<td><b>USERNAME</b></td>
<td><input type="text" name="username" size="35" /></td>
</tr>
<tr>
<th rowspan="3"></th>
<th><b><input type="submit" name="submit" value="SUBMIT" style="background-
color:green"/></b></th>
</tr>
</table>
</form>
</center>
</body>
</html>

STEP-2: CREATE A FOLDER UNDER C:\xampp\htdocs & MY FOLDER IS LP, HERE I


WILL SAVE THE PROGRAM LIKE C:\xampp\htdocs\LP\home.php

<html>
<head>
<title>HOME PAGE</title>
</head>
<body>
<?php
$name=$_REQUEST['username'];
echo "<P ALIGN=RIGHT>";
$timezone = new DateTimeZone("Asia/Kolkata" );
$date = new DateTime();
$date->setTimezone($timezone );
echo $date->format( 'h:i:s' );

B. V. R. I. T Dept of CSE Page No:28


Web Technologies Lab Manual Roll No:

echo "</P>";
echo "<br/><center><b><font color=green>HELLO ".$name."</font></b></center><br/>";
echo "<form name=\"form1\" action=\"http://localhost:81/lp/exit.php\"
method=\"post\">";
echo "<input type=\"submit\" value=\"LOGOUT\" style=\"float:right;background-
color:red\">";
echo "<input type=\"hidden\" name=\"user\" value=$name";
echo "</form>";
?>
</body>
</html>

STEP-3: CREATE A FOLDER UNDER C:\xampp\htdocs & MY FOLDER IS LP, HERE I


WILL SAVE THE PROGRAM LIKE C:\xampp\htdocs\LP\exit.php

<html>
<head>
<title>EXIT PAGE</title>
</head>
<body>
<?php
if(isset($_POST["user"]))
echo "<br/><center><b><font color=red>THANKYOU " .$_POST["user"]
."</font></b></center><br/>";
?>
</body>
</html>

STEP-4: RUN THE APACHE SERVER UNDER XAMPP CONTROL PANEL

STEP-5: OPEN THE WEB BROWSER & TYPE THE C:/xampp/htdocs/lp/login.html FOR
RUNNING THE login.html file

B. V. R. I. T Dept of CSE Page No:29


Web Technologies Lab Manual Roll No:

B. V. R. I. T Dept of CSE Page No:30


Web Technologies Lab Manual Roll No:

e. A user validation application using user name and password matching with database
information.

STEP-1: CREATE A FOLDER UNDER C Drive and folder name is ST, HERE I WILL
SAVE THE PROGRAM LIKE C:\st\p6e.html
<!-- A user validation application using user name and password
matching with database information using JSP & MYSQL DATABASE-->

<html>
<head>

<title>USER VALIDATION using SERVLET & MYSQL DATABASE WITH using HTML
FORMS</title>
</head>
<body>
<form enctype="multipart/form-data"
action="http://localhost:8080/examples/servlets/sdb" method="get">
<table>
<tr>
<td>USERNAME</td>
<td><input type="text" name="usern" id="usern" size="35" /></td>
</tr>
<tr>
<td>PASSWORD</td>
<td><input type="password" name="passn" id="passn" size="35" maxlength="10" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="submitn" value="SUBMIT"/></td>
</tr>
</table>
</body>
</html>

STEP-2: CREATE A FOLDER UNDER C Drive and folder name is ST, HERE I WILL
SAVE THE PROGRAM LIKE C:\st\sdb.java

/* A user validation application using user name and password


matching with database information using SERVLETS & MYSQL DATABASE*/

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.sql.Connection;
import java.sql.*;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.ResultSet;
import javax.servlet.http.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class sdb extends HttpServlet


{
public void doGet(HttpServletRequest request,HttpServletResponse response)throws
ServletException, IOException
{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();

B. V. R. I. T Dept of CSE Page No:31


Web Technologies Lab Manual Roll No:

Connection con=null;
ResultSet rs=null;
Statement st=null;

String user=request.getParameter("usern");
String pwd=request.getParameter("passn");
pw.println(user +" " +pwd);

try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();

con=DriverManager.getConnection("jdbc:mysql://localhost:3306/","root","yes");
pw.println("Connected to MySQL database !!!");
st=con.createStatement();

st.executeUpdate("create database user_db105;");


pw.println("Database user_db105 created sucessfully.");

st.executeUpdate("use user_db105;");
pw.println("USING Database user_db105, here we are creating tables");

st.executeUpdate("create table user_table105(username varchar(100),password


varchar(100));");
pw.println("Table user_table105 created sucessfully.");

st.executeUpdate("insert into user_table105(username,password) values('user1', 'pass1');");


st.executeUpdate("insert into user_table105(username,password) values('user2', 'pass2');");
st.executeUpdate("insert into user_table105(username,password) values('user3', 'pass3');");

pw.println("Data is successfully inserted in user_table105!");

rs=st.executeQuery("select * from user_table105;");

while(rs.next())
{
pw.println(rs.getString("username") +" " +rs.getString("password"));
}

rs=st.executeQuery("select * from user_table105;");

int c=0;
while(rs.next())
{
if(rs.getString("username").equals(user) && rs.getString("password").equals(pwd))
{
c=c+1;
break;
}
}
if(c==1)
{
pw.println("<br/><b><font color=green> LOGIN SUCCESSFULLY WITH THE GIVEN
USERNAME & PASSWORD </font></b><br/>");
}
else
{
pw.println("<br/><b><font color=red> INVALID USERNAME & PASSWORD
</font></b><br/>");
}

B. V. R. I. T Dept of CSE Page No:32


Web Technologies Lab Manual Roll No:

st.executeUpdate("drop table user_table105;");


pw.println("TABLE user_table105 DROPPED!");

st.executeUpdate("drop database user_db105;");


pw.println("DATABASE USERS_DB105 IN MYSQL DROPPED");

pw.println("CLOSE THE CONNECTION OF MySQL database !!!");

rs.close();
st.close();
con.close();
}
catch(Exception e)
{
pw.println("ERROR");
e.printStackTrace();
}
pw.close();
}//main
}//sdb

STEP-3: run the sdb.java program in cmd prompt

STEP-4: copy the sdb.class into C:\xampp\tomcat\webapps\examples\WEB-INF\classes


folder like C:\xampp\tomcat\webapps\examples\WEB-INF\classes\sdb.class

STEP-5: go & write the servlet tag & servlet-mapping tag code into
C:\xampp\tomcat\webapps\examples\WEB-INF\web.xml file & save it

<!-- Define servlets that are included in the example application -->

<servlet>

<servlet-name>LOGIN VALIDATION Example</servlet-name>

<servlet-class>sdb</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>LOGIN VALIDATION Example</servlet-name>

<url-pattern>/servlets/sdb</url-pattern>

</servlet-mapping>

STEP-6: Go to the xampp control panel and start the Mysql and Tomcat server

B. V. R. I. T Dept of CSE Page No:33


Web Technologies Lab Manual Roll No:

STEP-7: OPEN THE WEB BROWSER & TYPE THE C:/st/p6e.html FOR RUNNING THE
p6e.html file

B. V. R. I. T Dept of CSE Page No:34


Web Technologies Lab Manual Roll No:

f. A user validation application using user name and password matching with database
information.

STEP-1: CREATE A FOLDER UNDER C:\xampp\tomcat\webapps\examples\jsp\LP,


HERE I WILL SAVE THE PROGRAM LIKE
C:\xampp\tomcat\webapps\examples\jsp\LP \p6f.html

<!-- A user validation application using user name and password


matching with database information using SERVLETS & MYSQL DATABASE-->

<html>
<head>

<title>USER VALIDATION using JSP & MYSQL DATABASE WITH using HTML
FORMS</title>
</head>
<body>
<form enctype="multipart/form-data"
action="http://localhost:8080/examples/jsp/LP/jdatabase.jsp" method="get">
<table>
<tr>
<td>USERNAME</td>
<td><input type="text" name="usern" id="usern" size="35" /></td>
</tr>
<tr>
<td>PASSWORD</td>
<td><input type="password" name="passn" id="passn" size="35" maxlength="10" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="submitn" value="SUBMIT"/></td>
</tr>
</table>
</body>
</html>

STEP-2: CREATE A FOLDER UNDER C:\xampp\tomcat\webapps\examples\jsp\LP,


HERE I WILL SAVE THE PROGRAM LIKE
C:\xampp\tomcat\webapps\examples\jsp\LP \jdatabase.jsp

<% -- USER VALIDATION using JSP & MYSQL DATABASE --% >

<%@ page language="java" import="java.sql.*" contentType="text/html; charset=ISO-8859-


1"
pageEncoding="ISO-8859-1" %>
<%@ page import="java.io.*" %>
<%@ page import="java.sql.*" %>
<%@ page import="java.lang.*" %>
<%@ page import="java.util.*" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.DriverManager" %>

B. V. R. I. T Dept of CSE Page No:35


Web Technologies Lab Manual Roll No:

<%@ page import="java.sql.ResultSet" %>


<%@ page import="java.sql.ResultSetMetaData" %>
<%@ page import="java.sql.Statement" %>
<%@ page import="com.mysql.jdbc.*" %>

<html>

<body>
<%
Connection con=null;
ResultSet rs=null;
Statement st=null;
try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();

con=DriverManager.getConnection("jdbc:mysql://localhost:3306/","root","yes");
out.write("Connected to MySQL database !!!");
st=con.createStatement();

st.executeUpdate("create database user_db105;");


out.write("Database user_db105 created sucessfully.");

st.executeUpdate("use user_db105;");
out.write("USING Database user_db105, here we are creating tables");

st.executeUpdate("create table user_table105(username varchar(100),password


varchar(100));");
out.write("Table user_table105 created sucessfully.");

st.executeUpdate("insert into user_table105(username,password) values('user1', 'pass1');");


st.executeUpdate("insert into user_table105(username,password) values('user2', 'pass2');");
st.executeUpdate("insert into user_table105(username,password) values('user3', 'pass3');");

out.write("Data is successfully inserted in user_table105!");

rs=st.executeQuery("select * from user_table105;");

while(rs.next())
{
out.write(rs.getString("username") +" " +rs.getString("password"));
}

rs=st.executeQuery("select * from user_table105;");

String user=request.getParameter("usern");
String pwd=request.getParameter("passn");

int c=0;
while(rs.next())
{
if(rs.getString("username").equals(user) && rs.getString("password").equals(pwd))
{
c=c+1;
break;
}
}
if(c==1)
{
out.write("<br/><b><font color=green> LOGIN SUCCESSFULLY WITH THE GIVEN
USERNAME & PASSWORD </font></b><br/>");
out.write(user +" " +pwd);

B. V. R. I. T Dept of CSE Page No:36


Web Technologies Lab Manual Roll No:

}
else
{
out.write("<br/><b><font color=red> INVALID USERNAME & PASSWORD
</font></b><br/>");
}

st.executeUpdate("drop table user_table105;");


out.write("TABLE user_table105 DROPPED!");

st.executeUpdate("drop database user_db105;");


out.write("DATABASE USERS_DB105 IN MYSQL DROPPED");

out.write("CLOSE THE CONNECTION OF MySQL database !!!");

rs.close();
st.close();
con.close();
}
catch(Exception e)
{
out.println("ERROR");
}
%>
</body>
</html>
STEP-3: Go to the website and download
https://dev.mysql.com/downloads/connector/j/mysql-connector-java-5.1.45.zip

Step-4: Extract the content mysql-connector-java-5.1.45-bin.jar from mysql-


connector-java-5.1.45.zip
Copy the jar file and save it C:\xampp\tomcat\webapps\examples\web-inf\lib

Set classpath under user variables of environment variables

Next set path under system variables as follows

B. V. R. I. T Dept of CSE Page No:37


Web Technologies Lab Manual Roll No:

Step-5: RUN THE Tomcat & MySQL SERVER UNDER XAMPP CONTROL PANEL

STEP-4: OPEN THE WEB BROWSER & TYPE THE


C:\xampp\tomcat\webapps\examples\jsp\LP \p6f.html

B. V. R. I. T Dept of CSE Page No:38


Web Technologies Lab Manual Roll No:

B. V. R. I. T Dept of CSE Page No:39


Web Technologies Lab Manual Roll No:

7. Write a program for cookies using PHP, Servlets and JSP.

a. Write a program for storing cookies on client and it should read the same when the
user visiting the page next time using PHP

STEP-1:

OPEN THE TEXT EDITOR LIKE NOTEPAD AND TYPE THE FOLLOWING CODE. SAVE YOUR
CODE BY THE EXTENSION .PHP LIKE C:\XAMPP\HTDOCS\LP\ CookieSetDemo.PHP
IT IS EXPECTED THAT THE PHP CODE MUST BE STORED IN HTDOCS FOLDER OF APACHE
LIKE C:\xampp\htdocs\lp HERE I HAVE CREATED THE LP FOLDER UNDER HTDOCS
FOLDER

<html>
<head>
<title>COOKIE SET DEMO USING PHP </title>
</head>
<body>
<?php
$Cookie_period=time()+60*60*24*30;
setcookie("Myname","Monika",$Cookie_period);
?>
</body>
</html>

PROGRAM EXPLANATION

PHP CAN BE USED TO CREATE AND RETERIVE THE COOKIES.


NOTE THAT YOU HAVE GOT THE BLANK SCREEN IT INDICATES THAT THE COOKIE IS SET.
IN ABOVE PHP DOCUMENT WE HAVE SET THE PHP SCRIPT FOR ONE MONTH. JUST
OBSERVE THE THIRD PARAMETER OF THE SETCOOKIE FUNCTION.
NOW YOU CAN RETRIEVE THE COOKIE AND READ THE VALUE TO ENSURE WHETHER OR
THE COOKIE IS SET.

SAVE YOUR CODE BY THE EXTENSION .PHP LIKE C:\XAMPP\HTDOCS\LP\


CookieReadDemo.PHP

<html>
<head>
<title>COOKIE READ DEMO (READING COOKIES) USING PHP </title>
</head>
<body>
<?php
if(isset($_COOKIE["Myname"]))
{
echo "<h3> Welcome " .$_COOKIE["Myname"] ."!!!</h3>";
}//if
else
{
echo "<h3> Welcome guest! </h3>";
}//else
?>
</body>
</html>

PROGRAM EXPLANATION

THE ISSET FUNCTION IS USED FOR CHECKING WHETHER OR NOT THE COOKIE IS SET.
THEN USING THE $_COOKIE THE VALUE OF THE COOKIE CAN BE RETERIVED.

STEP-2:

RUN THE XAMPP SERVER I.E, XAMPP CONTROL PANEL & START APACHE

B. V. R. I. T Dept of CSE Page No:40


Web Technologies Lab Manual Roll No:

STEP-3:

HENCE WHEN I WANT TO GET THE OUTPUT OF THE PHP CODE I ALWAYS GIVE THE URL
THE HTTP://LOCALHOST REFERS TO THE PATH C:\XAMPP\HTDOCS\LP LIKE

http://localhost:81/lp/CookieSetDemo.php

http://localhost:81/lp/CookieReadDemo.php

B. V. R. I. T Dept of CSE Page No:41


Web Technologies Lab Manual Roll No:

b. Write a program for storing cookies on client and it should read the same when the
user visiting the page next time using servlets

STEP-1: CookieDemo.html

<!DOCTYPE HTML>

<html>

<head>

<title>DEMO FOR COOKIE</title>

</head>

<body>

<form name="form1" action="http://localhost:8080/examples/servlets/PostCookieSetServletDemo"


target="_BLANK" method="POST">

<h3> Enter the value for my cookie: </h3>

<input type=text name="txt_data" size=30 value="">

<input type=submit value="SUBMIT">

</form>

</body>

</html>

STEP-2:

SAVE LIKE GetCookieReadServletDemo.java AND COMPLE THE JAVA PROGRAM

//GetCookieReadServletDemo

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

B. V. R. I. T Dept of CSE Page No:42


Web Technologies Lab Manual Roll No:

public class GetCookieReadServletDemo extends HttpServlet

public void doGet(HttpServletRequest request,HttpServletResponse response)throws


ServletException, IOException

response.setContentType("text/html");

PrintWriter pw = response.getWriter();

Cookie[] mc=request.getCookies();

pw.println("<b>");

int n=mc.length;

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

String name=mc[i].getName();

String value=mc[i].getValue();

pw.println("name=" +name);

pw.println(" and value=" +value);

pw.close();

SAVE LIKE PostCookieSetServletDemo.java AND COMPLE THE JAVA PROGRAM

//PostCookieSetServletDemo

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class PostCookieSetServletDemo extends HttpServlet

public void doPost(HttpServletRequest request,HttpServletResponse response)throws


ServletException, IOException

String t1 = request.getParameter("txt_data");

response.setContentType("text/html");

PrintWriter pw = response.getWriter();

//create cookie

Cookie c=new Cookie("My_Cookie",t1);

B. V. R. I. T Dept of CSE Page No:43


Web Technologies Lab Manual Roll No:

//adding cookie to HTTP response

response.addCookie(c);

//write friendly output to browser

pw.println("<h2>MyCookie has been set to: ");

pw.println(t1);

pw.println("<br><br><br>");

pw.println("THIS PAGE SHOWS THAT THE COOKIE HAS BEEN ADDED");

pw.close();

STEP-3:

COPY THIS CALSS FILE INTO C:\xampp\tomcat\webapps\examples\WEB-


INF\classes\GetCookieReadServletDemo.class

COPY THIS CALSS FILE INTO C:\xampp\tomcat\webapps\examples\WEB-INF\classes\


PostCookieSetServletDemo.class

STEP-4:

Edit the web.xml file present at C:\xampp\tomcat\webapps\examples\WEB-INF\web.xml &


SAVE IT

<servlet>

<servlet-name>PostCookieSetServletDemo Example</servlet-name>

<servlet-class>PostCookieSetServletDemo</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>PostCookieSetServletDemo Example</servlet-name>

B. V. R. I. T Dept of CSE Page No:44


Web Technologies Lab Manual Roll No:

<url-pattern>/servlets/PostCookieSetServletDemo</url-pattern>

</servlet-mapping>

<servlet>

<servlet-name>GetCookieReadServletDemo Example</servlet-name>

<servlet-class>GetCookieReadServletDemo</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>GetCookieReadServletDemo Example</servlet-name>

<url-pattern>/servlets/GetCookieReadServletDemo</url-pattern>

</servlet-mapping>

STEP-5: now start the tomcat server i.e, C:\xampp\catalina_start.bat (or)


C:\xampp\tomcat\ catalina_start.bat batch file

STEP-6: Open the web browser and run the html file like CookieDemo.html in the URL LIKE

B. V. R. I. T Dept of CSE Page No:45


Web Technologies Lab Manual Roll No:

And for reading the cookies type the following URL


http://localhost:8080/examples/servlets/GetCookieReadServletDemo and you will get the
following output

B. V. R. I. T Dept of CSE Page No:46


Web Technologies Lab Manual Roll No:

c. Write a program for storing cookies on client and it should read the same when the
user visiting the page next time using JSP

STEP-1: save the file in C:\xampp\tomcat\webapps\examples\jsp\LP-JSP\input.html

<!-- CREATE AN HTML FILE TO READ THE VALUES FROM THE USER -->
<html>
<head>
<title>READING THE VALUES</title>
</head>
<body>
<form method="post" action="CreateCookie.jsp">
USERNAME <input type="text" name="name">
CITY <input type="text" name="city">
<input type="submit" name="submit" value="SUBMIT">
</form>
</body>
</html>

STEP-2: save the file in C:\xampp\tomcat\webapps\examples\jsp\LP-JSP\


CreateCookie.jsp

<% -- CREATING THE COOKIE --% >


<%@ page language="java" import="java.util.*"%>
<%
String name=request.getParameter("name");
String city=request.getParameter("city");

Cookie namecookie=new Cookie("name",name);


Cookie citycookie=new Cookie("city",city);

response.addCookie(namecookie);
response.addCookie(citycookie);

namecookie.setMaxAge(60*60*24);
citycookie.setMaxAge(60*60*24);
%>
<h3>
<a href="ReadCookie.jsp">click here to continue...</a>
</h3>

STEP-3: save the file in C:\xampp\tomcat\webapps\examples\jsp\LP-JSP\


ReadCookie.jsp

<% -- READING THE CREATED COOKIE --% >


<h3> Reading the Cookie </h3>
<%
Cookie[] c=request.getCookies();
for(int i=0;i<c.length;i++)
{
out.println("Cookie_Name=" +c[i].getName() +"<br>");
out.println("Cookie_Value=" +c[i].getValue() +"<br>");
}
%>
<a href="DeleteCookie.jsp">click here to Delete the Cookies...</a>

STEP-4: save the file in C:\xampp\tomcat\webapps\examples\jsp\LP-JSP\


DeleteCookie.jsp

<% -- DELETING THE COOKIE --% >


<%
Cookie namecookie=new Cookie("name","");
namecookie.setMaxAge(0);
namecookie.setValue("");

B. V. R. I. T Dept of CSE Page No:47


Web Technologies Lab Manual Roll No:

response.addCookie(namecookie);

Cookie citycookie=new Cookie("city","");


citycookie.setMaxAge(0);
citycookie.setValue("");
response.addCookie(citycookie);
%>
<h3> Cookie is Deleted </h3>
<a href="ReadCookie.jsp">click here to check the deletion...</a>

STEP-5: now start the tomcat server i.e, C:\xampp\catalina_start.bat (or)


C:\xampp\tomcat\ catalina_start.bat batch file

STEP-6: Open the web browser and type the URL LIKE http://
localhost:8080/examples/jsp/LP-JSP/input.html

CLICK SUBMIT BUTTON

B. V. R. I. T Dept of CSE Page No:48


Web Technologies Lab Manual Roll No:

B. V. R. I. T Dept of CSE Page No:49


Web Technologies Lab Manual Roll No:

B. V. R. I. T Dept of CSE Page No:50


Web Technologies Lab Manual Roll No:

8. Write a program for session tracking using PHP, Servlets and JSP.

a. Write a program for session tracking using PHP

STEP-1:

OPEN THE TEXT EDITOR LIKE NOTEPAD AND TYPE THE FOLLOWING CODE. SAVE YOUR
CODE BY THE EXTENSION .PHP LIKE C:\XAMPP\HTDOCS\LP\SessionDemo.PHP
IT IS EXPECTED THAT THE PHP CODE MUST BE STORED IN HTDOCS FOLDER OF APACHE
LIKE C:\xampp\htdocs\lp HERE I HAVE CREATED THE LP FOLDER UNDER HTDOCS
FOLDER

<html>
<head>
<title>SESSION DEMO USING PHP</title>
</head>
<body>
<?php
session_start();
if(isset($_SESSION['pgvisit']))
{
$_SESSION['pgvisit']=$_SESSION['pgvisit']+1;
echo "<h3> You are visiting this page for <i>" .$_SESSION['pgvisit'] ."</i> times </h3>";
}//if
else
{
$_SESSION['pgvisit']=1;
echo "<h3> You are visiting this page for the first time</h3>";
}//else
?>
</body>
</html>

STEP-2:

RUN THE XAMPP SERVER I.E, XAMPP CONTROL PANEL & START APACHE

STEP-3:

HENCE WHEN I WANT TO GET THE OUTPUT OF THE PHP CODE I ALWAYS GIVE THE URL
THE HTTP://LOCALHOST REFERS TO THE PATH C:\XAMPP\HTDOCS\LP LIKE

http://localhost:81/lp/SessionDemo.php

B. V. R. I. T Dept of CSE Page No:51


Web Technologies Lab Manual Roll No:

PROGRAM EXPLANATION

IN ABOVE PROGRAM, WE HAVE STRATED THE SESSION BY USING SESSION_START()


FUNCTION.
THE ISSET() FUNCTION CHECKS IF THE PGVISIT VARIABLE HAS ALREADY BEEN SET.
IF PGVISIT HAS BEEN SET, WE CAN INCREMENT OUR COUNTER.
IF PGVISIT IS NOT SET THEN WE CREATE A SET IT TO 1.
THE VALUE OF PGVISIT IS DISPLAYED ON THE SCREEN.

b. Write a program for session tracking using servlets

STEP-1:

//SESSION TRACKING USING SERVLET

import java.io.*;

import java.util.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class SessionServletDemo extends HttpServlet

public void doGet(HttpServletRequest request,HttpServletResponse response) throws


ServletException, IOException

response.setContentType("text/html");

PrintWriter pw = response.getWriter();

HttpSession session=request.getSession();

String heading;

Integer c=(Integer)session.getAttribute("c");

if(c==null)

c=new Integer(0);

heading="WELCOME YOU ARE ACCESSING THE PAGE FOR THE FIRST TIME";

B. V. R. I. T Dept of CSE Page No:52


Web Technologies Lab Manual Roll No:

else

heading="WELCOME ONCE AGAIN!";

c=new Integer(c.intValue()+1);

session.setAttribute("c",c);

pw.println("<html>");

pw.println("<head>");

pw.println("<title>");

pw.println("SESSION DEMO USING PHP");

pw.println("</title>");

pw.println("</head>");

pw.println("<body>");

pw.println("<h1>" +heading);

pw.println("<h2>THE NUMBER OF PREVIOUS ACCESS=" +c);

pw.println("</body>");

pw.println("</html>");

pw.close();

}//doGet

}//SessionServletDemo

STEP-2:

SAVE LIKE SessionServletDemo .java AND COMPLE THE JAVA PROGRAM

B. V. R. I. T Dept of CSE Page No:53


Web Technologies Lab Manual Roll No:

STEP-3:

COPY THIS CALSS FILE INTO C:\xampp\tomcat\webapps\examples\WEB-INF\classes\


SessionServletDemo .class

STEP-4:

Edit the web.xml file present at C:\xampp\tomcat\webapps\examples\WEB-INF\web.xml &


SAVE IT

<servlet>

<servlet-name>SessionServletDemo Example</servlet-name>

<servlet-class>SessionServletDemo</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>SessionServletDemo Example</servlet-name>

<url-pattern>/servlets/SessionServletDemo</url-pattern>

</servlet-mapping>

STEP-5: now start the tomcat server i.e, C:\xampp\catalina_start.bat (or)


C:\xampp\tomcat\ catalina_start.bat batch file

STEP-6: Open the web browser and give the URL LIKE
HTTP://localhost:8080/examples/servlets/SessionServletDemo and you will get the
following output

B. V. R. I. T Dept of CSE Page No:54


Web Technologies Lab Manual Roll No:

IF YOU REFRESH YOUR BROWSER EITHER BY PROCESSING F5 OR CLICKING THE REFRESH


BUTTON THEN YOU WILL GET FOLLOWING KIND OF OUTPUT.

c. Write a program for session tracking using JSP

STEP-1:

FIRST OF ALL OPEN SOME TEXT EDITOR LIKE NOTEPAD AND TYPE THE FOLLOWING CODE
LIKE

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<html>

<head>

<!-- THIS IS BASIC HTML PAGE (HTML COMMENT STATEMENT STYLE) -->

<title>SESSION JSP DEMO</title>

</head>

<% -- DISPLAYING THE MESSAGE ON THE BROWSER (JSP COMMENT STATEMENT STYLE)--% >

<body>

<c:set var="first_cnt" scope="session" value="${first_cnt+1}" />

<c:set var="second_cnt" scope="application" value="${second_cnt+1}" />

<h3>WELCOME</h3>

THE SESSION COUNT OF THIS PAGE IS ${first_cnt}

THE APPLICATION COUNT OF THIS PAGE IS ${second_cnt}

</body>

</html>

B. V. R. I. T Dept of CSE Page No:55


Web Technologies Lab Manual Roll No:

STEP-2:

CREATE A USER-DEFINED FOLDER IN C:\xampp\tomcat\webapps\examples\jsp


HERE MY FOLDER NAME IS LP-JSP SO I AM SAVING THE FILE LIKE SessionJSPDemo.jsp &
NOW THE PATH IS
C:\xampp\tomcat\webapps\examples\jsp\LP-JSP\ SessionJSPDemo.jsp

STEP-3:

now start the tomcat server i.e, C:\xampp\catalina_start.bat (or) C:\xampp\tomcat\


catalina_start.bat batch file

STEP-4:

OPEN the web browser and give the URL LIKE


http://localhost:8080/examples/jsp/LP-JSP/SessionJSPDemo.jsp

B. V. R. I. T Dept of CSE Page No:56


Web Technologies Lab Manual Roll No:

9. Create an employee table in database with employee information. Write a program to


connect with database and get results from database for following operations.
a. Retrieving the results in a tabular form
b. Updating of employee information
c. Adding new employee information
d. Deleting an employee information

STEP-1: SAVING IN C:\xampp\htdocs\p\p10.php

<html>

<head>

<title>EMPLOYEE DB DEMO</title>

</head>

<body>

<?php

//MAKE A MYSQL CONNECTION

$conn=mysql_connect("localhost","root","yes") or die(mysql_error());

if(!$conn)

die('ERROR IN CONNECTION' .mysql_error());

else

print "CONNECTED<br/>";

//CREATING A DATABASE

if(mysql_query("create database EMPLOYEE1",$conn))

B. V. R. I. T Dept of CSE Page No:57


Web Technologies Lab Manual Roll No:

echo "CREATED THE DATABASE EMPLOYEE1 IN MYSQL<br/>";

else

print "ERROR CREATING DATABASE: " .mysql_error();

//BEFORE CREATING THE TABLE, SELECT THE DATABASE

mysql_query("use EMPLOYEE1",$conn);

mysql_select_db("EMPLOYEE1",$conn) or die(mysql_error());

echo "CONNECTED THE DATABASE EMPLOYEE1 IN MYSQL <br/>";

//CREATING A TABLE

mysql_query("create table EMP1(eno int not null auto_increment,ename varchar(20),esal real,primary


key(eno))") or die(mysql_error());

print "<br/>";

echo "TABLE EMP1 CREATED<br/>";

//INSERTING A ROW

mysql_query("insert into EMP1(ename,esal) values('om','70500.57')") or die(mysql_error());

mysql_query("insert into EMP1(ename,esal) values('sai','92390.67')") or die(mysql_error());

mysql_query("insert into EMP1(ename,esal) values('ram','60234.77')") or die(mysql_error());

mysql_query("insert into EMP1(ename,esal) values('omsairam','80786.87')") or die(mysql_error());

mysql_query("insert into EMP1(ename,esal) values('saibaba','50123.97')") or die(mysql_error());

print "<br/>";

echo "ROWS INSERTED<br/>";

//RETERIVING A ROW FROM TABLE

$result=mysql_query("select * from EMP1") or die(mysql_error());

print "<br/>";

echo "<b>USER DATABASE</b>";

echo "<table border=1>";

echo "<tr><th>eno</th><th>ename</th><th>esal</th></tr>";

while($row=mysql_fetch_array($result))

B. V. R. I. T Dept of CSE Page No:58


Web Technologies Lab Manual Roll No:

//PRINT OUT THE CONTENTS OF EACH ROW INTO A TABLE

echo "<tr><td>";

echo $row['eno'];

echo "</td><td>";

echo $row['ename'];

echo "</td><td>";

echo $row['esal'];

echo "</td></tr>";

}//while

echo "</table>";

//UPDATING A ROW FROM TABLE

$result=mysql_query("update EMP1 set eno='30' where eno='3' ") or die(mysql_error());

print "<br/>";

echo "ROW UPDATED<br/>";

$result=mysql_query("select * from EMP1") or die(mysql_error());

print "<br/>";

echo "<b>USER DATABASE</b>";

echo "<table border=1>";

echo "<tr><th>eno</th><th>ename</th><th>esal</th></tr>";

while($row=mysql_fetch_array($result))

//PRINT OUT THE CONTENTS OF EACH ROW INTO A TABLE

echo "<tr><td>";

echo $row['eno'];

echo "</td><td>";

echo $row['ename'];

echo "</td><td>";

echo $row['esal'];

echo "</td></tr>";

}//while

echo "</table>";

B. V. R. I. T Dept of CSE Page No:59


Web Technologies Lab Manual Roll No:

//DELETING A ROW FROM TABLE

$result=mysql_query("delete from EMP1 where eno='30' ") or die(mysql_error());

print "<br/>";

echo "ROW DELETED<br/>";

$result=mysql_query("select * from EMP1") or die(mysql_error());

print "<br/>";

echo "<b>USER DATABASE</b>";

echo "<table border=1>";

echo "<tr><th>eno</th><th>ename</th><th>esal</th></tr>";

while($row=mysql_fetch_array($result))

//PRINT OUT THE CONTENTS OF EACH ROW INTO A TABLE

echo "<tr><td>";

echo $row['eno'];

echo "</td><td>";

echo $row['ename'];

echo "</td><td>";

echo $row['esal'];

echo "</td></tr>";

}//while

echo "</table>";

//DROP THE TABLE

mysql_query("drop table EMP1") or die(mysql_error());

print "<br/>";

echo "TABLE EMP1 DROPPED<br/>";

print "<br/>";

echo "<b>USER DATABASE</b>";

//DROP THE DATABASE

$query="drop database EMPLOYEE1";

mysql_query($query,$conn);

echo "<br/>DATABASE EMPLOYEE1 IN MYSQL DROPPED<br/>";

B. V. R. I. T Dept of CSE Page No:60


Web Technologies Lab Manual Roll No:

//CLOSING THE CONNECTION OF THE DATABASE MYSQL

mysql_close($conn);

print "CLOSE CONNECTION<br/>";

?>

</body>

</html>

STEP-2:

STEP-3:

B. V. R. I. T Dept of CSE Page No:61


Web Technologies Lab Manual Roll No:

B. V. R. I. T Dept of CSE Page No:62


Web Technologies Lab Manual Roll No:

(OR)

STEP-1: SAVING IN C:\js\DBDemo.html

<html>

<head>

<title>

DB Connectivity using JDBC</title>

</head>

<frameset rows="100,*">

<frame src="c:\js\Head.html" name="top_frame">

<frameset cols="200,*">

B. V. R. I. T Dept of CSE Page No:63


Web Technologies Lab Manual Roll No:

<frame src="c:\js\Menu.html" name="left_frame">

<frame src="c:\js\Display.html" name="right_frame">

</frameset>

</frameset>

<body></body>

</html>

STEP-2: SAVING IN C:\js\Display.html

<html>

<body>

<center>

<p>This is DB Demo Connectivity between</p>

<p>Servlet and MYSQL</p>

<p>Click links given in left frame</p>

</center>

</body>

</html>

STEP-3: SAVING IN C:\js\Head.html

<html>

<head>

<title>DATABASE CONNECTION</title>

</head>

<body>

<h1><center>Operations on Employee Database</center></h1>

</body>

</html>

STEP-4: SAVING IN C:\js\Menu.html

<html>

<body>

<h2>Main Menu</h2>

<h3>

<a href="http://localhost:8080/examples/servlets/Insert_Q"

target="right_frame">Insert Record</a>

<br/>

<a href="http://localhost:8080/examples/servlets/Delete_Q"

B. V. R. I. T Dept of CSE Page No:64


Web Technologies Lab Manual Roll No:

target="right_frame">Delete Record</a>

<br/>

<a href="http://localhost:8080/examples/servlets/Update_Q"

target="right_frame">Update Record</a>

<br/>

<a href="http://localhost:8080/examples/servlets/ServletDB"

target="right_frame">Display Record</a>

</h3>

</body>

</html>

STEP-5: SAVING IN C:\js\Insert_Q.java

import java.io.*;

import java.util.*;

import javax.sql.*;

import javax.servlet.*;

import javax.servlet.http.*;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

public class Insert_Q extends HttpServlet

public void service(HttpServletRequest request,HttpServletResponse response)throws IOException,


ServletException

response.setContentType("text/html");

PrintWriter out=response.getWriter();

out.println("<html>");

out.println("<head><title>Servlet DB Connectivity</title></head>");

out.println("<body></body></html>");

//Connection to DB

Connection con=null;

B. V. R. I. T Dept of CSE Page No:65


Web Technologies Lab Manual Roll No:

Statement st=null;

ResultSet rs=null;

try

Class.forName("com.mysql.jdbc.Driver");

con=DriverManager.getConnection("jdbc:mysql://localhost:3306/employee","root","yes");

st=con.createStatement();

out.println("\n\n");

String emp_name=request.getParameter("ename");

String emp_add=request.getParameter("eadd");

String emp_phn=request.getParameter("ephn");

if(emp_name!=null&&emp_add!=null&emp_phn!=null)

if(emp_name.length()>0)

st.executeUpdate("insert into
emp(name,address,phone)values('"+emp_name+"','"+emp_add+"','"+emp_phn+"')");

rs=st.executeQuery("select*from emp");

out.println("<html>");

out.println("<body>");

out.println("<form action='Insert_Q' method='post'>");

out.println("<strong>Name:</strong><input name='ename' type='text'>");

out.println("<br/>");

out.println("<strong>Address:</strong><input name='eadd' type='text'>");

out.println("<br/>");

out.println("<strong>Phone:</strong><input name='ephn' type='text'>");

out.println("<br/>");

out.println("<input type='submit'value='Submit'>");

out.println("</from>");

out.println("</body>");

out.println("</html>");

}//try

catch(SQLException e)

{throw new ServletException("Servlet Can't display records",e);}

catch(ClassNotFoundException e)

{throw new ServletException("JDBC Driver Not Found",e);}

B. V. R. I. T Dept of CSE Page No:66


Web Technologies Lab Manual Roll No:

finally

try

if(rs!=null)

rs.close();

rs=null;

if(st!=null)

st.close();

st=null;

if(con!=null)

con.close();

con=null;

}//try

catch(SQLException e){}

}//finally

out.close();

}//service

}//class

STEP-6: SAVING IN C:\js\Delete_Q.java

import java.io.*;

import java.lang.*;

import java.util.*;

import javax.sql.*;

import javax.servlet.*;

import javax.servlet.http.*;

import java.sql.Connection;

import java.sql.DriverManager;

B. V. R. I. T Dept of CSE Page No:67


Web Technologies Lab Manual Roll No:

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

public class Delete_Q extends HttpServlet

public void service(HttpServletRequest request,HttpServletResponse response)throws IOException,


ServletException

response.setContentType("text/html");

PrintWriter out=response.getWriter();

out.println("<html>");

out.println("<head><title>Servlet DB Connectivity</title></head>");

out.println("<body></body></html>");

//Connection to DB

Connection con=null;

Statement st=null;

ResultSet rs=null;

try

Class.forName("com.mysql.jdbc.Driver");

con=DriverManager.getConnection("jdbc:mysql://localhost:3306/employee","root","yes");

st=con.createStatement();

out.println("\n\n");

String emp_id=request.getParameter("eid");

if(emp_id==null)

emp_id="0";

int n=Integer.parseInt(emp_id);

st.executeUpdate("delete from emp where id="+n);

rs=st.executeQuery("select * from emp");

out.println("<html>");

out.println("<body>");

out.println("<form action='Delete_Q' method='post'>");

out.println("<strong>Enter id to delete</strong>");

B. V. R. I. T Dept of CSE Page No:68


Web Technologies Lab Manual Roll No:

out.println("<br/>");

out.println("<input name='eid'type='text'>");

out.println("<br/>");

out.println("<input type='submit'value='Submit'>");

out.println("</from>");

out.println("</body>");

out.println("</html>");

}//try

catch(SQLException e)

{throw new ServletException("Servlet Can't display records",e);}

catch(ClassNotFoundException e)

{throw new ServletException("JDBC Driver Not Found",e);}

finally

try

if(rs!=null)

rs.close();

rs=null;

if(st!=null)

st.close();

st=null;

if(con!=null)

con.close();

con=null;

}//try

catch(SQLException e){}

}//finally

B. V. R. I. T Dept of CSE Page No:69


Web Technologies Lab Manual Roll No:

out.close();

}//service

}//class

STEP-7: SAVING IN C:\js\Update_Q.java

import java.io.*;

import java.lang.*;

import java.util.*;

import javax.sql.*;

import javax.servlet.*;

import javax.servlet.http.*;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

public class Update_Q extends HttpServlet

public void service(HttpServletRequest request,HttpServletResponse response)throws IOException,


ServletException

response.setContentType("text/html");

PrintWriter out=response.getWriter();

out.println("<html>");

out.println("<head><title>Servlet DB Connectivity</title></head>");

out.println("<body></body></html>");

//Connection to DB

Connection con=null;

Statement st=null;

ResultSet rs=null;

try

Class.forName("com.mysql.jdbc.Driver");

con=DriverManager.getConnection("jdbc:mysql://localhost:3306/employee","root","yes");

B. V. R. I. T Dept of CSE Page No:70


Web Technologies Lab Manual Roll No:

st=con.createStatement();

out.println("\n\n");

String emp_id=request.getParameter("eid");

String emp_phn=request.getParameter("ephn");

if(emp_id==null)

emp_id="0";

int n=Integer.parseInt(emp_id);

st.executeUpdate("update emp set phone= '"+emp_phn+"' where id="+n);

rs=st.executeQuery("select*from emp");

out.println("<html>");

out.println("<body>");

out.println("<form action='Update_Q' method='post'>");

out.println("<strong>Enter id to update</strong>");

out.println("<br/>");

out.println("<input name='eid'type='text'>");

out.println("<br/>");

out.println("<strong>Enter new phone to update</strong>");

out.println("<br/>");

out.println("<input name='ephn' type='text'>");

out.println("<br/>");

out.println("<input type='submit'value='Submit'>");

out.println("</from>");

out.println("</body>");

out.println("</html>");

}//try

catch(SQLException e)

{throw new ServletException("Servlet Can't display records",e);}

catch(ClassNotFoundException e)

{throw new ServletException("JDBC Driver Not Found",e);}

finally

try

if(rs!=null)

B. V. R. I. T Dept of CSE Page No:71


Web Technologies Lab Manual Roll No:

rs.close();

rs=null;

if(st!=null)

st.close();

st=null;

if(con!=null)

con.close();

con=null;

}//try

catch(SQLException e){}

}//finally

out.close();

}//service

}//class

STEP-8: SAVING IN C:\js\ServletDB.java

import java.io.*;

import java.lang.*;

import java.util.*;

import javax.sql.*;

import javax.servlet.*;

import javax.servlet.http.*;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

public class ServletDB extends HttpServlet

B. V. R. I. T Dept of CSE Page No:72


Web Technologies Lab Manual Roll No:

public void service(HttpServletRequest request,HttpServletResponse response)throws IOException,


ServletException

response.setContentType("text/html");

PrintWriter out=response.getWriter();

out.println("<html>");

out.println("<head><title>Servlet DB Connectivity</title></head>");

out.println("<body></body></html>");

//Connection to DB

Connection con=null;

Statement st=null;

ResultSet rs=null;

try

Class.forName("com.mysql.jdbc.Driver");

con=DriverManager.getConnection("jdbc:mysql://localhost:3306/employee","root","yes");

st=con.createStatement();

out.println("Connected to DB...");

out.println("\n\n");

rs=st.executeQuery("select*from emp");

out.println("<center>");

out.println("<h2>Emloyee DB</h2>");

out.println("<table border=3>");

out.println("<th>Id</th>");

out.println("<th>Name</th>");

out.println("<th>Address</th>");

out.println("<th>Phone</th>");

while(rs.next())

out.print("<tr>");

out.print("<td>");

out.print(rs.getObject(1).toString());

B. V. R. I. T Dept of CSE Page No:73


Web Technologies Lab Manual Roll No:

out.print("</td>");

out.print("<td>");

out.print(rs.getObject(2).toString());

out.print("</td>");

out.print("<td>");

out.print(rs.getObject(3).toString());

out.print("</td>");

out.print("<td>");

out.print(rs.getObject(4).toString());

out.print("</td>");

out.print("</tr>");

out.print("</table>");

out.print("</center>");

}//try

catch(SQLException e)

{throw new ServletException("Servlet Can't display records",e);}

catch(ClassNotFoundException e)

{throw new ServletException("JDBC Driver Not Found",e);}

finally

try

if(rs!=null)

rs.close();

rs=null;

if(st!=null)

st.close();

st=null;

if(con!=null)

B. V. R. I. T Dept of CSE Page No:74


Web Technologies Lab Manual Roll No:

con.close();

con=null;

}//try

catch(SQLException e){}

}//finally

out.close();

}//service

}//class

STEP-9: CREATE DATABASE & TABLES IN MYSQL, & NOW RUN XAMPP CONTROL PANEL AND START
APACHE AND MYSQL SERVER

B. V. R. I. T Dept of CSE Page No:75


Web Technologies Lab Manual Roll No:

B. V. R. I. T Dept of CSE Page No:76


Web Technologies Lab Manual Roll No:

B. V. R. I. T Dept of CSE Page No:77


Web Technologies Lab Manual Roll No:

B. V. R. I. T Dept of CSE Page No:78


Web Technologies Lab Manual Roll No:

B. V. R. I. T Dept of CSE Page No:79


Web Technologies Lab Manual Roll No:

(OR)

B. V. R. I. T Dept of CSE Page No:80


Web Technologies Lab Manual Roll No:

STEP-10: RUN THE JAVA PROGRAM IN COMMAND PROMPT THAT STORED IN C:\JS

B. V. R. I. T Dept of CSE Page No:81


Web Technologies Lab Manual Roll No:

STEP-11: COPY ALL THE CLASS FILES INTO C:\xampp\tomcat\webapps\examples\WEB-INF\CLASSES

STEP-12: OPEN WEB.XML IN C:\xampp\tomcat\webapps\examples\WEB-INF AND ADD THE SERVLET


AND SERVLET MAPPING TAGS

<!-- Define servlets that are included in the example application -->

<servlet>

<servlet-name>Insert_Q Example</servlet-name>

<servlet-class> Insert_Q </servlet-class>

</servlet>

<servlet-mapping>

<servlet-name> Insert_Q Example</servlet-name>

<url-pattern>/servlets/ Insert_Q

</url-pattern>

</servlet-mapping>

SIMILARLY FOR Delete_Q ,Update_Q AND ServletDB FILES.

STEP-13: START MYSQL AND TOMCAT SERVER UNDER THE XAMPP CONTROL PANNEL

B. V. R. I. T Dept of CSE Page No:82


Web Technologies Lab Manual Roll No:

STEP-14: OPEN THE WEB BROWSER AND TYPE THE URL LIKE C:\JS\DBDemo.html

Inserting the values into database

B. V. R. I. T Dept of CSE Page No:83


Web Technologies Lab Manual Roll No:

Displaying the values of the database after insertion

Inserting another value

B. V. R. I. T Dept of CSE Page No:84


Web Technologies Lab Manual Roll No:

Displaying database after insertion

Updating the record

B. V. R. I. T Dept of CSE Page No:85


Web Technologies Lab Manual Roll No:

Displaying database after updation of record

Deleting the record

B. V. R. I. T Dept of CSE Page No:86


Web Technologies Lab Manual Roll No:

Displaying database after deletion of record

STEP-15: STOP ALL SERVERS UNDER THE XAMPP CONTROL PANNEL

B. V. R. I. T Dept of CSE Page No:87


Web Technologies Lab Manual Roll No:

=======================================================================================

B. V. R. I. T Dept of CSE Page No:88


Web Technologies Lab Manual Roll No:

1. Write a simple program for GenericServlet & its invokes using html & lifecycle servlet
methods by reading servlet parameters

STEP-1: save like book.html in c:\ drive of any user-created folder like st is a folder name

<!DOCTYPE HTML>

<html>

<head>

<title>BOOK ORDER FORM</title>

</head>

<body>

<center>

<h3>ENTER THE BOOK DATA</h3>

<form name="form1" action="http://localhost:8080/examples/servlets/HtmlLifeCycleServletDemo"


target="_BLANK" method="POST">

<table>

<tr>

<td>Sl.No.</td>

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

</tr>

<tr>

<td>Book Name</td>

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

</tr>

<tr>

<td>Publisher Name</td>

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

</tr>

<tr>

<td>Price</td>

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

</tr>

<tr>

<td>Quantity</td>

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

</tr>

B. V. R. I. T Dept of CSE Page No:89


Web Technologies Lab Manual Roll No:

<tr>

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

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

</tr>

</table>

</form>

</center>

</body>

</html>

STEP-2: save like HtmlLifeCycleServletDemo.java in c:\ drive of any user-created folder

import javax.servlet.*;

import javax.servlet.http.*;

import java.io.*;

import java.util.*;

public class HtmlLifeCycleServletDemo extends GenericServlet

public void init(ServletConfig config) throws ServletException

System.out.println("from init\n");

}//init

public void service(ServletRequest request, ServletResponse response) throws ServletException,


IOException

System.out.println("from service\n");

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("WELCOME TO SERVICE METHOD\n");

Enumeration e=request.getParameterNames();

while(e.hasMoreElements())

String n=(String)e.nextElement();

out.println(n + "=");

String v=request.getParameter(n);

out.println(v +"\n");

B. V. R. I. T Dept of CSE Page No:90


Web Technologies Lab Manual Roll No:

out.println();

}//while

out.close();

}//service

public void destroy()

System.out.println("from destroy");

}//destroy

}//HtmlLifeCycleServletDemo

STEP-3: run the HtmlLifeCycleServletDemo.java program in cmd prompt

The ServletRequest class includes methods that allow you to read the names and values of
parameters that are included in a client request. We will develop a servlet that illustrates their
use.
This example contains two files.
A Web page is defined in book.html and a servlet is defined in HtmlLifeCycleServletDemo.java

The source code for HtmlLifeCycleServletDemo.java contains service( ) method is overridden to


process client requests. The getParameterNames( ) method returns an enumeration of the
parameter names. These are processed in a loop. we can see that the parameter name and value
are output to the client. The parameter value is obtained via the getParameter( ) method.

STEP-4: copy the HtmlLifeCycleServletDemo.class into


C:\xampp\tomcat\webapps\examples\WEB-INF\classes folder like
C:\xampp\tomcat\webapps\examples\WEB-INF\classes\HtmlLifeCycleServletDemo.class

STEP-5: go & write the servlet tag & servlet-mapping tag code into
C:\xampp\tomcat\webapps\examples\WEB-INF\web.xml file & save it

<!-- Define servlets that are included in the example application -->

<servlet>

<servlet-name>HtmlLifeCycleServletDemo Example</servlet-name>

<servlet-class>HtmlLifeCycleServletDemo</servlet-class>

</servlet>

<servlet-mapping>

B. V. R. I. T Dept of CSE Page No:91


Web Technologies Lab Manual Roll No:

<servlet-name>HtmlLifeCycleServletDemo Example</servlet-name>

<url-pattern>/servlets/HtmlLifeCycleServletDemo</url-pattern>

</servlet-mapping>

STEP-6: now start the tomcat server i.e, C:\xampp\catalina_start.bat (or) C:\xampp\tomcat\
catalina_start.bat batch file

STEP-7: enter the complete path for the html program in the web browser like
file:///C:/st/book.html and you will get the following output

STEP-8: when the user submit the book details it automatically opens the web browser &
gets the command like

http://localhost:8080/examples/servlets/HtmlLifeCycleServletDemo

There is also a submit button. Notice that the action parameter of the form tag specifies a URL. The
URL identifies the servlet to process the HTTP POST request.

B. V. R. I. T Dept of CSE Page No:92


Web Technologies Lab Manual Roll No:

----------------------------------------------------------------------------------------------------------------------------------

2. Write a simple program for HttpServlet

STEP-1

import javax.servlet.*;

import javax.servlet.http.*;

import java.io.*;

import java.util.*;

public class FirstServlet extends HttpServlet

public void doGet(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<!DOCTYPE HTML>");

out.println("<HTML>");

out.println("<HEAD>");

out.println("<TITLE>MY First Servlet</TITLE>");

out.println("</HEAD>");

out.println("<BODY>");

out.println("<h1>Welcome to the Servlet Testing Center</h1>");

out.println("<br><hr><br>");

B. V. R. I. T Dept of CSE Page No:93


Web Technologies Lab Manual Roll No:

out.println("<h3>Servlet Random Message</h3><br>");

String[] ms={"GOOD MORNING","GOOD NIGHT","HOW ARE YOU?","GOOD EVENING","SEE


YOU"};

Random r=new Random();

out.println(ms[r.nextInt(ms.length)]);

out.println("</BODY>");

out.println("</HTML>");

STEP-2

----------------------------------------------------------------------------------------------------------------------------------

3. Write a simple program for reading servlet parameters

STEP-1: sum.html

<html>

<body>

<center>

<form name="Form1" method="post" action="http://localhost:8080/examples/servlets/Add"


target="_BLANK" >

<table>

<tr>

<td><B>Enter First Number</td>

<td><input type=textbox name="Enter First Number" size="25" value=""></td>

</tr>

B. V. R. I. T Dept of CSE Page No:94


Web Technologies Lab Manual Roll No:

<tr>

<td><B>Enter Second Number</td>

<td><input type=textbox name="Enter Second Number" size="25" value=""></td>

</tr>

</table>

<input type=submit value="Submit">

</body>

</html>

STEP-2: Add.java

//Reading Servlet Parameters

/*The ServletRequest class includes methods that allow you to read the names and values of
parameters

that are included in a client request. We will develop a servlet that illustrates their use.

The example contains two files.

A Web page is defined in sum.html and a servlet is defined in Add.java*/

import java.io.*;

import java.util.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class Add extends HttpServlet

public void doPost(HttpServletRequest request,HttpServletResponse response) throws


ServletException, IOException

// Get print writer.

response.setContentType("text/html");

PrintWriter pw = response.getWriter();

// Get enumeration of parameter names.

Enumeration e = request.getParameterNames();

// Display parameter names and values.

int sum1=0;

while(e.hasMoreElements())

String pname = (String)e.nextElement();

pw.print(pname + " = ");

B. V. R. I. T Dept of CSE Page No:95


Web Technologies Lab Manual Roll No:

String pvalue = request.getParameter(pname);

sum1+=Integer.parseInt(pvalue);

pw.println(pvalue+"\n");

pw.println("Sum of two numbers are= "+sum1);

pw.close();

STEP-3:

The HTML source code for sum.html defines a table that contains two labels and two text fields.
One of the labels is Enter First Number,and the other is Enter Second Number. There is also a
submit button. Notice that the action parameter of the form tag specifies a URL. The URL identifies
the servlet to process the HTTP POST request.

The source code for Add.java contains doPost( ) method is overridden to process client requests.
The getParameterNames( ) method returns an enumeration of the parameter names. These are
processed in a loop.we can see that the parameter name and value are output to the client. The
parameter value is obtained via the getParameter( ) method.

B. V. R. I. T Dept of CSE Page No:96


Web Technologies Lab Manual Roll No:

----------------------------------------------------------------------------------------------------------------------------------

4. Write a simple program for reading initialization parameters for a servlet

//Reading Initialization Parameters for a servlet

STEP-1:

import java.io.*;

import java.util.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class Reverse extends HttpServlet

public void doGet(HttpServletRequest request,HttpServletResponse response) throws


ServletException, IOException

//Get print writer

response.setContentType("text/html");

PrintWriter pw = response.getWriter();

ServletConfig config=getServletConfig();

//Get enumeration of parameter names

Enumeration e = config.getInitParameterNames();

//obtain number as a parameter from web.xml file

// Display parameter names and values.

int sum1=0;

while(e.hasMoreElements())

B. V. R. I. T Dept of CSE Page No:97


Web Technologies Lab Manual Roll No:

String pname = (String)e.nextElement();

pw.println("\n" +pname +" = ");

String pvalue = config.getInitParameter(pname);

sum1=sum1+Integer.parseInt(pvalue);

pw.println(pvalue +"\n");

pw.println("\nSum of three numbers are= "+sum1);

String num=config.getInitParameter("number");

pw.println("\nThe Given Number is: "+num);

int n=Integer.parseInt(num);

int rev=0,t;

while(n>0)

t=n%10;

rev=(rev*10)+t;

n=n/10;

}//while

pw.println("\nReverse of a given number= "+rev);

pw.close();

}//doGet

}//Reverse

STEP-2:

<servlet>

<init-param>

<param-name>x</param-name>

<param-value>12</param-value>

</init-param>

<init-param>

<param-name>y</param-name>

<param-value>3</param-value>

</init-param>

<init-param>

<param-name>number</param-name>

B. V. R. I. T Dept of CSE Page No:98


Web Technologies Lab Manual Roll No:

<param-value>123</param-value>

</init-param>

<servlet-name>Reverse Example</servlet-name>

<servlet-class>Reverse</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>Reverse Example</servlet-name>

<url-pattern>/servlets/Reverse</url-pattern>

</servlet-mapping>

STEP-3:

STEP-4:

----------------------------------------------------------------------------------------------------------------------------------

B. V. R. I. T Dept of CSE Page No:99


Web Technologies Lab Manual Roll No:

5. A. Write a program for Handling Http Request & Responses in servlets using get method

STEP-1:

The HttpServlet class provides specialized methods that handle the various types of HTTP requests.
A servlet developer typically overrides one of these methods. These methods are doDelete( ), doGet(
), doHead( ), doOptions( ), doPost( ), doPut( ), and doTrace( ). The GET and POST requests are
commonly used when handling form input.

STEP-2:

Handling HTTP GET Requests:

The following programs are for servlets that handles HTTP GET request. The servlet is invoke when
a form on a Web page is submitted.

The example contains two files. A Web page is defined in Get.html and a servlet is defined in
GetServlet.java. The HTML source code for Get.htm is shown in the following listing. It defines a
form that contains a select element and a submit button. Notice that the action parameter of the
form tag specifies a URL. The URL identifies a servlet to process the HTTP GET request.

STEP-3: Get.html

<html>

<body>

<center>

<form name="form1" method="get" action="http://localhost:8080/examples/servlets/GetServlet"


target="_BLANK">

<B>Color:</B>

<select name="color" size="1">

<option value="">Pick an option</option>

<option value="Red" style="color:red;">Red</option>

<option value="Green" style="color:green;">Green</option>

<option value="Blue" style="color:blue;">Blue</option>

</select>

<br><br>

<input type=submit value="SUBMIT">

</form>

</body>

</html>

STEP-4: GetServlet.java

The source code for GetServlet.java is shown in the following listing. The doGet( ) method is
overridden to process any HTTP GET requests that are sent to this servlet. It uses the
getParameter( ) method of HttpServletRequest to obtain the selection that was made by the user. A
response is then formulated.

//Handling HTTP GET Requests

B. V. R. I. T Dept of CSE Page No:100


Web Technologies Lab Manual Roll No:

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class GetServlet extends HttpServlet

public void doGet(HttpServletRequest request,HttpServletResponse response)throws


ServletException, IOException

String col = request.getParameter("color");

response.setContentType("text/html");

PrintWriter pw = response.getWriter();

pw.println("<B>The selected color is: ");

pw.println(col);

pw.close();

STEP-5:

Compile the servlet and perform these steps to test this example:
a. Start Tomcat, if it is not already running.
b. Display the Web page in a browser.

B. V. R. I. T Dept of CSE Page No:101


Web Technologies Lab Manual Roll No:

c. Select a color.

d. Submit the Web page.

B. V. R. I. T Dept of CSE Page No:102


Web Technologies Lab Manual Roll No:

After completing these steps, the browser will display the response that is dynamically generated by the
servlet.
One other point: Parameters for an HTTP GET request are included as part of the URL that is sent to the
Web server. Assume that the user selects the green option and submits the form. The URL sent from the
browser to the server is

http://localhost:8080/examples/servlets/GetServlet?color=Red

The characters to the right of the question mark are known as the query string.

----------------------------------------------------------------------------------------------------------------------------------

5. B. Write a program for Handling Http Request & Responses in servlets using post method

STEP-1:

The servlet is invoked when a form on a Web page is submitted. The example contains two files. A
Web page is defined in Post.html and a servlet is defined in PostServlet.java.The HTML source code
for Post.html is shown in the following listing. It isidentical toPost.html except that the method
parameter for the form tag explicitly specifies that the POST method should be used, and the
action parameter for the form tag specifies a different servlet.

Handling HTTP POST Requests:

The following programs are for servlets that handles HTTP POST request. The servlet is invoke
when a form on a Web page is submitted.

STEP-2: Post.html

<html>
<body>
<center>
<form name="form1" method="post" action="http://localhost:8080/examples/servlets/PostServlet"
target="_BLANK">
<B>Color:</B>
<select name="color" size="1">
<option value="">Pick an option</option>
<option value="Red" style="color:red;">Red</option>
<option value="Green" style="color:green;">Green</option>
<option value="Blue" style="color:blue;">Blue</option>
</select>
<br><br>
<input type=submit value="SUBMIT">
</form>
</body>

B. V. R. I. T Dept of CSE Page No:103


Web Technologies Lab Manual Roll No:

</html>

STEP-3: PostServlet.java

//Handling HTTP POST Requests

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class PostServlet extends HttpServlet

public void doPost(HttpServletRequest request,HttpServletResponse response)throws


ServletException, IOException

String col = request.getParameter("color");

response.setContentType("text/html");

PrintWriter pw = response.getWriter();

pw.println("<B>The selected color is: ");

pw.println(col);

pw.close();

STEP-4:

Compile the servlet and perform these steps to test this example:
a. Start Tomcat, if it is not already running.
b. Display the Web page in a browser.

B. V. R. I. T Dept of CSE Page No:104


Web Technologies Lab Manual Roll No:

c. Select a color.

d. Submit the Web page.

B. V. R. I. T Dept of CSE Page No:105


Web Technologies Lab Manual Roll No:

Note: Parameters for an HTTP POST request are not included as part of the URL that
is sent to the Web server. In this example, the URL sent from the browser to the server

http://localhost:8080/examples/servlets/PostServlet

The parameter names and values are sent in the body of the HTTP request.
----------------------------------------------------------------------------------------------------------------------------------

=======================================================================================

B. V. R. I. T Dept of CSE Page No:106


Web Technologies Lab Manual Roll No:

VIVA QUESTIONS

1. What is XAMPP stack?

2. What is setup file?

3. What is client side scripting?

4. What is server side scripting?

5. What is Mysql?

6. Why is the name as Mysql?

7. What is the usage of apache tomcat server?

8. How to run the PHP file?

9. What is an example of client side scripting language?

10. What are JavaScript data types?

11. How do we submit the form in JavaScript?

12. What is JavaScript?


13. How to create the text field?

14. How to retrieve the form data?

15. What is the purpose of writing document.getElementById ('anumber').value?

16. How to create an array in JavaScript?


17. How to create the HTML document?

18. How to create the text area in an HTML document?

19. How to create the submit button in an HTML document?


20. How to create function in an HTML document?
21. What is the purpose of str.split(' ')?

22. What is the purpose of str.split('\n')?

23. How to find the length of the array?

24. How to create the alert message?


25. How do you insert a comment in html?

26. What are some of the common lists that can be used when designing a page?

B. V. R. I. T Dept of CSE Page No:107


Web Technologies Lab Manual Roll No:

27. How do you create links to sections within the same page?

28. Does a hyperlink apply to text only?


29. If the user’s operating system does not support the needed character, how can the symbol be
represented?

30. How do you change the number type in the middle of a list?

31. Is it possible to set specific colors for table borders?

32. How do you create a link that will connect to another web page when clicked?
33. Is Java purely object oriented language?

34. How to create an object in java language?

35. How to display the string in java language?

36. What is the purpose of java.io.* package?


37. How to handle the exceptions in java?

38. How to catch exceptions using java language?

39. How to read the XML file using java language?

40. How many types of parsers we have in XML?


41. What does the initials of PHP stand for?

42. Which programming language does PHP resemble to?

43. What is the actually used PHP version?

44. How do you execute a PHP script from the command line?

45. How can PHP and HTML interact?


46. What is the difference between SQL and Mysql?

47. What is JOIN in MySQL? What are the different types of join?

48. If we use SUM function in MySQL, does it return sum of that row or for that column?

49. What do we use to remove duplicate records while fetching a data in MySQL?

50. Whether root element is required for XML? If so, how many root elements are required?

51. What are the disadvantages of xml?

52. Is there a way to describe XML data?

B. V. R. I. T Dept of CSE Page No:108


Web Technologies Lab Manual Roll No:

53. What is well formed XML document?


54. How to read the data from the controls.

55. Why do we use multipart/form-data in html form?

56. What function do we use to find length of string, and length of array?

57. How to display the form data in php?


58. What are arithmetic operations in PHP?

59. How can we change the value of a constant?

60. Differences between GET, POST and REQUEST methods ?

61. What is Open Source Software?


62. How to read the data using form controls?

63. How to use the switch case in PHP?

64. What is the purpose of ($_POST['num1'])?

65. What is the purpose of ($_POST['num2'])?


66. Explain how to submit form without a submit button.

67. How can we encrypt the password using PHP?

68. What is the difference between $message and $$message?

69. Is PHP a loosely Typed Language? What is the difference between strongly typed and loosely typed
language?
70. How will you create a database using PHP and MySQL?

71. How will you find out the value of current session id?

72. List the different run time errors in PHP.

73. What is a PHP Session?

B. V. R. I. T Dept of CSE Page No:109


Web Technologies Lab Manual Roll No:

LAB ASSIGNMENT

1. Install WAMP Stack Server?

2. Install LAMP Stack Server?

3. Write a JavaScript program for checking a number is even or odd?

4. Write a JavaScript program for a string is palindrome or not?

5. Write a JavaScript program for printing the days of a week?


6. Write an HTML program for creating two frames?

7. Write a HTML program for adding images with HTML.

8. Write a HTML Program to demonstrate Cell Spacing and Cell Padding in a XHTML Table?
9. Write a HTML Program to demonstrate Form Fields.

10. Write a HTML Demonstration of Navigation through various frames

11. To create a php program to demonstrate the different file handling methods.
12. Write a program to reverse a number using Java language?

13. Write a program for linear search using Java language?

14. Write a program to check a number is even or odd using Java language?
15. Write a HTML program to demonstrate HTML Headers
16. Write a HTML program using images as link Anchor.
17. Write a HTML program for adding images with HTML.
1. Write a program to create a CD catalog using XML file.

2. To create an XSL style sheet to display the data in the xml using html table.

3. Write an XML file which will display the Book information.

It includes the following:

1) Title of the book

2) Author Name

3) ISBN number

4) Publisher name

5) Edition

6) Price

Write an Internal Document Type Definition (DTD) to validate the above XML file.
18. A program to store and display student marks using arrays.

19. Write a HTML Program to demonstrate different forms of Lists- Ordered, Unordered, Nested and
description lists

B. V. R. I. T Dept of CSE Page No:110


Web Technologies Lab Manual Roll No:

20. Write a HTML Demonstration of Navigation through various frames


21. Write a PHP program for reversing the string?

22. Write a PHP program for creating feedback Form?

23. Write a PHP program for creating registration form?

B. V. R. I. T Dept of CSE Page No:111


Web Technologies Lab Manual Roll No:

Additional Content

CGI (Commmon Gateway Interface) :


The Common Gateway Interface (CGI) is the first technology used to generate dynamic
contents. It allows a web client to pass data to the application running on the web server so
that a dynamic web page can be returned to the client according to the input data. For
example, when you use a search engine, buy a book at an online store; get a stock quote
etc., your browser uses CGI to communicate with a server side application.
CGI is not a programming language, rather it is an interface (or a set of rules) that allows an
input from a web browser and produce an output in the form of HTML page. A CGI script
can be written in a verity of languages such as C, C++, Visual Basic, Perl, FORTRAN and
even Java. Out of these, Perl is most commonly used.
When a web server receives a request for a CGI script, the web server passes some
parameters to this script and executes it. The script runs and generates some output which
is then collected by the web server and returned to the client (browser).

1. CGI (Common Gateway Interface) is used to provide dynamic content to the user.
2. CGI is used to execute a program that resides in the server to process data or
access databases to produce the relevant dynamic content.
3. Programs that reside in server can be written in native operating system such as
C++.
Diagrammatic Representation :

We have listed some problems in CGI technology –


Advantages of CGI
1. CGI is a true cross-platform technology. This means that CGI scripts work with any web
browser as well as with most web servers running on Windows and Unix.
2. CGI is language independent. It can be written in a variety of languages so developers do
not have to learn a new language.
3. CGI is very simple interface. It is not necessary to have any special libraries to create a CGI
program or write programs using a particular API.
Disadvantages of CGI :
1. For each request CGI Server receives, It creates new Operating System Process.
2. If the number of requests from the client increases then more time it will take to respond to
the request.
3. As programs executed by CGI Script are written in the native languages such as C, C++,
perl which are platform independent.
4. A new process is started for each client request. The creation of the process for every such
request requires time and significant server resources which limits the number of requests
a server can handle.
5. CGI program cannot interact with the web server or take advantage of the server's abilities
once it begins execution. This is because it is running in a separate process. For example, a
CGI script cannot write to the server's log file.
Servlet :

B. V. R. I. T Dept of CSE Page No:112


Web Technologies Lab Manual Roll No:

CGI programs are used to execute programs written inside the native language. But in
Servlet all the programs are compiled into the Java bytecode which is then run in the Java
virtual machine.

In Servlet, All the requests coming from the Client are processed with the threads instead of
the OS process.
Servlets – Diagrammatic Representation

Servlets Execution Steps :


1. Browser or any HTTP client sent data to the HTTP Server in the form of Web Page.
2. The request sent by the Browser or client is read by Servlets. Request or data sent
includes
No. Request Sent by Browser includes

1 HTML Form

2 cookies

3 media types

4 compression schemes etc


3. Servlet then processes the data and generate the results
4. Servlet then Sends data to the clients (browsers) in verity of formats which includes
web page,images, pdf or excel

Difference between SERVLET and CGI


Both Java servlets and CGI are used for creating dynamic web applications that accept a
user request, process it on the server side and return responses to the user. However, Java
servlets provide a number of advantages over traditional CGI which are as follows,
• Efficient: Unlike traditional CGI where a new process is started for each client request,
a servlet processes each request as a thread inside of a process. Thus servlets improve the
performance as it removes the overhead of creating a new process for request every time.
Also, unlike CGI program which terminates after handling a request, the servlets remains in
memory even after they complete a response and destroyed only when the servlet container
is shutdown. Thus servlets make it easier to cache computations,
keep database connections open and perform other optimizations that rely on persistent
data.
• Powerful: Servlets support several capabilities that are difficult or impossible to
accomplish with traditional CGI. These capabilities include talking directly to the web
server, sharing data between multiple servlets, session tracking and caching of previous
computations.
• Portable: Since servlets are written in the Java programming language and follow a
standard API, so a servlet can be moved from one servlet compatible web server to another
very easily. For example, servlets written for Apache web server can run unchanged on
other severs such as Microsoft Internet Information (IIS) Server, IBM Web Sphere etc. On

B. V. R. I. T Dept of CSE Page No:113


Web Technologies Lab Manual Roll No:

the other hand, CGI programs may be platform dependent, need to be recompiled or web
server dependent.
• Inexpensive: A number of free or very inexpensive web servers are available these days.
Once you have a web server, adding servlet support to it costs very little. On the other
hand, CGI alternatives require a significant initial investment to purchase a proprietary
package.
• Language dependency: Since servlets can be written only in Java so they are language
dependent. On the other hand, CGI programs can be written in any programming language
like C, C++, Perl, Visual Basic or even Java so they are language independent.
• Secure: As Java was designed from the ground up as a secure language, so a servlet can
be run by a servlet engine or servlet container in restrictive sandbox just like an applet runs
in a web browser's JVM, which increases the server security. On the other hand, CGI
scripts are not subject to same degree of security sandboxing as Java servlets, they are
significantly less secure.
• Convenient: Servlets have an extensive infrastructure for automatically parsing and
decoding HTML form data, reading and setting HTTP headers, handling cookies, session
handling etc. On the other hand, CGI does not support such infrastructure.

Servlet Vs CGI :
Let’s differentiate Servlet and CGI –

Servlet CGI (Common Gateway Interface)

Servlets are portable CGI is not portable.

In Servlets each request is handled by IN CGI each request is handled by heavy


lightweight Java Thread weight OS process

In Servlets, Data sharing is possible In CGI, data sharing is not available.

Servlets can link directly to the Web server CGI cannot directly link to Web server.

Session tracking and caching of previous Session tracking and caching of previous
computations can be performed computations cannot be performed

Automatic parsing and decoding of HTML form Automatic parsing and decoding of HTML
data can be performed. form data cannot be performed.

Servlets can read and Set HTTP Headers CGI cannot read and Set HTTP Headers

Servlets can handle cookies CGI cannot handle cookies

Servlets can track sessions CGI cannot track sessions

Servlets is inexpensive than CGI CGI is more expensive than Servlets

Servlets are platform-independent server-side components, being written in Java.


1. Servlets used to create web application
2. Servlets are middle layer of between a request from browser or HTTP client and
database application.
3. Servlets are robust and scalable
4. Servlets are platform independent
5. Servlets resides at server side and generates dynamic web page
6. Servlets are used to collect input through the web forms or to show records from
database via web reports.
7. Servlets performance is significantly better than CGI.
8. Servlets execute within the address space of a Web server. So it is not not necessary
to create a separate process to handle each client request.
9. Servlets are secure.

B. V. R. I. T Dept of CSE Page No:114


Web Technologies Lab Manual Roll No:

Figure on Servlet vs GenericServlet vs HttpServlet

Observe the hierarchy and understand the relationship between the three (involved in
multilevel inheritance). With the observation, a conclusion can be arrived, to write a Servlet
three ways exist.
a) by implementing Servlet (it is interface)
b) by extending GenericServlet (it is abstract class)
c) by extending HttpServlet (it is abstract class)

The minus point of the first way is, all the 5 abstract methods of the
interface Servlet should be overridden eventhough Programmer is not interested in all (like
the interface WindowListener to close the frame). A smart approach is
inheriting GenericServlet (like using WindowAdapter) and overriding its only one abstract
method service(). It is enough to the programmer to override only this method. It is
a callback method (called implicitly). Still better way is extending HttpServlet and need not
to override any methods as HttpServlet contains no abstract methods. Eventhough the
HttpServlet does not contain any abstract methods, it is declared as abstract class by the
Designers to not to allow the Programmer to create an object directly because a Servlet
object is created by the system (here system is Servlet Container).

1. Servlet interface
It is the super interface for the remaining two – GenericServlet and HttpServlet. It contains
5 abstract methods and all inherited by GenericServlet and HttpServlet. Programmers
implement Servlet interface who would like to develop their own container.
2. GenericServlet
It is the immediate subclass of Servlet interface. In this class, only one abstract
method service() exist. Other 4 abstract methods of Servlet interface are given
implementation (given body). Anyone who extends this GenericServlet should
override service() method. It was used by the Programmers when the Web was not
standardized to HTTP protocol. It is protocol independent; it can be used with any protocol,
say, SMTP, FTP, CGI including HTTP etc.
Signature:
public abstract class GenericServlet extends java.lang.Object implements Servlet,
ServletConfig, java.io.Serializable

3. HttpServlet
When HTTP protocol was developed by W3C people to suit more Web requirements, the
Servlet designers introduced HttpServlet to suit more for HTTP protocol. HttpServlet is
protocol dependent and used specific to HTTP protocol only.
The immediate super class of HttpServlet is GenericServlet. HttpServlet overrides
the service() method of GenericServlet. HttpServlet is abstract class but without any
abstract methods.
With HttpServlet extension, service() method can be replaced by doGet() or doPost() with
the same parameters of service() method.
Signature:
public abstract class HttpServlet extends GenericServlet implements
java.io.Serializable

Being subclass of GenericServlet, the HttpServlet inherits all the properties (methods) of
GenericServlet. So, if you extend HttpServlet, you can get the functionality of both.

Let us tabulate the differences for easy understanding and remembering.

B. V. R. I. T Dept of CSE Page No:115


Web Technologies Lab Manual Roll No:

GENERIC SERVLET HTTP SERVLET

Can be used with any protocol (means, can Should be used with HTTP protocol only (can
handle any protocol). Protocol independent. handle HTTP specific protocols). Protocol
Generic Servlet is protocol independent.It dependent.
handles all types of protocol like http, smtp, HttpServlet is protocol dependent. It handles
ftp etc. only http protocol.

All methods are concrete except service() All methods are concrete (non-abstract).
method. service() method is abstract method. service() is non-abstract method.

service() should be overridden being abstract


in super interface. service() method need not be overridden.

It is a must to use service() method as it is a Being service() is non-abstract, it can be


callback method. replaced by doGet() or doPost() methods.

Extends Object and implements interfaces Extends GenericServlet and implements


Servlet, ServletConfig and Serializable. interface Serializable

Direct subclass of Servet interface. Direct subclass of GenericServlet.

Defined javax.servlet package. Defined javax.servlet.http package.

All the classes and interfaces belonging to All the classes and interfaces present in
javax.servlet package are protocol javax.servlet.http package are protocol
independent. dependent (specific to HTTP).

Not used now-a-days. Used always.

GenericServlet class is direct subclass of HttpServlet class is the direct subclass of


Servlet interface. Generic Servlet.

HttpServlet supports
public void service(ServletRequest
Generic Servlet only supports service() req,ServletResponse res ) and
method. It handles only simple request protected void service(HttpServletRequest
public void service(ServletRequest req,HttpServletResponse res).
req,ServletResponse res ). HttpServlet supports also
Generic Servlet only supports service() doGet(),doPost(),doPut(),doDelete(),doHead(),do
method. Trace(),doOptions()etc.

Similarities:
1. One common feature is both the classes are abstract classes.
2. Used with Servlets only.

Different Terms used in Servlet Technology :


Term Description

HTTP Protocol allows web servers and browsers to exchange data over the web

Get and Post Methods for a request-response data between a client and
method server

Container Run time environment for Java EE applications

Application A server that exposes business logic to client applications


Server through various protocols including HTTP.

Web Server A server that handles HTTP protocol.

B. V. R. I. T Dept of CSE Page No:116


Web Technologies Lab Manual Roll No:

Term Description

HTTP header which provides the description about what are


Content Type
you sending to the browser.

Deployment Activity by which make a web application available for use

LIFE CYCLE OF JSP

Difference between Servlets and JSP

Java Servlets are programs that run on a Web or Application server and act as a middle
layer between a request coming from a Web browser or other HTTP client and databases or
applications on the HTTP server.

Using Servlets, you can collect input from users through web page forms, present records
from a database or another source, and create web pages dynamically.

JavaServer Pages (JSP) is a technology for developing web pages that support dynamic
content which helps developers insert java code in HTML pages by making use of special
JSP tags, most of which start with <% and end with %>.

JSP are webpages similar to aspx/php pages which run at client side.

Key Differences :

 Servlet is html in java whereas JSP is java in html.


 Servlets run faster compared to JSP
 JSP can be compiled into Java Servlets
 It’s easier to code in JSP than in Java Servlets
 JSP is a webpage scripting language that can generate dynamic content while
Servlets are Java programs that are already compiled which also creates dynamic
web content
 In MVC, jsp acts as a view and servlet acts as a controller.
 JSP are generally preferred when there is not much processing of data required.
But servlets are best for use when there is more processing and manipulation
involved.

B. V. R. I. T Dept of CSE Page No:117


Web Technologies Lab Manual Roll No:

 The advantage of JSP programming over servlets is that we can build custom
tags which can directly call Java beans. There is no such facility in servlets.
 We can achieve functionality of JSP at client side by running JavaScript at
client side. There are no such methods for servlets.
 A servlet is like any other Java class. You put HTML into print statements like
you use System.out or how JavaScript uses document.write. A JSP technically
gets converted to a servlet but it looks more like PHP files where you embed the
Java into HTML.

JSP Servlets

JSP is a webpage scripting language that can Servlets are Java programs that are already
generate dynamic content. compiled which
also creates dynamic web content.

JSP run slower compared to Servlet as it takes Servlets run faster compared to JSP.
compilation time to convert into Java Servlets.

It�s easier to code in JSP than in Java Servlets. Its little much code to write here.

In MVC, jsp act as a view. In MVC, servlet act as a controller.

JSP are generally preferred when there is not servlets are best for use when there is
much processing of data required. more processing and manipulation involved.

The advantage of JSP programming over There is no such custom tag facility in servlets.
servlets is that we can build custom tags which
can directly call Java beans.

We can achieve functionality of JSP at client There are no such methods for servlets.
side by running JavaScript at client side.
Difference between Applet and Servlet

BASIS FOR
APPLET SERVLET
COMPARISON

Execution Applet is always executed on the Servlet is always executed on the

client side. server side.

Packages import java.applet.*; import javax.servlet.*;

import java.awt.*; import java.servlet.http.*;

Lifecycle init(), stop(), paint(), start(), init( ), service( ), and destroy( ).

methods destroy().

User interface Applets use user interface classes No User interface required.

like AWT and Swing.

B. V. R. I. T Dept of CSE Page No:118


Web Technologies Lab Manual Roll No:

BASIS FOR
APPLET SERVLET
COMPARISON

Requirement Requires java compatible browser It processes the input from client side

for execution. and generates the response in terms

of the HTML page, Javascript,

Applets.

Resources As it arrives at the client, it uses

the resources of the client to It utilizes the resources of the server

produce graphical interface and to process request and response of

run complex computation. the client.

Bandwidth Applets utilize more network Servlets are executed on the servers

Utilization bandwidth as it executes on the and hence require less bandwidth.

client machine.

Security More prone to risk as it is on the It is under the server security.

client machine.

B. V. R. I. T Dept of CSE Page No:119

Potrebbero piacerti anche