Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Lab Record
of
Name: ________________________________
Roll NO: _______________________________
Year: _______________ Sem: _____________
Branch:_____________ Section____________
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
CERTIFICATE
Date:
STUDENT PROFILE
NAME
ROLL NO
YEAR
SEMESTER
B.TECH
BATCH
LAB NAME
ACADEMIC YEAR
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:
RESOURCES:
PROCEDURE:
2. In the next Screen, Select the path if required and then click on the Next Button.
3. In the next screen select Apache and MySQL. You may optionally select FileZilla (FTP Client)
if needed. Click Install.
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
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
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:
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.*;
Element de=dom.getDocumentElement();
System.out.println("Enter the element tag name of xml document: ");
String xtn=sc.next();
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:
<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>
</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>
SAX PARSER
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
}//main
try
{
//
// Create SAXParserFactory instance and a SAXParser
//
}//try
catch (Exception e)
{
System.out.println(xfn +" FILE IS NOT WELL-FORMED");
e.printStackTrace();
}//catch
}//run
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
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:
<?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-1:
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" >
</xs:schema>
<?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
5. Write an XSLT program to convert the XML document into HTML page.
STEP-1:
<xsl:output method="html"/>
<xsl:template match="/">
<html><body>
<xsl:apply-templates/>
</body></html>
</xsl:template>
<xsl:template match="/PAGE/HEADING">
</xsl:template>
<xsl:template match="/PAGE/ARTICLE">
</xsl:template>
<xsl:template match="/PAGE/ARTICLE/TITLE">
</xsl:template>
<xsl:template match="/PAGE/ARTICLE/DESCRIPTION">
</xsl:template>
<xsl:template match="/PAGE/ASIDE/TITLE">
</xsl:template>
<xsl:template match="ITEM">
</xsl:template>
<xsl:template match="/PAGE/FOOTER">
<div style="clear:both;"></div>
</xsl:template>
</xsl:stylesheet>
STEP-2:
<?xml version="1.0"?>
<PAGE>
<HEADING>page heading</HEADING>
<ARTICLE>
<TITLE>article title</TITLE>
<DESCRIPTION>article description</DESCRIPTION>
</ARTICLE>
<ASIDE>
<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
<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>
<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
{
print "ERROR CREATING DATABASE: " .mysql_error();
}
//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/>";
?>
</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
<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>
<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>
<html>
<head>
<title>USER VALIDATION using XML FILE WITH using HTML FORMS & PHP</title>
</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
c. A simple calculator web application that takes two values and an arithmetic operator
from an HTML page and return s the result.
<!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>
<!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
?>
</body>
</html>
STEP-4: OPEN THE WEB BROWSER & TYPE THE C:/xampp/htdocs/p/p6c.html FOR
RUNNING THE p6c.html file
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>.
<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>
<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' );
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>
<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-5: OPEN THE WEB BROWSER & TYPE THE C:/xampp/htdocs/lp/login.html FOR
RUNNING THE login.html file
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
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;
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("use user_db105;");
pw.println("USING Database user_db105, here we are creating tables");
while(rs.next())
{
pw.println(rs.getString("username") +" " +rs.getString("password"));
}
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/>");
}
rs.close();
st.close();
con.close();
}
catch(Exception e)
{
pw.println("ERROR");
e.printStackTrace();
}
pw.close();
}//main
}//sdb
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-class>sdb</servlet-class>
</servlet>
<servlet-mapping>
<url-pattern>/servlets/sdb</url-pattern>
</servlet-mapping>
STEP-6: Go to the xampp control panel and start the Mysql and Tomcat server
STEP-7: OPEN THE WEB BROWSER & TYPE THE C:/st/p6e.html FOR RUNNING THE
p6e.html file
f. A user validation application using user name and password matching with database
information.
<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>
<% -- USER VALIDATION using JSP & MYSQL DATABASE --% >
<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("use user_db105;");
out.write("USING Database user_db105, here we are creating tables");
while(rs.next())
{
out.write(rs.getString("username") +" " +rs.getString("password"));
}
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);
}
else
{
out.write("<br/><b><font color=red> INVALID USERNAME & PASSWORD
</font></b><br/>");
}
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-5: RUN THE Tomcat & MySQL SERVER UNDER XAMPP CONTROL PANEL
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
<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
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. 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>
</head>
<body>
</form>
</body>
</html>
STEP-2:
//GetCookieReadServletDemo
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
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.close();
//PostCookieSetServletDemo
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
String t1 = request.getParameter("txt_data");
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
//create cookie
response.addCookie(c);
pw.println(t1);
pw.println("<br><br><br>");
pw.close();
STEP-3:
STEP-4:
<servlet>
<servlet-name>PostCookieSetServletDemo Example</servlet-name>
<servlet-class>PostCookieSetServletDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>PostCookieSetServletDemo Example</servlet-name>
<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-6: Open the web browser and run the html file like CookieDemo.html in the URL LIKE
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
<!-- 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>
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>
response.addCookie(namecookie);
STEP-6: Open the web browser and type the URL LIKE http://
localhost:8080/examples/jsp/LP-JSP/input.html
8. Write a program for session tracking using PHP, Servlets and JSP.
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
PROGRAM EXPLANATION
STEP-1:
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
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";
else
c=new Integer(c.intValue()+1);
session.setAttribute("c",c);
pw.println("<html>");
pw.println("<head>");
pw.println("<title>");
pw.println("</title>");
pw.println("</head>");
pw.println("<body>");
pw.println("<h1>" +heading);
pw.println("</body>");
pw.println("</html>");
pw.close();
}//doGet
}//SessionServletDemo
STEP-2:
STEP-3:
STEP-4:
<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-6: Open the web browser and give the URL LIKE
HTTP://localhost:8080/examples/servlets/SessionServletDemo and you will get the
following output
STEP-1:
FIRST OF ALL OPEN SOME TEXT EDITOR LIKE NOTEPAD AND TYPE THE FOLLOWING CODE
LIKE
<html>
<head>
<!-- THIS IS BASIC HTML PAGE (HTML COMMENT STATEMENT STYLE) -->
</head>
<% -- DISPLAYING THE MESSAGE ON THE BROWSER (JSP COMMENT STATEMENT STYLE)--% >
<body>
<h3>WELCOME</h3>
</body>
</html>
STEP-2:
STEP-3:
STEP-4:
<html>
<head>
<title>EMPLOYEE DB DEMO</title>
</head>
<body>
<?php
$conn=mysql_connect("localhost","root","yes") or die(mysql_error());
if(!$conn)
else
print "CONNECTED<br/>";
//CREATING A DATABASE
else
mysql_query("use EMPLOYEE1",$conn);
mysql_select_db("EMPLOYEE1",$conn) or die(mysql_error());
//CREATING A TABLE
print "<br/>";
//INSERTING A ROW
print "<br/>";
print "<br/>";
echo "<tr><th>eno</th><th>ename</th><th>esal</th></tr>";
while($row=mysql_fetch_array($result))
echo "<tr><td>";
echo $row['eno'];
echo "</td><td>";
echo $row['ename'];
echo "</td><td>";
echo $row['esal'];
echo "</td></tr>";
}//while
echo "</table>";
print "<br/>";
print "<br/>";
echo "<tr><th>eno</th><th>ename</th><th>esal</th></tr>";
while($row=mysql_fetch_array($result))
echo "<tr><td>";
echo $row['eno'];
echo "</td><td>";
echo $row['ename'];
echo "</td><td>";
echo $row['esal'];
echo "</td></tr>";
}//while
echo "</table>";
print "<br/>";
print "<br/>";
echo "<tr><th>eno</th><th>ename</th><th>esal</th></tr>";
while($row=mysql_fetch_array($result))
echo "<tr><td>";
echo $row['eno'];
echo "</td><td>";
echo $row['ename'];
echo "</td><td>";
echo $row['esal'];
echo "</td></tr>";
}//while
echo "</table>";
print "<br/>";
print "<br/>";
mysql_query($query,$conn);
mysql_close($conn);
?>
</body>
</html>
STEP-2:
STEP-3:
(OR)
<html>
<head>
<title>
</head>
<frameset rows="100,*">
<frameset cols="200,*">
</frameset>
</frameset>
<body></body>
</html>
<html>
<body>
<center>
</center>
</body>
</html>
<html>
<head>
<title>DATABASE CONNECTION</title>
</head>
<body>
</body>
</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"
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>
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;
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_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("<br/>");
out.println("<br/>");
out.println("<br/>");
out.println("<input type='submit'value='Submit'>");
out.println("</from>");
out.println("</body>");
out.println("</html>");
}//try
catch(SQLException e)
catch(ClassNotFoundException 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
out.close();
}//service
}//class
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;
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);
out.println("<html>");
out.println("<body>");
out.println("<strong>Enter id to delete</strong>");
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)
catch(ClassNotFoundException 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
out.close();
}//service
}//class
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;
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");
String emp_phn=request.getParameter("ephn");
if(emp_id==null)
emp_id="0";
int n=Integer.parseInt(emp_id);
rs=st.executeQuery("select*from emp");
out.println("<html>");
out.println("<body>");
out.println("<strong>Enter id to update</strong>");
out.println("<br/>");
out.println("<input name='eid'type='text'>");
out.println("<br/>");
out.println("<br/>");
out.println("<br/>");
out.println("<input type='submit'value='Submit'>");
out.println("</from>");
out.println("</body>");
out.println("</html>");
}//try
catch(SQLException e)
catch(ClassNotFoundException 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
out.close();
}//service
}//class
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;
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());
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)
catch(ClassNotFoundException 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
out.close();
}//service
}//class
STEP-9: CREATE DATABASE & TABLES IN MYSQL, & NOW RUN XAMPP CONTROL PANEL AND START
APACHE AND MYSQL SERVER
(OR)
STEP-10: RUN THE JAVA PROGRAM IN COMMAND PROMPT THAT STORED IN C:\JS
<!-- Define servlets that are included in the example application -->
<servlet>
<servlet-name>Insert_Q Example</servlet-name>
</servlet>
<servlet-mapping>
<url-pattern>/servlets/ Insert_Q
</url-pattern>
</servlet-mapping>
STEP-13: START MYSQL AND TOMCAT SERVER UNDER THE XAMPP CONTROL PANNEL
STEP-14: OPEN THE WEB BROWSER AND TYPE THE URL LIKE C:\JS\DBDemo.html
=======================================================================================
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>
</head>
<body>
<center>
<table>
<tr>
<td>Sl.No.</td>
</tr>
<tr>
<td>Book Name</td>
</tr>
<tr>
<td>Publisher Name</td>
</tr>
<tr>
<td>Price</td>
</tr>
<tr>
<td>Quantity</td>
</tr>
<tr>
</tr>
</table>
</form>
</center>
</body>
</html>
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
System.out.println("from init\n");
}//init
System.out.println("from service\n");
response.setContentType("text/html");
Enumeration e=request.getParameterNames();
while(e.hasMoreElements())
String n=(String)e.nextElement();
out.println(n + "=");
String v=request.getParameter(n);
out.println(v +"\n");
out.println();
}//while
out.close();
}//service
System.out.println("from destroy");
}//destroy
}//HtmlLifeCycleServletDemo
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
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>
<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.
----------------------------------------------------------------------------------------------------------------------------------
STEP-1
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
response.setContentType("text/html");
out.println("<!DOCTYPE HTML>");
out.println("<HTML>");
out.println("<HEAD>");
out.println("</HEAD>");
out.println("<BODY>");
out.println("<br><hr><br>");
out.println(ms[r.nextInt(ms.length)]);
out.println("</BODY>");
out.println("</HTML>");
STEP-2
----------------------------------------------------------------------------------------------------------------------------------
STEP-1: sum.html
<html>
<body>
<center>
<table>
<tr>
</tr>
<tr>
</tr>
</table>
</body>
</html>
STEP-2: Add.java
/*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.
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
Enumeration e = request.getParameterNames();
int sum1=0;
while(e.hasMoreElements())
sum1+=Integer.parseInt(pvalue);
pw.println(pvalue+"\n");
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.
----------------------------------------------------------------------------------------------------------------------------------
STEP-1:
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
ServletConfig config=getServletConfig();
Enumeration e = config.getInitParameterNames();
int sum1=0;
while(e.hasMoreElements())
sum1=sum1+Integer.parseInt(pvalue);
pw.println(pvalue +"\n");
String num=config.getInitParameter("number");
int n=Integer.parseInt(num);
int rev=0,t;
while(n>0)
t=n%10;
rev=(rev*10)+t;
n=n/10;
}//while
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>
<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:
----------------------------------------------------------------------------------------------------------------------------------
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:
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>
<B>Color:</B>
</select>
<br><br>
</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.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
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.
c. Select a color.
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.
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>
</html>
STEP-3: PostServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
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.
c. Select a color.
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.
----------------------------------------------------------------------------------------------------------------------------------
=======================================================================================
VIVA QUESTIONS
5. What is Mysql?
26. What are some of the common lists that can be used when designing a page?
27. How do you create links to sections within the same page?
30. How do you change the number type in the middle of a list?
32. How do you create a link that will connect to another web page when clicked?
33. Is Java purely object oriented language?
44. How do you execute a PHP script from the command line?
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?
56. What function do we use to find length of string, and length of array?
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?
LAB ASSIGNMENT
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.
11. To create a php program to demonstrate the different file handling methods.
12. Write a program to reverse a number 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.
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
Additional Content
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 :
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
1 HTML Form
2 cookies
3 media types
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 –
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
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.
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.
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).
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.
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
Term Description
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 :
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.
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
methods destroy().
User interface Applets use user interface classes No User interface required.
BASIS FOR
APPLET SERVLET
COMPARISON
Requirement Requires java compatible browser It processes the input from client side
Applets.
Bandwidth Applets utilize more network Servlets are executed on the servers
client machine.
client machine.