Sie sind auf Seite 1von 119

List of Experiments

S.No. Exp.No. Name of the Experiment


Install the following on the Local Machine
i)Apache Web Server
1. 1 ii)Tomcat Application Server Locally
iii)Install MySQL
iv)Install PHP and configure it to work with Apache web server
Write an HTML page including any required Javascript that takes
a number from one text field in the range of 0 to 999 and shows it
2. 2 in another text field in words.If the number is out of range, it
should show “Out of range” and if it is not a number, it should
show “not a number” message in the result box
Write an HTML page that has one input, which can take multi-
line text and a submit button. Once the user clicks the submit
3. 3 button, it should show the number of characters, words and lines
in the text entered using an alert message. Words are separated
with white space and lines are separated with new line character.
Write an HTML page that contains a selection box with a list of 5
countries. When the user selects a country, its capital should be
4. 4
printed next to the list. Add CSS to customize the properties of
the font of capital(color, bold and font size)
Create an XML document that contains 10 users information.
Write a Java program, which takes User Id as input and returns
the user details by taking the user information from the XML
5. 5
document using
i)DOM Parser
ii)SAX Parser
Implement the following web applications using
6
a)PHP
b)Servlets
c)JSP
6. A user validation web application, where the user submits the
i.
login name and password to the server. The name and password
are checked against the data already available in Data base and if
the data matches, a successful login page is returned. Otherwise a
failure message is shown to the user.
7. ii. Modify the above program to use an XML file instead of database
Modify the above program to use AJAX to show the result on the
8. iii.
same page below the submit button
A simple calculator web application that takes two numbers and
9 iv. an operator (+,-,/,* and %) from an HTML page and returns the
result page with the operation performed on the operands.
Modify the above program such that it stores each query in a
10 v.
database and checks the database first for the result. If the query
is already available in the DB, it returns the value that was
previously computed(from DB) or it computes the result and
returns it after storing the new query and result in DB
A web application takes a name as input and on submit it shows a
hello <name> page where <name> is taken from the request. It
shows the start time at the right top corner of the page and
11 vi. provides a logout button. On clicking this button, it should show a
logout page with Thank You <name> message with the duration
of usage(hint: Use session to store name and time)

A web application that takes name and age from an HTML


page.vIf the age is less than 18, it should send a page with “Hello
12 vii. <name>, you are not authorized to visit this site” message, where
<name> should be replaced with the entered name. Otherwise it
should send “Welcome <name> to this site” message
A web application for implementation
The user is first served a login page which takes user’s name and
password. After submitting the details the server checks these
values against the data from a database and takes the following
decisions.
If name and password matches, serves a welcome page with
user’s full name
13 viii. If name matches and password doesn’t match, then serves
“password mismatch” page
If name is not found in the database, serves a registration page,
where user’s full name is asked and on submitting the full name,
it stores, the login name, password and full name in the data
base(hint: Use session for storing the submitted login name and
password)

A web application that lists all cookies stored in the browser on


14 ix.
clicking “List Cookies” button. Add cookies if necessary.
1. Install the following on the Local Machine

i) Apache Web Server

Step 1: Download Apache 2.2

(1) Go to Archived Win32 binaries download page -


here http://archive.apache.org/dist/httpd/binaries/win32/

(2) Download Apache 2.2.14 msi installer.

Here is the direct download link apache_2.2.14-win32-x86-no_ssl.msi

Step 2: Start installation

Click on Next to Continue..


Step3: Accept License Agreement and click on Next to continue

Step3: Read Apache HTTP server details and click on Next to continue
Step 5: Add localhost to both Network Domain and Server Name box. Administrator's Email
Address can be anything you like.These info are used for Apache configuration file but you can
change them after the installation.Next, select the first radio button as recommended. This way,
Apache will be running as a Windows Service.

Step 6: Choose Typical as the setup type.


Step 7: You can leave the default installation folder as is.

Step 8: Ready to install then Click on Install to continue installation


Step 9: Installing in progress

Step 10: Completed successfully So click on Finish


Test your installation:

After install, open web browser and type either of the following URLs into your browser's address bar
and hit Enter key.

1. http://localhost
2. http://127.0.0.1
3. http://169.254.32.57 or 192.168.0.1 (eg. local network IP address)

If Apache has been installed correctly, you should see a success message opened in your web browser,
as shown below.

Edit the Apache httpd.conf Configuration File:

1. Apache Configuration File is located at

C:\Program Files\Apache Software Foundation\Apache2.2\conf\httpd.conf. It can also be opened from


the Start menu as below.

Make sure you change the httpd.conf file according to the screenshots shown in the following section.

2. Change your document root directory to a more meaningful one.

Inside the configuration file, DocumentRoot is the directory out of which Appache executes web
documents, eg. PHP, HTML, etc. It's the directory where your PHP or other web page files are placed
into.

1. Commented out DocumentRoot "C:/Program Files/Apache Software Foundation/Apache2.2/htdocs"


2. Then added DocumentRoot "C:/test"

So, all my php files will be located in a folder named as test on my C drive.
3. Commented out <Directory "C:/Program Files/Apache Software Foundation/Apache2.2/htdocs">
4. Then added <Directory "C:\test">

Add PHP file type into DirectoryIndex:

Add the default document file names that Apache will run if we don't type its filename in web browser.

Edit the line as below shows, ie., DirectoryIndex index.html index.htm index.php
Restart Apache:

After changing Apache configuration file, remember restart Apache Server so that these changes will
take effect.

To start, stop, and restart Apache Server, do this: Start -> Programs -> Apache HTTP Server ->
Control Apache Server.

If Control Apache Server menu is not available. You can start, stop, and restart Apache by using
Microsoft Management Console for Windows Services.

Start -> Settings -> Control Panel -> Administrative Tools -> Services

By using Windows Services, you can Start, Stop, and Restart Apache from Microsoft Management
Console. See screenshot below. Selecting Apache as a Windows service will make it automatically
start when your computer starts up, and to keep Apache running when you log-off.

ii)Tomcat Application Server Locally

Step 1:

Installation of JDK:

Before beginning the process of installing Tomcat on your system, ensure first the availability of JDK
on your system program directory. Install it on your system if not already installed (because any
version of tomcat requires the Java 1.6 or higher versions) and then set the class path (environment
variable) of JDK. To set the JAVA_HOME Variable: you need to specify the location of the java run
time environment to support the Tomcat else Tomcat server cannot run.

This variable contains the path of JDK installation directory.

set JAVA_HOME=C:\Program Files\Java\jdk1.6


Note: it should not contain the path up to bin folder. Here, we have taken the URL path according to
our installation convention.
For Windows OS, go through the following steps:

Start menu->Control Panel->System->Advanced tab->Environment Variables->New->set the


Variable name = JAVA_HOME and variable value = C:\Program Files\Java\jdk1.6
Now click on all the subsequent ok buttons one by one. It will set the JDK path.

Step 2:

For setting the class path variable for JDK, do like this:

Start menu->Control Panel->System->Advanced tab->Environment Variables->New->


Set PATH="C:\Program Files\Java\jdk1.6\bin"; %PATH%
OR First, right click on the

My Computer->properties->advance->Environment Variables->path.

Now, set bin directory path of JDK in the path variable

Step 3:

The process of installing Tomcat 6.0 begins here from now. It takes various steps for installing and
configuring the Tomcat 6.0.For Windows OS, Tomcat comes in two forms: .zip file and .exe file (the
Windows installer file). Here we are exploring the installation process by using the .exe file. First
unpack the zipped file and simply execute the '.exe' file.
A Welcome screen shot appears that shows the beginning of installation process. Just click on the
'Next' button to proceed the installation process.

Step 4: A screen of 'License Agreement' displays.

Click on the 'I Agree' button.

Step 5:

A screen shot appears asking for the 'installing location'

Choose the default components and click on the 'Next' button.


Step 6:

A screen shot of 'Configuration Options' displays on the screen. Choose the location for the Tomcat
files as per your convenience. You can also opt the default Location

The port number will be your choice on which you want to run the tomcat server. The port number
8080 is the default port value for tomcat server to proceed the HTTP requests. The user can also
change the 'port number' after completing the process of installation; for this, users have to follow the
following tips.

Go to the specified location as " Tomcat 6.0 \conf \server.xml ". Within the server.xml file choose
"Connector" tag and change the port number.

Now, click on the 'Next' button to further proceed the installation process.

Step 7:

A Window of Java Virtual Machine displays on the screen

This window asks for the location of the installed Java Virtual Machine. Browse the location of the
JRE folder and click on the Install button. This will install the Apache tomcat at the specified location.
Step 8:

A processing window of installing displays on the screen.

To get the information about installer click on the "Show details" button

Step 9:

A screen shot of 'Tomcat Completion' displays on the screen.

Click on the 'Finish' button.


Step 10:

A window of Apache Service Manager appears with displaying the running process.

Let the running process goes on.

Step 11:

After completing the installation process, the Apache Tomcat Manager appears on the toolbar panel
like shown in the below picture.

Configuring Tomcat Manager

To Configure the Tomcat Manager, there are two ways; either user can configure Tomcat directly from
the toolbar panel or can configure it from Control Panel Section.

i-) Configuring from toolbar Panel

To Configure Apache Tomcat web server from the toolbar panel, you have to press 'double click' on
the appeared icon.
A configured window appears on the desktop. Now, just click on the Startup button. The installation
process will be completed.

ii-) Configuration from the Control Panel:

To configure the Apache Tomcat Manager, Users will have to follow the follwing steps:

Click on the Start up button -- select Control Panel -- Administrator Tool -- Services -- select Apache
Tomcat.

The following screen displays on the monitor.

Double click on the Apache Tomcat. The window of Apache Tomcat Properties appears on the screen.

Now, Click on the start up button. The Apache Tomcat is now ready to function.

To operate it, follow the below steps of processing:

Start the Tomcat Server:


1. Start the tomcat server from the bin folder of Tomcat 6.0 directory by double clicking the
"tomcat6.exe" file.
OR

Create a shortcut of this .exe file at your desktop.


2. Now Open web browser and type URL http://localhost:8080 in the address bar to test the server
3. To Stop the Tomcat Server: Stop the server by pressing the "Ctrl + c" keys.

The screen of Apache Tomcat software looks like this:

iii) Install MySQL

Step 1:

Download MySQL 5.0 Community Edition to your Desktop.

Step 2:

Unzip mysql-5.0.45-win32.zip (the downloaded mysql file) to get Setup.exe. Double click Setup.exe to
start installing MySQL. Click “Next ” when you are prompted as below.
Step 3:

Select “Typical” for Setup Type and click “Next ” again.

Step 4:

Click “Install ” to proceed with the installation process.

Step 5:

The setup activity will show you some advertisement. Read it if you wish and click “Next “.
Step 6:

Tick “Configure the MySQL Server now” and click “Next ” two times.

Step 7:

Click “Standard Configuration” to ease installation process and click “Next ” again.

Step 8:

Tick “Install As Windows Service” to make MySQL auto-startup with Windows and “Include Bin
Directory in Windows PATH ” to make MySQL system files automatically available for other
application.
Step 9:

Tick “Modify Security Settings” and enter a root (Administrator) password to secure your MySQL
installation. Don’t skip this step! Click “Next ” again.

Step 10:

Click “Execute” to start the MySQL Configuration process. Once finished, click “Finish ” to end
configuration.
Step 11:

Make sure MySQL runs automatically after installation. You can check the status from Administrative
Tools Services snap in (Start -> Programs -> Administrative Tools -> Services ), also available via
Control Panel.

Step 12:

(OPTIONAL) Open your DOS command prompt (Run -> cud). Type in “net stat -na“. Check out ports
opened by MySQL (3306) and Apache (80) . That means the services are up and running.

Step 13:

(OPTIONAL) Run some of MySQL commands to further ensure that the installation is a success.
Check out and follow the commands as pictured below. User account is root and password depends on
what you have entered previously during your MySQL configuration.
Step 14:

IMPORTANT: Reboot your machine! This is to ensure all MySQL system files are rss-read by
Windows as environment variables.

iv) Install PHP and configure it to work with Apache web server:

Step1:

Download the latest Windows PHP Binaries (MSI file) and Save the file to your Desktop.

Step 2:

Right click on the file and click “Install“.

Step 3:

Click “Next ” once the Welcome page is displayed.


Step 4:

Select “I accept the license agreement” and click “Next “.

Step 5:

Change your PHP installation path OR just accept the default path – C:\Program Files\PHP\ and click
“Next “.

Step 6: On the Web Server Setup screen, select the Apache 2.2.x Module and click “Next“.
Step 7:

On the Apache Configuration Directory screen, browse for the Apache configuration directory
(conf) OR just enter C:\Program Files\Apache Software Foundation\Apache2.2\conf\ and click
“Next ” to proceed with the installation.

Step 8:

For now, accept the default selection and click “Next”.

Step 9:

Click “Install ” to install PHP 5 on Windows.


Step 10:

Click “Finish ” once completed. PHP 5 is successfully installed.

Step 11:

Start your Apache 2.2 server using the “Monitor Apache Servers” console (Start -> Apache HTTP
Servers 2.2.4 -> Monitor Apache Servers ). You can see that PHP was successfully installed by
checking the Apache status at the bottom of the console.
Test your PHP 5 Installation:

1- Open up your Windows Notepad. Type in “<?php phpinfo(); ?>” inside the file. Save this file as
“info.php” inside your Apache root directory, C:\Program Files\Apache Software
Foundation\Apache2.2\htdocs .

2- Open up your web browser. In the address bar, type in your web server domain name plus
info.php as the file name. Example: http://www.syahid.com/info.php . You should get a PHP
configuration page just like the one below.

Congratulations! You have successfully installed and test PHP 5 on Windows!

Configure Apache 2.2.x with PHP :

1- Rename your index.html to index1.html and info.php to index.php (for testing purposes only!).
2- Edit your Apache configuration file,

C:\Program Files\Apache Software Foundation\Apache2.2\conf\httpd.conf by opening it with


Windows Notepad.

3- Find a line that starts with “DirectoryIndex index.html…“. Add index.php at the end of the line .
Save the file and restart your Apache Server from the “Monitor Apache Servers” console.

4- Load your Internet browser again. Type in your web server address e.g http://www.syahid.com. You
should get a page similar to the info.php page above. Index.php now is recognized as a default Apache
homepage, just like your normal index.html page.

Configure PHP with MySQL:

1- Open the Add / Remove Programs console via Windows Control Panel. Find thePHP 5.x.x
entry and click “Change “.
2- Click “Next ” once you are prompted the Welcome page.

3- Click the “Change ” button to proceed.

4- Select Apache 2.2.x as shown in the picture below. Click “Next ” once again.
5- Select your Apache configuration directory (conf) – the directory where your httpd.conf resides.
Click “Next ” once done.

6- On the “Choose items to install” screen, click on the plus (+) icon next to Extensions to expand the
list.
7- Select on the “X” next to “MySQL” and select “Entire feature will be installed on local hard
drive”. Click “Next” again.

8- Click the “Change” button to save all the PHP configuration changes.
9- Finally, restart your Apache 2.2 web server! You can check out that the MySQL extension
support for PHP was successfully installed by checking out the info.php / index.php page that was
created before.
2. Write an HTML page including any required Java Script that takes a number from one text field in
the range of 0 to 999 and shows it in another text field in words. If the number is out of range, it should
show “Out of range” and if it is not a number, it should show “not a number” message in the result box

week2.html

<html>
<head>
<title>Number to word conversion</title>
<script language="javascript">
function convertion()
{
n=document.f1.t1.value;
i=0;
s="";
var tens=['ten','twenty','thirty','forty','fifty','sixty','seventy','eighty','ninty'];
var
ones=['','one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelev
e','thirteen','forteen','fifteen','sixteen','seventeen', 'eighteen', 'ninteen'];
if(n>999)
alert("You entered out of range number...");
if(isNaN(n))
alert("You must enter only numbers...");
else
{
if(n>99 && n<1000)
{
i=Math.floor(n/100);
s=ones[i]+" hundreden ";
n=n%100;
}
if(n>19 && n<100)
{
i=Math.floor(n/10);
s=s+tens[i-1]+" ";
n=n%10;
}
if(n>0 && n<20)
s=s+ones[n]+" ";
document.f1.t2.value=s;
}
}
</script>
</head>
<body><center>
<h1>Number to Word Conversion</h1>
<form name="f1">
<br>
Enter your number :&nbsp;<input type="text" name="t1"><br><br>
<p><input type="button" value="Convert" onClick="convertion()">
<input type="reset" value="Reset"><br><br>
After Convertion:&nbsp;<input type="text" name="t2" size="30">
</form></center>
</body>
</html>

OUT PUT:
3. Write an HTML page that has one input, which can take multi-line text and a submit button. Once
the user clicks the submit button, it should show the number of characters, words and lines in the text
entered using an alert message. Words are separated with white space and lines are separated with new
line character.

week3.html

<html>
<head>
<title>Counts</title>
<script language="javascript">
function count()
{
var a=document.f.t.value;
if(a.length>0)
{
var len=a.length;
var l=1;
var w=1;
for(var i=0;i<len;i++)
{
if(a[i]=="\n")
l=l+1;
if(a[i]==" "||a[i]=="\n")
w=w+1;
}
alert("No. of words:"+w+ "\nNo. of lines:"+l+"\nNo. of Characters
:"+len);
}
else
alert("No. of words:0 \n No. of lines:0 \n No. of Characters :0");
}
</script>
</head>
<body>
<form name="f">
<h1>Number of lines and words</h1>
<textarea name="t" rows="5" cols="43"></textarea>
<p><input type="button" value="Click" onClick="count()" >
<input type="reset">
</form>
</body>
</html>
OUT PUT:
4. Write an HTML page that contains a selection box with a list of 5 countries. When the user selects a
country, its capital should be printed next to the list. Add CSS to customize the properties of the font
of capital (color, bold and font size)

week4.html

<html>
<head>
<style>
#l1
{
color:red;
font:20px verdana;
font-weight:bold;
}
</style>
<script language="javascript">
function getCapital()
{
var country;
country=parseInt(document.f1.d1.value);
switch(country)
{
case 1:document.f1.l1.value="New Delhi";
break;
case 2:document.f1.l1.value="Mascow";
break;
case 3:document.f1.l1.value="Nairobi";
break;
case 4:document.f1.l1.value="Beizing";
break;
case 5:document.f1.l1.value="Koulalumpur";
break;
}
}
</script>
</head>
<body>
<h1 align="center">Select Country to get Capital</h1>
<form name="f1"><br><br>
Select Country :
<select name="d1" onChange="getCapital()">
<option>- Select Country -</option>
<option value="1">India</option>
<option value="2">Rassia</option>
<option value="3">Kenya</option>
<option value="4">China</option>
<option value="5">Singapur</option>
</select>
<br><br><br><br>
Capital City :<input type="label" id="l1" width="30">
</form>
</body>
</html>
OUT PUT:

5. Create an XML document that contains 10 users information. Write a Java program, which takes
User Id as input and returns the user details by taking the user information from the XML document
using

i)DOM Parser

user.html

<html>
<head>
<script language="javascript">
function fncDisplayInfo()
{

var flag=0;
var userid=document.frm.uname.value;
var xmlDoc=new ActiveXObject("microsoft.xmldom");
xmlDoc.load("user.xml");
var noofusers=xmlDoc.getElementsByTagName("userlist")[0].childNodes.length;
for(var i=0;i<parseInt(noofusers);i++)
{
var
uid=xmlDoc.getElementsByTagName("user")[i].childNodes[0].childNodes[0].nodeValue;
if(uid==userid)
{
document.write("<h1>User Details</h1>");
var
userName=xmlDoc.getElementsByTagName("user")[i].childNodes[1].childNodes[0].nodeValue;
var
Address=xmlDoc.getElementsByTagName("user")[i].childNodes[2].childNodes[0].nodeValue;
var
Phone=xmlDoc.getElementsByTagName("user")[i].childNodes[3].childNodes[0].nodeValue;
var
Email=xmlDoc.getElementsByTagName("user")[i].childNodes[4].childNodes[0].nodeValue;
document.write("<br>User ID : "+uid);
document.write("<br>User Name : "+userName);
document.write("<br>ADDRESS : "+Address);
document.write("<br>Phone No : "+Phone);
document.write("<br>Mail ID : "+Email);
flag=1;
break;
}
}
if(flag==0)
{
alert("Invalid User ID...");
}
}
</script>
</head>
<body>
<center>
<h1><b>User Information</h1>
<form name="frm">
User ID :<input type="text" name="uname"></br></br></br>
<input type="button" name="b1" value="Submit" onClick="fncDisplayInfo()">
</form>
</center>
</body>
</html>

user.xml

<?xml version="1.0"?>
<userlist>
<user>
<uid>user01</uid>
<uname>Ramesh</uname>
<address>Mahabubnagar</address>
<phone>9865245879</phone>
<email>rameshchary@gmail.com</email>
</user>
<user>
<uid>user02</uid>
<uname>Karthik</uname>
<address>Yenugonda</address>
<phone>9865245654</phone>
<email>karthikchary@gmail.com</email>
</user>
.......
<user>
<uid>user10</uid>
<uname>Mahesh</uname>
<address>Yenugonda</address>
<phone>9865296654</phone>
<email>maheshchary@gmail.com</email>
</user>
</userlist>

OUT PUT:
ii)SAX Parser

saxusers.xml

<users-details>
<user type="Female">
<Id>1111</Id>
<Name>sony</Name>
<Address>mbnr</Address>
</user>
<user type="Male">
<Id>1112</Id>
<Name>Bhanu</Name>
<Address>hyd</Address>
</user>
<user type="Female">
<Id>1113</Id>
<Name>Sowmya</Name>
<Address>Jdcl</Address>
</user>
<user type="Male">
<Id>1114</Id>
<Name>Anil</Name>
<Address>WNP</Address>
</user>
<user type="Female">
<Id>1115</Id>
<Name>Ananya</Name>
<Address>KTKT</Address>
</user>
<user type="Female">
<Id>1116</Id>
<Name>Angana</Name>
<Address>Gdwl</Address>
</user>
<user type="Male">
<Id>1117</Id>
<Name>Akhil</Name>
<Address>mbnr</Address>
</user>
<user type="Female">
<Id>1118</Id>
<Name>Jay</Name>
<Address>Gdwl</Address>
</user>
<user type="Male">
<Id>1119</Id>
<Name>Raghu</Name>
<Address>Gdwl</Address>
</user>
<user type="Male">
<Id>1120</Id>
<Name>Srinu</Name>
<Address>mbnr</Address>
</user>
</users-details>

user.java

public class user


{
public String name;
public int id;
public String address,type;
public user()
{
public user(int id,String name,String address,String type)
{
this.name=name;
this.address=address;
this.id=id;
this.type=type;
}
}
public String getAddress()
{
return address;
}
public void setAddress(String address)
{
this.address=address;
}
public int getId()
{
return id;
}
public void setId(int id)
{
this.id=id;
}
public String getName()
{
return name;
}
publ-ic void setName(String name)
{
this.name=name;
}
public String getType()
{
return type;
}
public void setType(String Type)
{
this.type=type;
}
public String toString()
{
StringBuffer sb=new StringBuffer();
sb.append(getId());
sb.append(",");
sb.append(getName());
sb.append(",");
sb.append(getType());
sb.append(",");
sb.append(getAddress());
return sb.toString();
}
}

exp5saxparser.java

import java.io.IOException;
import java.util.*;
import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;
public class exp5saxparser extends DefaultHandler
{
ArrayList myUsers;
private String tempVal;
private User tempUser;
public exp5saxparser(){
myUsers=new ArrayList();
}
public void runExample()
{
parseDocument();
printData();
}
private void parseDocument()
{
SAXParserFactory sf=SAXParserFactory.newInstance();
Try
{
SAXParser sp=sf.newSAXParser();
sp.parse("saxusers.xml",this);
}
catch(SAXException se)
{
se.printStackTrace();
}
catch(ParserConfigurationException pce)
{
pce.printStackTrace();
}
catch(IOException ie)
{
ie.printStackTrace();
}
}
private void printData()
{
Iterator itr=myUsers.iterator();
System.out.println("No of Users:"+myUsers.size());
Scanner in=new Scanner(System.in);
System.out.println("Enter User ID:");
int n=in.nextInt();
int flag=0;
while(itr.hasNext())
{
User st=(User)itr.next();
if(st.id==n)
{
System.out.println("ID " +" Name "+"gender "+" Address");
System.out.println(st.id+" "+st.name+" "+st.type+" "+st.address);
flag=1;
break;
}
else
flag=0;
}
if(flag==0)
System.out.println("User Id Not Exist, Try Again");
}
public void startElement(String uri,String localName,String qName,Attributes attributes)throws
SAXException
{
tempVal="";
if(qName.equalsIgnoreCase("User"))
{
tempUser=new User();
tempUser.setType(attributes.getValue("type"));
}
}
public void characters(char[] ch,int start,int length)throws SAXException
{
tempVal=new String(ch,start,length);
}
public void endElement(String uri,String localName,String qName)throws SAXException
{
if(qName.equalsIgnoreCase("User"))
{
myUsers.add(tempUser);
}
else if(qName.equalsIgnoreCase("Name"))
{
tempUser.setName(tempVal);
}
else if(qName.equalsIgnoreCase("Id"))
{
tempUser.setId(Integer.parseInt(tempVal));
}
else if(qName.equalsIgnoreCase("Address"))
{
tempUser.setAddress(tempVal);
}
}
public static void main(String[] args)
{
exp5saxparser usp=new exp5saxparser();
usp.runExample();
}

OUT PUT:

Enter User ID:


1116
ID Name Gender Address
1116 Angana Female Gdwl

Enter User ID:


1130
User Id Not Exist, Try Again!
PHP Programming

i) A user validation web application, where the user submits the login name and password to the
server. The name and password are checked against the data already available in Data base and if the
data matches, a successful login page is returned. Otherwise a failure message is shown to the user.

login.html

<html>
<body>
<form action="valid.php" method="post">
User ID: <input type="text" name="uname"><br><br>
Password:<input type="text" name="pwd"><br><br>
<input type="submit" ><br>
</form>
</body>
</html>

valid.php

<?php
$conn=mysqli_connect("localhost","root","","jpnce") or die("connection failed");
//get the posted values
$uname=$_POST['uname'];
$pwd=$_POST['pwd'];
//now validating the username and password
$sql="SELECT * FROM user WHERE uname='$uname' and pwd='$pwd'";
$result=mysqli_query($conn,$sql);
if(mysqli_num_rows($result)>0)
{
echo "Login Successfull";
}
else
echo "Invalid username or password";
mysqli_close($conn);
?>
OUTPUT:
ii) Modify the above program to use an XML file instead of database

login.html

<html>
<form action="loginxml.php" method="post">
Username<input type="text" name="uname"><br>
Password<input type="password" name="pwd">
<input type="submit" >
</form>
</html>

users.xml

<?xml version="1.0" ?>


<login>
<user>
<name>jpnce</name>
<pwd>cse</pwd>
</user>
<user>
<name>system</name>
<pwd>manager</pwd>
</user>
</login>

loginxml.php

<?php
$uname=$_POST['uname'];
$pwd=$_POST['pwd'];
$xml=simplexml_load_file("users.xml") or die("Error: Cannot create object");
$count=0;
foreach($xml->children() as $users)
{
if($users->name==$uname&&$users->pwd==$pwd)
{
$count++;
}
}
if($count>0)
echo "login successfull";
else
echo "invalid username or password";
?>
OUTPUT:
iii) Modify the above program to use AJAX to show the result on the same page below the submit
button
loginajax.html

<html>
<head>
<script language="javascript">
function loadDoc()
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
if (xhttp.readyState == 4 && xhttp.status == 200)
{
document.getElementById("demo").innerHTML =
xhttp.responseText;
}
};
var uname=document.f1.uname.value;
var pwd=document.f1.pwd.value;
var url= 'getuser.php?uname=' + uname + '&pwd=' +pwd;
xhttp.open("GET",url, true);
xhttp.send();
}
</script>
</head>
<body>
<form name="f1">
User ID: <input type="text" name="uname"><br><br>
Password:<input type="text" name="pwd"><br><br>
<button type="button" onclick="loadDoc()">Submit</button><br>
<p id="demo"><h2></h2></p>
</form>
</body>
</html>
getuser.php

<?php
$conn=mysqli_connect("localhost","root","","jpnce") or die("connection failed");
//get the posted values
$uname=$_REQUEST["uname"];
$pwd=$_REQUEST["pwd"];
//now validating the username and password
$sql="SELECT uname, pwd FROM user WHERE uname='$uname' and pwd='$pwd'";
$result=mysqli_query($conn,$sql);
if(mysqli_num_rows($result)>0)
{
echo "Login Successfull";
}
else
echo "Invalid username or password";
mysqli_close($conn);
?>

OUTPUT:
iv) A simple calculator web application that takes two numbers and an operator (+,-,/,* and %) from an
HTML page and returns the result page with the operation performed on the operands.

calc.html

<html>
<head><title>Simple Calculator using PHP</title></head>
<body>
<form action="calcphp.php" method="post">
<h4>Enter your Values</h4>
Num1: <input type="text" name="num1">&nbsp Num2:<input type="text"
name="num2"><br><br>
Select Operator<input type="radio" name="opr" value="+" checked>+&nbsp
<input type="radio" name="opr" value="-">-&nbsp
<input type="radio" name="opr" value="*">*&nbsp
<input type="radio" name="opr" value="/">/&nbsp
<input type="radio" name="opr" value="%">%<br><br>
<input type="Submit" value="calculate">
</form>
</body>
</html>
calcphp.php

<?php
$a=$_POST['num1'];
$b=$_POST['num2'];
$c=$_POST['opr'];
if($a!=""&&$b!=""&$c!="")
{
switch($c)
{
case '+':$d=$a+$b;
break;
case '-':$d=$a-$b;
break;
case '*':$d=$a*$b;
break;
case '/':$d=$a/$b;
break;
case '%':$d=$a%$b;
break;
}
echo "the result is $d ";
}
else
echo "Please Enter valid input";
?>

OUTPUT:
v) Modify the above program such that it stores each query in a database and checks the database first
for the result. If the query is already available in the DB, it returns the value that was previously
computed (from DB) or it computes the result and returns it after storing the new query and result in
DB
calc.html

<html>
<head><title>Simple Calculator using PHP</title></head>
<body>
<form action="db_calc.php" method="post">
<h4>Enter your Values</h4>
<br>Num1:<input type="text" name="num1">&nbspNum2:<input type="text"
name="num2"><br><br>
Select Operator<input type="radio" name="opr" value="+" checked>+&nbsp
<input type="radio" name="opr" value="-">-&nbsp
<input type="radio" name="opr" value="*">*&nbsp
<input type="radio" name="opr" value="/">/&nbsp
<input type="radio" name="opr" value="%">%<br><br>
<input type="Submit" value="calculate">
</form>
</body>
</html>
db_calc.php

<?php
$hn="localhost";
$un="root";
$pwd="";
$db="akhi";
$conn=mysqli_connect("$hn","$un","$pwd","$db") or die("Connection Failed");
$a=$_POST['num1'];
$b=$_POST['num2'];
$c=$_POST['opr'];
$sql="select * from calcdb where n1='$a' and n2='$b'and opr='$c';";
$result=mysqli_query($conn,$sql);
$rc=mysqli_num_rows($result);
if($rc>0)
{
while($list=mysqli_fetch_assoc($result))
echo "The result is".$list['result']." already exists in db";
}
else
{
switch($c)
{
case '+':$d=$a+$b;
break;
case '-':$d=$a-$b;
break;
case '*':$d=$a*$b;
break;
case '/':$d=$a/$b;
break;
case '%':$d=$a%$b;
break;
}
$sql="insert into calcdb values('$a','$b','$c','$d');";
mysqli_query($conn,$sql);
$rc=mysqli_affected_rows($conn);
if($rc>0)
echo "Result Not Exists in DB, So the result is $d stored in to database";
}
mysqli_close($conn);
?>
OUT PUT:
vi) A web application takes a name as input and on submit it shows a hello <name> page where
<name> is taken from the request. It shows the start time at the right top corner of the page and
provides a logout button. On clicking this button, it should show a logout page with Thank You
<name> message with the duration of usage(hint: Use session to store name and time)

login.html

<html>
<form action="ref.php" method="post">
Username:<input type="text" name="uname">
<p align="center"><input type="Submit">
</form>
</html>

ref.php

<?php
session_start();
$_SESSION["user"]=$_POST['uname'];
$_SESSION['start']=time();
echo '<p align=center>';
echo "Hello ".$_SESSION["user"]."<br></p>";
echo '<p align=right>';
echo date(' H:i:s ',time())."</p>";
echo "<a href='logout.php'>Logout</a>";
?>

logout.php

<?php
session_start();
$_SESSION["timeused"] = time() - $_SESSION["start"];
$t=$_SESSION["timeused"];
$h=intval($t/3600);
$t=$t-($h*3600);
$m=intval($t/60);
$t=$t-($m*60);
$s=$t;
echo $_SESSION["user"] ."logged Out Successfully<br>";
//echo "Your access time is " . $_SESSION["timeused"] . " seconds.";
echo "Duration of Usage is".$h.":".$m.":".$s;
?>
OUT PUT:
vii) A web application that takes name and age from an HTML page. If the age is less than 18, it
should send a page with “Hello <name>, you are not authorized to visit this site” message, where
<name> should be replaced with the entered name. Otherwise it should send “Welcome <name> to
this site” message

user.html

<html>
<head>
<title>PHP Age Validation</title>
</head>
<body>
<form action="user.php" method="POST">
Name :<input type="text" name="name"><br>
Age :<input type="text" name="age"><p><font color="red" size=2>*Age must be
numeric</font><p>
<input type="submit" value="Submit">
<input type="reset">
</body>
</html>
user.php

<?php
$name=$_POST['name'];
$age=$_POST['age'];
if($age<18)
echo"<font color='red'>Hello! $name, you are not authorized to visit this site";
else
echo"<font color='green'>Welcome $name, to this site";
?>
OUT PUT:
viii) The user is first served a login page which takes user’s name and password. After submitting the
details the server checks these values against the data from a database and takes the following
decisions. If name and password matches, serves a welcome page with user’s full name. If name
matches and password doesn’t match, then serves “password mismatch” page. If name is not found in
the database, serves a registration page, where user’s full name is asked and on submitting the full
name, it stores, the login name, password and full name in the data base(hint: Use session for storing
the submitted login name and password)

login.html

<html>
<form action="valid.php" method="post">
Username<input type="text" name="uname"><br>
Password<input type="password" name="pwd">
<input type="submit" ><input type="reset" >
</form>
</html>

valid.php

<?php
session_start();
$conn=mysqli_connect("localhost","root","","jpnce") or die("connection failed");
//get the posted values
$uname=$_POST['uname'];
$pwd=$_POST['pwd'];
$_SESSION['uname']=$uname;
$_SESSION['pwd']=$pwd;
//now validating the username and password
$sql="SELECT * FROM users WHERE uname='$uname';";
$result=mysqli_query($conn,$sql);
$rc=mysqli_num_rows($result);
if($rc>0)
{
while($list=mysqli_fetch_assoc($result))
if($list['pwd']==$pwd)
echo "Welcome ".$list['fname'];
else
echo "Password Mismatch";
}
else
{
header("Location:reg.html");
}
mysqli_close($conn);
?>
reg.html

<html>
<form action="reg.php" method="post">
Enter Full Name<input type="text" name="fname"><br>
<input type="submit" ><input type="reset" >
</form>
</html>
reg.php

<?php
session_start();
$conn=mysqli_connect("localhost","root","","jpnce") or die("connection failed");
//get the posted values
$fname=$_POST['fname'];
$uname=$_SESSION['uname'];
$pwd=$_SESSION['pwd'];
$sql="insert into users values('$uname','$pwd','$fname');";
mysqli_query($conn,$sql);
$rc=mysqli_affected_rows($conn);
if($rc>0)
echo "User Registered Successfully";
else
echo "Registration failed".mysqli_error($conn);
mysqli_close($conn);
?>
OUT PUT:
ix) A web application that lists all cookies stored in the browser on clicking “List Cookies” button.
Add cookies if necessary.

setcookies.php

<?php
setcookie("cse","WK",time()+86400);
setcookie("ece","SAM",time()+86400);
setcookie("eee","SPARK",time()+86400);
setcookie("civil","NIRMAN",time()+86400);
echo "Cookies set Successfully";
?>

listcookie.php

<?php
if(count($_COOKIE)>0)
{
echo "List of cookies are<br>";
foreach($_COOKIE as $k=>$v)
echo $k."->".$v."<br>";
}
else
echo "COOKIES are not exists";
?>
OUT PUT:
Servlets Programming

i) A user validation web application, where the user submits the login name and password to the
server. The name and password are checked against the data already available in Data base and if the
data matches, a successful login page is returned. Otherwise a failure message is shown to the user.

Creating table in Oracle


SQL> create table users(uname varchar(20),pwd varchar(12));
Table created.
SQL> insert into users values('jpnce','cse1');
1 row created.
SQL> insert into users values('jpnce','cse');
1 row created.
SQL> select * from users;

UNAME PWD
---------- ----------
jpnce cse
jpnce cse1

loginserv.html

<html>
<center>
<body>
<form action="./login" method="get">
User ID:<input type="text" name="uname"><br><br>
Password:<input type="password" name="pwd"><br><br>
<input type="submit">
</form>
</body>
</center>
</html>

log.java

import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class log extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response)throws
IOException,ServletException
{
process(request,response);
}
public void doPost(HttpServletRequest request,HttpServletResponse response)throws
IOException,ServletException
{
process(request,response);
}
public void process(HttpServletRequest request,HttpServletResponse response)throws
IOException,ServletException
{
try
{
String uname=request.getParameter("uname");
String pd=request.getParameter("pwd");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:jpnce","system","jpnce");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from users where uname='"+uname+"' and
pwd='"+pd+"'");
response.setContentType("text/html");
PrintWriter out=response.getWriter();
if(rs.next())
out.println("login successfull");
else
out.println("invalid username or password");
}
catch(Exception e)
{
System.out.println(e);
}
}
}
web.xml

<web-app>
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>log</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>

OUT PUT:
ii) Modify the above program to use an XML file instead of database
xmllogserv.html

<html>
<center>
<body>
<form action="./xmllogin" method="get">
User ID:<input type="text" name="uname"><br><br>
Password:<input type="password" name="pwd"><br><br>
<input type="submit">
</form>
</body>
</center>
</html>

logxml.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class logxml extends HttpServlet
{
String u,p;
public void init(ServletConfig config)throws ServletException
{
u=config.getInitParameter("uname");
p=config.getInitParameter("pwd");}
public void doGet(HttpServletRequest request,HttpServletResponse response)throws
IOException,ServletException
{
String uname=request.getParameter("uname");
String pd=request.getParameter("pwd");
response.setContentType("text/html");
PrintWriter out=response.getWriter();
if(u.equals(uname)&&p.equals(pd))
out.println("login successfull");
else
out.println("invalid username or password");
}
}
}

web.xml

<web-app>
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>logxml</servlet-class>
<init-param>
<param-name>uname</param-name>
<param-value>jpnce</param-value>
</init-param>
<init-param>
<param-name>pwd</param-name>
<param-value>1234</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/xmllogin</url-pattern>
</servlet-mapping>
</web-app>

OUT PUT:
iii) Modify the above program to use AJAX to show the result on the same page below the submit
button
logajax.html

<html>
<center>
<head>
<script language="javascript">
function loaddoc()
{
var xhttp=new XMLHttpRequest();
xhttp.onreadystatechange=function()
{
if(xhttp.readyState==4 && xhttp.status==200)
document.getElementById("demo").innerHTML=xhttp.responseText;
};
var name=document.f1.uname.value;
var pwd=document.f1.pwd.value;
var url='./login?uname='+name+ '&pwd='+pwd;
xhttp.open("GET",url,true);
xhttp.send();
}
</script>
</head>
<body>
<form name="f1">
UserName<input type="text" name="uname"><br><br>
Password<input type="password" name="pwd"><br><br>
<button type="button" onClick="loaddoc()">submit</button>
<p id="demo"></p>
</form>
</body>
</center>
</html>

log.java

import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class log extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response)throws
IOException,ServletException
{
process(request,response);
}
public void doPost(HttpServletRequest request,HttpServletResponse response)throws
IOException,ServletException
{
process(request,response);
}
public void process(HttpServletRequest request,HttpServletResponse response)throws
IOException,ServletException
{
try
{
String uname=request.getParameter("uname");
String pd=request.getParameter("pwd");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection
con=DriverManager.getConnection("jdbc:odbc:jpnce","system","jpnce");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from users1 where uname='"+uname+"'
and pwd='"+pd+"'");
response.setContentType("text/html");
PrintWriter out=response.getWriter();
if(rs.next())
out.println("login successfull");
else
out.println("invalid username or password");
}
catch(Exception e)
{
System.out.println(e);
}
}
}

web.xml

<web-app>
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>log</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>
OUTPUT:
iv. A simple calculator web application that takes two numbers and an operator (+,-,/,* and %) from an
HTML page and returns the result page with the operation performed on the operands.

servcalc.html

<html>
<head>
<title>Simple calculator using Servlets</title>
</head>
<body>
<form method="get" action="./compute">
<h1>Enter Values</h1>
Number 1 : <input type="text" name="t1"> <br><br>
Number 2 : <input type="text" name="t2"> <br><br>
Select an operator :
<input type="radio" name="op" value="+" checked>+&nbsp
<input type="radio" name="op" value="-" >-&nbsp
<input type="radio" name="op" value="*">*&nbsp
<input type="radio" name="op" value="/" >/&nbsp
<input type="radio" name="op" value="%">%&nbsp
<br><br>
<input type="submit" >&nbsp <input type="Reset" >
</form>
</body>
</html>
calc.java

import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class calc extends HttpServlet
{
protected void doGet(HttpServletRequest req,HttpServletResponse res)throws
ServletException,IOException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
String num1=req.getParameter("t1");
String num2=req.getParameter("t2");
String opr=req.getParameter("op");
int n1=Integer.parseInt(num1);
int n2=Integer.parseInt(num2);
int result=0;
if(opr.equals("+"))
result=n1+n2;
if(opr.equals("-"))
result=n1-n2;
if(opr.equals("/"))
result=n1/n2;
if(opr.equals("*"))
result=n1*n2;
if(opr.equals("%"))
result=n1%n2;
out.println("Result is "+result);
}
}

OUTPUT:
v. Modify the above program such that it stores each query in a database and checks the database first
for the result. If the query is already available in the DB, it returns the value that was previously
computed(from DB) or it computes the result and returns it after storing the new query and result in
DB.
servcaldb.html

<html>
<head>
<title>Simple calculator using JSP</title>
</head>
<body>
<form method="get" action="./dbcal">
<h1>Enter Values</h1>
Number 1 : <input type="text" name="t1"> <br><br>
Number 2 : <input type="text" name="t2"> <br><br>
Select an operator :
<input type="radio" name="op" value="+" checked>+&nbsp
<input type="radio" name="op" value="-" >-&nbsp
<input type="radio" name="op" value="*">*&nbsp
<input type="radio" name="op" value="/" >/&nbsp
<input type="radio" name="op" value="%">%&nbsp
<br><br>
<input type="submit" >&nbsp <input type="Reset" >
</form>
</body>
</html>

cdb.java

import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class cdb extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response)throws
IOException,ServletException
{
process(request,response);
}
public void doPost(HttpServletRequest request,HttpServletResponse response)throws
IOException,ServletException
{
process(request,response);
}
public void process(HttpServletRequest request,HttpServletResponse response)throws
IOException,ServletException
{
try
{
int a,b;
String opr;
a=Integer.parseInt(request.getParameter("t1"));
b=Integer.parseInt(request.getParameter("t2"));
opr=request.getParameter("op");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:jpnce","system","jpnce");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from calc where n1='"+a+"' and n2='"+b+"' and
op='"+opr+"'");
response.setContentType("text/html");
PrintWriter out=response.getWriter();
if(rs.next())
{
out.println("operation alredy exist in the database");
out.println("Result is:"+rs.getString(4));
}
else
{
out.println("Result not Exists in DB");
int res=0;
if(opr.equals("+"))
res=a+b;
if(opr.equals("-"))
res=a-b;
if(opr.equals("*"))
res=a*b;
if(opr.equals("/"))
res=a/b;
if(opr.equals("%"))
res=a%b;
int x=st.executeUpdate("insert into calc
values('"+a+"','"+b+"','"+opr+"','"+res+"')");
if(x>0)
out.println(" Result is "+res+" Stored into DB");
else
out.println("error in insertion");
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}

web.xml

<web-app>
<servlet>
<servlet-name>abcd</servlet-name>
<servlet-class>cdb</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>abcd</servlet-name>
<url-pattern>/dbcal</url-pattern>
</servlet-mapping>
</web-app>

OUTPUT:
vi. A web application takes a name as input and on submit it shows a hello <name> page where
<name> is taken from the request. It shows the start time at the right top corner of the page and
provides a logout button. On clicking this button, it should show a logout page with Thank You
<name> message with the duration of usage(hint: Use session to store name and time)

loginses.html

<html>
<body>
<form action="getinf" method="get">
Enter Name<input type="text" name="name"><br><br>
<input type="submit">
</form>
</body>
</html>

getdetails.java

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class getdetails extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response)throws
ServletException,IOException
{
HttpSession session;
session=request.getSession(true);
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.println("<form action=logout method=get>");
String uname=request.getParameter("name");
out.println("<p align=center>");
out.println("Welcome "+uname+"</p>");
Date d=new Date();
int h=d.getHours();
int m=d.getMinutes();
int s=d.getSeconds();
out.println("<p align=right>Time:"+h+":"+m+":"+s+"</p>");
session.setAttribute("uname",uname);
session.setAttribute("time",d.getTime());
out.println("<input type=Submit value=Logout></form>");
}
}

logout.java

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class logout extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response)throws
ServletException,IOException
{
HttpSession session=request.getSession(true);
response.setContentType("text/html");
PrintWriter out=response.getWriter();
String uname=(String)session.getAttribute("uname");
Long t1=(Long)session.getAttribute("time");
Date d2=new Date();
Long t2=d2.getTime();
out.println("<center>Thank You "+uname );
out.println("<br><br>Duration of Usage is:"+(t2-t1)/(60*60)+"Seconds</center>");
session.invalidate();
}
}

web.xml

<web-app>
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>getdetails</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/getinf</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>abcd</servlet-name>
<servlet-class>logout</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>abcd</servlet-name>
<url-pattern>/logout</url-pattern>
</servlet-mapping>
</web-app>
OUTPUT:
vii. A web application that takes name and age from an HTML page.vIf the age is less than 18, it
should send a page with “Hello <name>, you are not authorized to visit this site” message, where
<name> should be replaced with the entered name. Otherwise it should send “Welcome <name> to
this site” message.

serage.html

<html>
<head>
<title>Servlet Age Validation</title>
</head>
<body>
<form action="ageval" method="get">
Name :<input type="text" name="cname"><br><br>
Age :<input type="text" name="age"><p><font color="red" size=2>*Age must
be numeric</font><p>
<input type="submit" >&nbsp&nbsp
<input type="reset">
</form>
</body>
</html>

checkage.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class checkage extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response)throws
IOException,ServletException
{
response.setContentType("text/html");
PrintWriter out=response.getWriter();
String name=request.getParameter("cname");
int age=Integer.parseInt(request.getParameter("age"));
if(age<=18)
out.println("<font color='red'>Hello "+name+",You are not authorized to visit
this site</font>");
else
out.println("<font color='green'>Welcome "+name+", to this site</font>");
}
}

web.xml

<web-app>
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>checkage</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/ageval</url-pattern>
</servlet-mapping>
</web-app>

OUTPUT:
viii. A web application for implementation. The user is first served a login page which takes user’s
name and password. After submitting the details the server checks these values against the data from a
database and takes the following decisions. If name and password matches, serves a welcome page
with user’s full name. If name matches and password doesn’t match, then serves “password mismatch”
page. If name is not found in the database, serves a registration page, where user’s full name is asked
and on submitting the full name, it stores, the login name, password and full name in the data
base(hint: Use session for storing the submitted login name and password).

login.html

<html>
<center><body>
<form action="./reglog" method="get">
UserName:<input type="text" name="uname"><br><br>
Password:<input type="password" name="pwd"><br><br>
<input type="submit"><input type="submit">
</form>
</body></center>
</html>
logreg.java

import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class logreg extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response)throws
IOException,ServletException
{
HttpSession session;
session=request.getSession(true);
try
{
String uname=request.getParameter("uname");
String pd=request.getParameter("pwd");
session.setAttribute("uname",uname);
session.setAttribute("pwd",pd);
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection
con=DriverManager.getConnection("jdbc:odbc:jpnce","system","jpnce");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from login where uname='"+uname+"'");
response.setContentType("text/html");
PrintWriter out=response.getWriter();
if(rs.next())
{
String pw=rs.getString(2);
String fname=rs.getString(3);
if(pw.equals(pd))
out.println("login successfull, Welcome "+fname);
else
out.println("Password Missmatch");
}
else
{
out.println("<h1>User does not exists,</h1><a href=reg.html>click here
to register</a>");
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
reg.html

<html>
<body>
<form action="./register" method="get">
Enter Full Name<input type="text" name="fname">
<input type="submit">
</form>
</body>
</html>

regi.java

import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class regi extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response)throws
IOException,ServletException
{
HttpSession session;
session=request.getSession(true);
try
{
response.setContentType("text/html");
PrintWriter out=response.getWriter();
String fname=request.getParameter("fname");
String user=(String)session.getAttribute("uname");
String pw=(String)session.getAttribute("pwd");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection
con=DriverManager.getConnection("jdbc:odbc:jpnce","system","jpnce");
Statement st=con.createStatement();
int x=st.executeUpdate("insert into login
values('"+user+"','"+pw+"','"+fname+"')");
if(x>0)
{
out.println("User Registered Successfully");
}
else
out.println("Invalid Data");
}
catch(Exception e)
{
System.out.println(e);
}
}
}
web.xml

<web-app>
<servlet>
<servlet-name>abcde</servlet-name>
<servlet-class>logreg</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>abcde</servlet-name>
<url-pattern>/reglog</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>abcdf</servlet-name>
<servlet-class>regi</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>abcdf</servlet-name>
<url-pattern>/register</url-pattern>
</servlet-mapping>
</web-app>

OUTPUT:
ix. A web application that lists all cookies stored in the browser on clicking “List Cookies” button.
Add cookies if necessary.

addcookies.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class addcookies extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response)throws
IOException,ServletException
{
response.setContentType("text/html");
PrintWriter out=response.getWriter();
Cookie c1=new Cookie("jpnce","drmpr");
Cookie c2=new Cookie("jpnes","mbnr");
Cookie c3=new Cookie("jntuh","hyd");
response.addCookie(c1);
response.addCookie(c2);
response.addCookie(c3);
c1.setMaxAge(60*60);
c2.setMaxAge(60*60);
c3.setMaxAge(60*60);
out.println("Cookies Set Successfully");
out.println("<form method=get action=./listcook><br>");
out.println("<input type=submit value=Listcookies></form>");
}
}
listcookies.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class listcookies extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response)throws
IOException,ServletException
{
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.println("<h1>List of Cookies are</h1>");
Cookie[] cookies=request.getCookies();
for(int i=0;i<cookies.length;i++)
{
out.println(cookies[i].getName()+"=>"+cookies[i].getValue()+"<br>");
}
}
}

web.xml

<web-app>
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>addcookies</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/addcookies</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>abcd</servlet-name>
<servlet-class>listcookies</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>abcd</servlet-name>
<url-pattern>/listcook</url-pattern>
</servlet-mapping>
</web-app>
OUTPUT:
JSP Programming
i) A user validation web application, where the user submits the login name and password to the
server. The name and password are checked against the data already available in Data base and if the
data matches, a successful login page is returned. Otherwise a failure message is shown to the user.

loginjsp.html

<html>
<center><body>
<form action="log.jsp" method="get">
User ID:<input type="text" name="uname"><br><br>
Password:<input type="password" name="pwd"><br><br>
<input type="submit">
</form>
</body></center>
</html>

log.jsp

<%@page import="java.sql.*" import="java.io.*"%>


<%
String uname=request.getParameter("uname");
String pd=request.getParameter("pwd");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:jpnce","system","jpnce");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from users where uname='"+uname+"' and
pwd='"+pd+"'");
if(rs.next())
out.println("login successfull");
else
out.println("invalid username or password");
con.close();
%>
OUTPUT:
ii. Modify the above program to use an XML file instead of database

loginjsp.html

<html>
<center><body>
<form action="loginxml.jsp" method="get">
UserName:<input type="text" name="uname"><br><br>
Password:<input type="password" name="pwd"><br><br>
<input type="submit">
</form>
</body></center>
</html>

loginxml.jsp

<%
String uname=request.getParameter("uname");
String pd=request.getParameter("pwd");
String u=config.getInitParameter("uname");
String p=config.getInitParameter("pwd");
if(u.equals(uname)&&p.equals(pd))
out.println("login successfull");
else
out.println("invalid username or password");
%>
web.xml

<web-app>
<servlet>
<servlet-name>abc</servlet-name>
<jsp-file>/loginxml.jsp</jsp-file>
<init-param>
<param-name>uname</param-name>
<param-value>jpnce</param-value>
</init-param>
<init-param>
<param-name>pwd</param-name>
<param-value>1234</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/loginxml.jsp</url-pattern>
</servlet-mapping>
</web-app>
OUTPUT:
iii. Modify the above program to use AJAX to show the result on the same page below the submit
button

loginajax.html

<html>
<center>
<head>
<script language="javascript">
function loaddoc()
{
var xhttp=new XMLHttpRequest();
xhttp.onreadystatechange=function()
{
if(xhttp.readyState==4 && xhttp.status==200)
document.getElementById("demo").innerHTML=xhttp.re
sponseText;
};
var name=document.f1.uname.value;
var pwd=document.f1.pwd.value;
var url='log.jsp?uname='+name+ '&pwd='+pwd;
xhttp.open("GET",url,true);
xhttp.send();
}
</script>
</head>
<body>
<form name="f1">
UserName<input type="text" name="uname"><br><br>
Password<input type="password" name="pwd"><br><br>
<button type="button" onClick="loaddoc()">submit</button>
<p id="demo"></p>
</form>
</body></center>
</html>

log.jsp

<%@page import="java.sql.*" import="java.io.*"%>


<%
String uname=request.getParameter("uname");
String pd=request.getParameter("pwd");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:jpnce","system","jpnce");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from users1 where uname='"+uname+"' and
pwd='"+pd+"'");
if(rs.next())
out.println("login successfull");
else
out.println("invalid username or password");
con.close();
%>
OUTPUT:
iv. A simple calculator web application that takes two numbers and an operator (+,-,/,* and %) from an
HTML page and returns the result page with the operation performed on the operands.

calcjsp.html

<html>
<head>
<title>Simple calculator using JSP</title>
</head>
<body>
<form method="get" action="cal.jsp">
<h1>Enter Values</h1>
Number 1 : <input type="text" name="t1"> <br><br>
Number 2 : <input type="text" name="t2"> <br><br>
Select an operator :
<input type="radio" name="op" value="+" checked>+&nbsp
<input type="radio" name="op" value="-" >-&nbsp
<input type="radio" name="op" value="*">*&nbsp
<input type="radio" name="op" value="/" >/&nbsp
<input type="radio" name="op" value="%">%&nbsp
<br><br>
<input type="submit" >&nbsp <input type="Reset" >
</form>
</body>
</html>
cal.jsp
<%
String num1=request.getParameter("t1");
String num2=request.getParameter("t2");
String opr=request.getParameter("op");
int n1=Integer.parseInt(num1);
int n2=Integer.parseInt(num2);
int result=0;
if(opr.equals("+"))
result=n1+n2;
if(opr.equals("-"))
result=n1-n2;
if(opr.equals("/"))
result=n1/n2;
if(opr.equals("*"))
result=n1*n2;
if(opr.equals("%"))
result=n1%n2;
out.println("Result is "+result);
%>
OUTPUT:
V. Modify the above program such that it stores each query in a database and checks the database first
for the result. If the query is already available in the DB, it returns the value that was previously
computed(from DB) or it computes the result and returns it after storing the new query and result in
DB.

calcdbjsp.html

<html>
<head>
<title>Simple calculator using JSP</title>
</head>
<body>
<form method="get" action="calcdb.jsp">
<h1>Enter Values</h1>
Number 1 : <input type="text" name="t1"> <br><br>
Number 2 : <input type="text" name="t2"> <br><br>
Select an operator :
<input type="radio" name="op" value="+" checked>+&nbsp
<input type="radio" name="op" value="-" >-&nbsp
<input type="radio" name="op" value="*">*&nbsp
<input type="radio" name="op" value="/" >/&nbsp
<input type="radio" name="op" value="%">%&nbsp
<br><br>
<input type="submit" >&nbsp <input type="Reset" >
</form>
</body>
</html>

calcdb.jsp

<%@page import="java.sql.*" import="java.io.*"%>


<%
int a,b;
String opr;
a=Integer.parseInt(request.getParameter("t1"));
b=Integer.parseInt(request.getParameter("t2"));
opr=request.getParameter("op");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:jpnce","system","jpnce");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from calc where n1='"+a+"' and n2='"+b+"' and
op='"+opr+"'");
if(rs.next())
{
out.println("operation alredy exist in the database");
out.println("Result is:"+rs.getString(4));
}
else
{
int res=0;
if(opr.equals("+"))
res=a+b;
if(opr.equals("-"))
res=a-b;
if(opr.equals("*"))
res=a*b;
if(opr.equals("%"))
res=a%b;
int x=st.executeUpdate("insert into calc values('"+a+"','"+b+"','"+opr+"','"+res+"')");
if(x>0)
out.println("Result Not exists in the db i.e:="+res);
else
out.println("error in insertion");
}
%>
OUTPUT:
vi. A web application takes a name as input and on submit it shows a hello <name> page where
<name> is taken from the request. It shows the start time at the right top corner of the page and
provides a logout button. On clicking this button, it should show a logout page with Thank You
<name> message with the duration of usage(hint: Use session to store name and time)

loginses.html

<html>
<body>
<form action="getdet.jsp" method="get">
Enter Name<input type="text" name="name">
<input type="submit">
</form>
</body>
</html>
getdet.jsp

<%@page import="java.util.*"%>
<form action="logout.jsp" method="get">
<%
String uname=request.getParameter("name");
session.setAttribute("uname",uname);%>
<p align="center">
<%
out.println("Welcome "+uname);
%>
</p><p align="right">Time:
<%Date d=new Date();
int h=d.getHours();
int m=d.getMinutes();
int s=d.getSeconds();
out.println(h+":"+m+":"+s);
%>
<%
session.setAttribute("time",d.getTime());
%>
</p><input type="Submit" value="Logout" >
%>
</form>

logout.html

<center>
<%@page import="java.util.*"%>
<%
String uname=(String)session.getAttribute("uname");
out.println("Thank You "+uname );
Long t1=(Long)session.getAttribute("time");
Date d2=new Date();
Long t2=d2.getTime();
%>
<br><br>
Duration of Usage is: <%=(t2-t1)/(60*60)%> Seconds
<%
session.invalidate();
%>
</center>
OUTPUT:
vii. A web application that takes name and age from an HTML page.vIf the age is less than 18, it
should send a page with “Hello <name>, you are not authorized to visit this site” message, where
<name> should be replaced with the entered name. Otherwise it should send “Welcome <name> to
this site” message.

userjsp.html

<html>
<head>
<title>JSP Age Validation</title>
</head>
<body>
<form action="check.jsp" method="get">
Name :<input type="text" name="cname"><br><br>
Age :<input type="text" name="age"><p><font color="red" size=2>*Age must
be numeric</font><p>
<input type="submit" >&nbsp&nbsp
<input type="reset">
</form>
</body>
</html>

check.jsp

<%
String name=request.getParameter("cname");
int age=Integer.parseInt(request.getParameter("age"));
if(age<=18)
out.println("<font color='red'>Hello "+name+",You are not authorized to visit this
site</font>");
else
out.println("<font color='green'>Welcome "+name+", to this site</font>");
%>
OUTPUT:
viii. A web application for implementation. The user is first served a login page which takes user’s
name and password. After submitting the details the server checks these values against the data from a
database and takes the following decisions. If name and password matches, serves a welcome page
with user’s full name. If name matches and password doesn’t match, then serves “password mismatch”
page. If name is not found in the database, serves a registration page, where user’s full name is asked
and on submitting the full name, it stores, the login name, password and full name in the data
base(hint: Use session for storing the submitted login name and password).

loginjsp.html

<html>
<center><body>
<form action="login.jsp" method="get">
UserName:<input type="text" name="uname"><br><br>
Password:<input type="password" name="pwd"><br><br>
<input type="submit"><input type="submit">
</form>
</body></center>
</html>

login.jsp

<%@page import="java.sql.*" import="java.io.*"%>


<%
String pw,fname;
String uname=request.getParameter("uname");
String pd=request.getParameter("pwd");
session.setAttribute("uname",uname);
session.setAttribute("pwd",pd);
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:jpnce","system","jpnce");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from login where uname='"+uname+"'");
if(rs.next())
{
pw=rs.getString(2);
fname=rs.getString(3);
if(pw.equals(pd))
out.println("login successfull, Welcome "+fname);
else
out.println("Password Missmatch");
}
else
{
out.println("User Does Not Exist");
<a href="reg.html">Click here to register</a>
<%
}
con.close();
%>
%>

reg.html

<html>
<body>
<form action="regi.jsp" method="get">
Enter Full Name<input type="text" name="fname">
<input type="submit">
</form>
</body>
</html>

regi.jsp

<%@page import="java.sql.*" import="java.io.*"%>


<%
String fname=request.getParameter("fname");
String user=(String)session.getAttribute("uname");
String pw=(String)session.getAttribute("pwd");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:jpnce","system","jpnce");
Statement st=con.createStatement();
int x=st.executeUpdate("insert into login values('"+user+"','"+pw+"','"+fname+"')");
if(x>0)
{
out.println("User Registered Successfully");
}
else
out.println("Invalid Data");
con.close();
%>
OUTPUT:
ix. A web application that lists all cookies stored in the browser on clicking “List Cookies” button.
Add cookies if necessary.

cook.jsp

<%
Cookie c1=new Cookie("jpnce","drmpr");
Cookie c2=new Cookie("jpnes","mbnr");
Cookie c3=new Cookie("jntuh","hyd");
response.addCookie(c1);
response.addCookie(c2);
response.addCookie(c3);
c1.setMaxAge(60*60);
c2.setMaxAge(60*60);
c3.setMaxAge(60*60);
out.println("Cookies Set Successfully");
%>
<form method="get" action="cook2.jsp">
<input type="submit" value="list cookies">
</form>

cook2.jsp

<h1>List of Cookies are<?h1>


<%
Cookie[] cookies=request.getCookies();
for(int i=0;i<cookies.length;i++)
{
out.println(cookies[i].getName()+"=>"+cookies[i].getValue());
%>
<br>
<%
}
%>
OUTPUT:

Das könnte Ihnen auch gefallen