100% found this document useful (1 vote)
279 views74 pages

CSE III-II SEM (Web Technologies Lab Manual)

The document provides instructions for installing the Tomcat web server and Apache web server on a local machine. It describes setting the JAVA_HOME environment variable, setting the CLASSPATH to include servlet API jars, enabling servlet reloading in Tomcat's configuration to allow reloading of changed servlets, and enabling the Invoker servlet in Tomcat's web application deployment descriptor to allow running servlets without descriptor changes. The goal is to set up the development environment for web applications using servlets and JSP.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
279 views74 pages

CSE III-II SEM (Web Technologies Lab Manual)

The document provides instructions for installing the Tomcat web server and Apache web server on a local machine. It describes setting the JAVA_HOME environment variable, setting the CLASSPATH to include servlet API jars, enabling servlet reloading in Tomcat's configuration to allow reloading of changed servlets, and enabling the Invoker servlet in Tomcat's web application deployment descriptor to allow running servlets without descriptor changes. The goal is to set up the development environment for web applications using servlets and JSP.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 74

WEB TECHNOLOGIES

LABORATORY MANUAL

B.TECH
(III YEAR – II SEM)
(2016-17)

Department of Computer Science and Engineering

MALLA REDDY COLLEGE OF


ENGINEERING & TECHNOLOGY
(Autonomous Institution – UGC, Govt. of India)
Recognized under 2(f) and 12 (B) of UGC ACT 1956
Affiliated to JNTUH, Hyderabad, Approved by AICTE - Accredited by NBA & NAAC – ‘A’ Grade - ISO 9001:2015 Certified
Maisammaguda, Dhulapally (Post Via. Hakimpet), Secunderabad – 500100, Telangana State, India
Objectives:

 To develop an ability to design and implement static and dynamic website


 Choose best technologies for solving web client/server problems
 Create conforming web pages
 Use JavaScript for dynamic effects
 To prepare PHP scripts
 Use JavaScript & PHP to validate form input entry
 Understand, analyze and create XML documents and XML Schema
 Understand, analyze and build web applications using PHP
 Use appropriate client-side or Server-side applications

Outcomes:

Upon successful completion of this course, the students will be able to:

 Design and implement dynamic websites with good aesthetic sense of designing
and latest technical know-how's
 Create web pages using HTML and Cascading Styles sheets
 Analyze a web page and identify its elements and attributes
 Create dynamic web pages using JavaScript
 Build web applications using PHP
 Create XML documents and XML Schema
 Understand, analyze and apply the role of languages like HTML, CSS, XML,
JavaScript, PHP and protocols in the workings of the web and web applications
 Have a Good grounding of Web Application Terminologies, Internet Tools,
E – Commerce and other web services
INDEX

S.No List of programs Pg.No.


Install the following on the local machine: Apache Web Server,
1 Tomcat Application Server locally, Install MySQL and install PHP 1-15
and configure it to work with Apache web server and MySQL.
Write an HTML page including any required JavaScript that takes a
2 number from one text field in the range of 0 to 999 and shows it in 16-18
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 a HTML page that has one input, which can take multi-line
3 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 19-20
entered using an alert message. Words are separated with white
spaces and lines are separated with new line character.
Write an HTML page that contains a selection box with a list of 5
4 countries. When the user selects a country, its capital should be 21-22
printed next to the list. Add CSS to customize the properties of the
font of the capital (color, bold and font size).
Create and save an XML document at the server, which contains 10
5 users information. Write a program which takes User Id as input 23-26
and returns the user details by taking the user information from the
XML document.
Implement the following web applications using (a) PHP, (b)
6. Servlets and (c) JSP.
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 Database and if 27-30
the data matches, a successful login page is returned. Otherwise a
failure message is shown to the user.

ii) Modify the above program to use an XML file instead of 31-34
database.
iii) Modify the above program using AJAX to show the result on the
same page below the submit button. 35-38

iv) A simple calculator application that takes two numbers and an


operator (+,-,*,/,%) from an HTML page and returns the result page 39-46
with the operation performed on the operands.
v) 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
the logout button. On clicking this button, it should show a logout 47-50
page with Thank You<name> message with the duration of
usage.(Use session to store name and time).

vi) 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> 51-53
should be replaced with the entered name. Otherwise it should
send “Welcome <name> to this site” message.

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 54-55
<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.

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.
56-66
If name and password matches serves a welcome page with user’s
full name.

If name 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 database
(hint: use session for storing data, submitted login name and
password).
ix) A web application that lists all cookies stored in the browser on
clicking “List Cookies” button. Add cookies if necessary. 67-70
WEB TECHNOLOGIES LAB MRCET

PROGRAM-1.1 DATE:

AIM: Install TOMCAT web server and APACHE.

While installation, we assign port number 8080 to APACHE. Make sure that these ports are
available i.e., no other process is using this port.

DESCRIPTION:

Set the JAVA_HOME Variable


You must set the JAVA_HOME environment variable to tell Tomcat where to find Java.
Failing to properly set this variable prevents Tomcat from handling JSP pages. This variable
should list the base JDK installation directory, not the bin subdirectory. On Windows XP, you
could also go to the Start menu, select Control Panel, choose System, click on the Advanced
tab, press the Environment Variables button at the bottom, and enter the JAVA_HOME
variable and value directly as:

Name: JAVA_HOME
Value: C:\jdk

Set the CLASSPATH


Since servlets and JSP are not part of the Java 2 platform, standard edition, you have to
identify the servlet classes to the compiler. The server already knows about the servlet
classes, but the compiler (i.e., javac) you use for development probably doesn't. So, if you
don't set your CLASSPATH, attempts to compile servlets, tag libraries, or other classes that
use the servlet and JSP APIs will fail with error messages about unknown classes.

Name: JAVA_HOME
Value: install_dir/common/lib/servlet-api.jar

Turn on Servlet Reloading


The next step is to tell Tomcat to check the modification dates of the class files of requested
servlets and reload ones that have changed since they were loaded into the server's
memory. This slightly degrades performance in deployment situations, so is turned off by
default. However, if you fail to turn it on for your development server, you'll have to restart the
server every time you recompile a servlet that has already been loaded into the server's
memory.

To turn on servlet reloading, edit install_dir/conf/server.xml and add a DefaultContext


subelement to the main Host element and supply true for the reloadable attribute. For
example, in Tomcat 5.0.27, search for this entry:

<Host name="localhost" debug="0" appBase="webapps" ...> and then insert the following
immediately below it:
<DefaultContext reloadable="true"/>
Be sure to make a backup copy of server.xml before making the above change.

www.mrcet.ac.in DEPARTMENT OF CSE Page 1


WEB TECHNOLOGIES LAB MRCET

Enable the Invoker Servlet


The invoker servlet lets you run servlets without first making changes to your Web
application's deployment descriptor. Instead, you just drop your servlet into WEB-INF/classes
and use the URL http://host/servlet/ServletName. The invoker servlet is extremely convenient
when you are learning and even when you are doing your initial development.

To enable the invoker servlet, uncomment the following servlet and servlet-mapping
elements in install_dir/conf/web.xml. Finally, remember to make a backup copy of the original
version of this file before you make the changes.
<servlet>
<servlet-name>invoker</servlet-name>
<servlet-class>
org.apache.catalina.servlets.InvokerServlet
</servlet-class>
...
</servlet>
...
<servlet-mapping>
<servlet-name>invoker</servlet-name>
<url-pattern>/servlet/*</url-pattern>
</servlet-mapping>

OUTPUT:

RESULT: Thus TOMCAT web server was installed successfully.

www.mrcet.ac.in DEPARTMENT OF CSE Page 2


WEB TECHNOLOGIES LAB MRCET

PROGRAM-1.2 DATE:

AIM: Access the developed static web pages for books web site, using these servers by
putting the web pages developed in week-1 and week-2 in the document root.

Output:

RESULT: These pages are accessed using the TOMCAT web server successfully.

www.mrcet.ac.in DEPARTMENT OF CSE Page 3


WEB TECHNOLOGIES LAB MRCET

PROGRAM-1.3 Install MySQL DATE:

Aim: Step-by-Step guide for Installing MySQL on Windows

You can download the MySQL database from the MySQL website http://www.mysql.com by
clicking on the downloads tab. Scroll down to the MySQL database server & standard
clients section and select the latest production release of MySQL, 5.1.35 at the time of
writing.

Installation of MySQL Server


Unzip the setup file and execute the downloaded MSI file. Follow the instructions below
exactly when installing MySQL Server:

Click on the "setup"

Perform a typical installation

www.mrcet.ac.in DEPARTMENT OF CSE Page 4


WEB TECHNOLOGIES LAB MRCET

www.mrcet.ac.in DEPARTMENT OF CSE Page 5


WEB TECHNOLOGIES LAB MRCET

Check box to configure MySQL Server

If you checked the Configure the MySQL Server now check box on the final dialog of the
MySQL Server installation, then the MySQL Server Instance Configuration Wizard will
automatically start.
Follow the instructions below carefully to configure your MySQL Server to run correctly with
Event Sentry.

Select Detailed Configuration

www.mrcet.ac.in DEPARTMENT OF CSE Page 6


WEB TECHNOLOGIES LAB MRCET

I was installing it on my local machine where other applications & tools are running I decided
to opt "developer machine" but it is recommended that you use a Dedicated MySQL Server
Machine for your MySQL database, if this is not an option then select "Server Machine".

If you selected Dedicated MySQL Server Machine and your MySQL service does not start
after the wizard completes, then try to re-run the wizard (or re-install) MySQL, but this time
select the Server Machine option.

I have checked "Multifunctional databases" as I wanted MyISAM as default storage engine


but if you want you can select "Transactional Database Only", this will make sure that
InnoDB is the main storage engine. If you have checked 3rd option then only myISAM engine
would be available

Select the drive where the database files will be stored.


Select the drive on the fastest drive(s) on your server

www.mrcet.ac.in DEPARTMENT OF CSE Page 7


WEB TECHNOLOGIES LAB MRCET

It is recommended that you leave the default port 3306 in place

It is highly recommended that you run the MySQL Server as a Windows


service(you can disable this if you want to start it manually whenever required) and include
the binary directory in the search path.

www.mrcet.ac.in DEPARTMENT OF CSE Page 8


WEB TECHNOLOGIES LAB MRCET

Specify a secure root password; you may want to check the box Enable root access from
remote machines if you plan on administering your MySQL server from your workstation or
other servers.
If you are getting an error message after clicking the Next button, then please enable
port 3306 in the Windows XP Firewall Settings

Done!!!

But if you are installing MySQL on a Windows XP workstation, or any other computer that
has a firewall enabled, and the wizard fails with an error message similar to the one shown
below (Can't connect to MySQL server on 'localhost'), then you will have to exclude the
MySQL daemon from your firewall configuration

www.mrcet.ac.in DEPARTMENT OF CSE Page 9


WEB TECHNOLOGIES LAB MRCET

On Windows XP, you can exclude MySQL from the firewall by following the steps below:
1. Navigate to Start -> Settings -> Control Panel -> Windows Firewall
2. In the resulting dialog, enter the information as shown in the screenshot

After clicking OK twice, return to the MySQL error message and select Retry. MySQL should
now be able to create the instance correctly.

www.mrcet.ac.in DEPARTMENT OF CSE Page 10


WEB TECHNOLOGIES LAB MRCET

PROGRAM-1.4 Install PHP DATE:

Aim: Install PHP and configure to work with Apache Web Server and MySQL.

Apache HTTP Server


1. Download the Apache2 HTTP server.
2. Run the installation file .msi. The installation wizard starts. Follow the instructions.
On Microsoft Vista, do not install the Apache Server to the default location, which is in
Program Files. All files in Program Files are write-protected.
3. When the installation is completed, restart the Apache server.
4. To check that the installation is successful, run the browser and enter the following
URL:
http://localhost/
The Apache welcome test page opens:

Troubleshooting
By default, the Apache server listens to port 80. This port can be already used by other
services, for example Skype. To solve the issue, change the port which the server listens to:

1. Open the Apache web server configuration file httpd.conf. By default the file is located
in C:\Program Files\Apache Software Foundation\Apache<version>\conf\
2. Locate the line Listen 80 and change the port number, for example 8080. Save the
file.
3. Restart the Apache web server.
4. To check that the web server works, run the browser and enter the URL and specify
the port number explicitly: http://localhost:8080
You can also stop the processes that possibly listen to port 80. In the Task Manager, select
the relevant file name and click End Process.

www.mrcet.ac.in DEPARTMENT OF CSE Page 11


WEB TECHNOLOGIES LAB MRCET

PHP Engine
1. Download the Windows binary installer for the PHP5 version of your choice.
Important: If there is no installer available for the version of PHP you want to install,
you have to install it manually from the .zip file. See Manual Instruction Steps in the
php.net documentation.
2. When the download is complete, run the .msi installation file. The installation wizard
starts.
3. On the Apache Configuration Directory panel, specify the directory where
the httpd.conf file is located, the default setting is C:\Program Files\Apache Software
Foundation\Apache<version>\conf\. The PHP processing will be enabled
automatically.
4. If you want to use the MySQL database server, choose the Complete installation
option or select the MySQL and MySQLi items in the Extensions list.
5. After the installation is completed, restart the Apache server.
6. To check that the PHP engine has been installed successfully and PHP processing
has been enabled in the Apache configuration:
Open Notepad or another text editor and Create a file and type the following text:
 <?php
echo "PHP has been installed successfully!";
?>
 Save the file in the htdocs folder as test.php. The default path is C:\Program
Files\Apache Software Foundation\Apache<version>\htdocs\test.php
 Run the browser and enter the following URL: http://localhost:<port>/test.php. The
following page opens:

Troubleshooting
If the page does not open:

1. Restart the Apache server.


2. Check that the Apache server configuration file httpd.conf contains the following lines:
3. AddType Application/x-httpd-php .php
LoadModule php5_module "c:/php/sapi/php5apache2_2.dll"
4. If the lines are missing, add them, save httpd.conf, and restart Apache.
5. Refresh the http://localhost:<port>/test.php page.
MySQL Database Server
Find detailed information on installing and configuring the MySQL database server.

www.mrcet.ac.in DEPARTMENT OF CSE Page 12


WEB TECHNOLOGIES LAB MRCET

Installation of WampServer2:
To start the installation process, you need to open the folder where you saved the file, and
double-click the installer file. A security warning window will open, asking if you are sure
you want to run this file. Click Run to start the installation process.
Next you will see the Welcome To The WampServer Setup Wizard screen. Click Next to
continue the installation.

The next screen you are presented with is the License Ageement. Read the agreement,
check the radio button next to I accept the agreement, then click Next to continue the
installation.
Next you will see the Select Destination Location screen. Unless you would like to install
WampServer on another drive, you should not need to change anything. Click Next to
continue.
The next screen you are presented with is the Select Additional Tasks screen. You will be
able to select whether you would like a Quick Launch icon added to the taskbar or a Desktop
icon created once installation is complete. Make your selections, then click Next to continue.

www.mrcet.ac.in DEPARTMENT OF CSE Page 13


WEB TECHNOLOGIES LAB MRCET

Next you will see the Ready To Install screen. You can review your setup choices, and
change any of them by clicking Back to the appropriate screen, if you choose to. Once you
have reviewed your choices, click Install to continue.
WampServer will begin extracting files to the location you selected.

Once the files are extracted, you will be asked to select your default browser. WampServer
defaults to Internet Explorer upon opening the local file browser window. If your default
browser isn’t IE, then look in the following locations for the corresponding .exe file:
 Opera: C:\Program Files (x86)\Opera\opera.exe
 Firefox: C:\Program Files (x86)\Mozille Firefox\firefox.exe
 Safari: C:\Program Files (x86)\Safari\safari.exe
 Chrome: C:\Users\xxxxx\AppData\Local\Google\Chrome\Application\chrome.exe
Select your default browser’s .exe file, then click Open to continue. The Setup screen will
appear next, showing you the status of the installation process.

Once the progress bar is completely green, the PHP Mail Parameters screen will appear.
Leave the SMTP server as localhost, and change the email address to one of your
choosing. Click Next to continue.

www.mrcet.ac.in DEPARTMENT OF CSE Page 14


WEB TECHNOLOGIES LAB MRCET

The Installation Complete screen will now appear. Check the Launch WampServer Now
box, then click Finish to complete the installation.

Testing WampServer:
Once you have completed the installation process, test that your installation is working
properly by going to http://localhost/ in your browser. You should see the WampServer
homepage displayed.

www.mrcet.ac.in DEPARTMENT OF CSE Page 15


WEB TECHNOLOGIES LAB MRCET

PROGRAM-2 DATE:

Aim: 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 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.

Main.html
<html>
<head>
<title>HTML - Convert numbers to words using JavaScript</title>
<script src="src.js" type="text/javascript"></script>
</head>
<body>
<h1>
HTML - Convert numbers to words using JavaScript</h1>
<input id="Text1" type="text" onkeypress="return onlyNumbers(this.value);"
onkeyup="NumToWord(this.value,'divDisplayWords');"maxlength="4" style="background-
color: #efefef; border: 2px solid #CCCCC; font-size: large" />
<br />
<br />
<div id="divDisplayWords" style="font-size: 13; color: Teal; font-family: Arial;">
</div>
</body>
</html>

Src.js
function onlyNumbers(evt) {
var e = event || evt; // For trans-browser compatibility
var charCode = e.which || e.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}

function NumToWord(inputNumber, outputControl) {


var str = new String(inputNumber)
var splt = str.split("");
var rev = splt.reverse();
var once = ['Zero', ' One', ' Two', ' Three', ' Four', ' Five', ' Six', ' Seven', ' Eight', ' Nine'];
var twos = ['Ten', ' Eleven', ' Twelve', ' Thirteen', ' Fourteen', ' Fifteen', ' Sixteen', '
Seventeen', ' Eighteen', ' Nineteen'];
var tens = ['', 'Ten', ' Twenty', ' Thirty', ' Forty', ' Fifty', ' Sixty', ' Seventy', ' Eighty', ' Ninety'];

numLength = rev.length;
var word = new Array();

www.mrcet.ac.in DEPARTMENT OF CSE Page 16


WEB TECHNOLOGIES LAB MRCET

var j = 0;
for (i = 0; i < numLength; i++) {

switch (i)
{
case 0:
if ((rev[i] == 0) || (rev[i + 1] == 1)) {
word[j] = '';
}
else {
word[j] = once[rev[i]];
}
word[j] = word[j];
break;

case 1:
aboveTens();
break;

case 2:
if (rev[i] == 0) {
word[j] = '';
}
else if ((rev[i - 1] == 0) || (rev[i - 2] == 0)) {
word[j] = once[rev[i]] + " Hundred ";
}
else {
word[j] = once[rev[i]] + " Hundred and";
}
break;

case 3:
document.write("Number Out of Range");
break;

default:
break;
}
j++;
}
function aboveTens() {
if (rev[i] == 0) { word[j] = ''; }
else if (rev[i] == 1) { word[j] = twos[rev[i - 1]]; }
else { word[j] = tens[rev[i]]; }
}
word.reverse();

www.mrcet.ac.in DEPARTMENT OF CSE Page 17


WEB TECHNOLOGIES LAB MRCET

var finalOutput = '';


for (i = 0; i < numLength; i++) {
finalOutput = finalOutput + word[i];
}
document.getElementById(outputControl).innerHTML = finalOutput;
}

OUTPUT:

Signature of the faculty

www.mrcet.ac.in DEPARTMENT OF CSE Page 18


WEB TECHNOLOGIES LAB MRCET

PROGRAM-3 DATE:

Aim: Write a 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
spaces and lines are separated with new line character.

count.html
<html>
<head>
<script>
function countWords(str)
{
var count = 0;
words = str.split(" ");
for (i=0 ; i < words.length ; i++){
// inner loop -- do the count
if (words[i] != "")
count += 1;
}
document.theForm.results.value ="There are " +count +" words in the text string you
entered!";
}
function countLines()
{
var area = document.getElementById("texta");
// trim trailing return char if exists
var text = area.value.replace(/\s+$/g,"");
var split = text.split("\n");
return split.length;
}
function countit(what){
formcontent=what.form.inStr.value
what.form.displaycount.value=formcontent.length
}
</script>
</head>
<body>
<h1><font color="purple">COUNT TOTAL NUMBER OF WORDS CHARACTERS AND
LINES</font></h1>
<form name="theForm">
Enter a text string:
<textarea name="inStr" id="texta" rows=5 cols=15>
</textarea>
<input type=button value="Count Words"
onClick="countWords(document.theForm.inStr.value)";>

www.mrcet.ac.in DEPARTMENT OF CSE Page 19


WEB TECHNOLOGIES LAB MRCET

<input type=button name="theButton" value="Clear Results"


onClick='document.theForm.results.value=""';>
<br>
<textarea name=results rows=5 cols=90>
</textarea>
<table>
<tr>
<td width="100%"><div align="right"><p><input type="button" value="Calculate Characters"
onClick="countit(this)"> <input type="text" name="displaycount" size="20"></p>
</div></td>
</tr>
</table>
<br>
<button onclick="alert(countLines())">Count Lines</button>
</form>
</body>
</html>

OUTPUT:

Signature of the faculty

www.mrcet.ac.in DEPARTMENT OF CSE Page 20


WEB TECHNOLOGIES LAB MRCET

PROGRAM- 4 DATE:

Aim: 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 the capital (color, bold and font size).

Countries.html
<html>
<head>
<title>Get the country capital</title>
</head>
<body bgcolor="black" onload="document.getElementById('myedit').value=''">
<font color="white" size="4"><b>Select the country name to find its capital and
continent</b></font><br/><br/>
<br>
<select <input type="text" class="resizedTextbox" id="myedit" onchange="editChange()"
onkeyup="editChange()" />>
<option>Select Country</option>
<option>Germany</option>
<option>United States of America</option>
<option>India</option>
<option>United Kingdom</option>
<option>France</option>
</select>
<div id="result">&nbsp;</div>
<script type="text/javascript">
// country,capital,continent
var cName = new Array();
cName[0] = 'Germany,Berlin,Europe';
cName[1] = 'United States of America,Washington DC,North America';
cName[2] = 'India,New Delhi,Asia';
cName[3] = 'United Kingdom,London,Europe';
cName[4] = 'France,Paris,Europe';
function editChange() {
obj = document.getElementById('myedit');
s = obj.value.toLowerCase();
res = '';
for (i=0; i<cName.length; i++) {
s2 = cName[i].toLowerCase().substr(0, s.length);
if (s2 == s && s != '') {
sp = cName[i].split(',');

www.mrcet.ac.in DEPARTMENT OF CSE Page 21


WEB TECHNOLOGIES LAB MRCET

res += '<table><tr><td><font color="white" size="5">'+sp[0]+',


'+sp[1]+'&nbsp;&nbsp;'+sp[2]+'<font></td></tr></table>';
}
}
document.getElementById('result').innerHTML = res == '' ? '<font color="white"
size="5"><i>&nbsp; Not found</i></font>' : res;
}
</script>
</body>
</html>

OUTPUT:

Signature of the faculty

www.mrcet.ac.in DEPARTMENT OF CSE Page 22


WEB TECHNOLOGIES LAB MRCET

PROGRAM- 5 DATE:

Aim: Create and save an XML document at the server, which contains 10 users information.
Write a program which takes User Id as input and returns the user details by taking the user
information from the XML document.

User.xml

<?xml version=”1.0”?>
<userlist>
<user>
<userid>usr01</userid>
<username>Gouse</username>
<address>DSNR</address>
<phone>8801550101</phone>
<email>[email protected]</email>
</user>
<user>
<userid>usr02</userid>
<username>D Divakar</username>
<address>Ameerpet</address>
<phone>9888888888</phone>
<email>D [email protected]</email>
</user>
<user>
<userid>usr03</userid>
<username>Rajinth</username>
<address>SR Nagar</address>
<phone>9866666666</phone>
<email>[email protected]</email>
</user>
<user>
<userid>usr04</userid>
<username>M Vijaya</username>
<address>DESHMUKHI</address>
<phone>9835994445</phone>
<email>M [email protected]</email>
</user>
<user>
<userid>usr05</userid>
<username>Kusuma</username>
<address>KOTI</address>
<phone>968877555</phone>
<email>[email protected]</email>
</user>

www.mrcet.ac.in DEPARTMENT OF CSE Page 23


WEB TECHNOLOGIES LAB MRCET

<user>
<userid>usr06</userid>
<username>P Kalpana</username>
<address>KOTI</address>
<phone>968875554</phone>
<email>P [email protected]</email>
</user>

<user>
<userid>usr07</userid>
<username>V Anitha</username>
<address>KPHB</address>
<phone>968888554</phone>
<email>V [email protected]</email>
</user>

<user>
<userid>usr08</userid>
<username>M Ramesh</username>
<address>IBP</address>
<phone>968878554</phone>
<email>M [email protected]</email>
</user>

<user>
<userid>usr09</userid>
<username>Raswitha</username>
<address>DSNGR</address>
<phone>968899554</phone>
<email>[email protected]</email>
</user>

<user>
<userid>usr10</userid>
<username>A Prasanna</username>
<address>KPHB</address>
<phone>9088008554</phone>
<email>A [email protected]</email>
</user>

</userlist>

www.mrcet.ac.in DEPARTMENT OF CSE Page 24


WEB TECHNOLOGIES LAB MRCET

User.html

<html>
<head>
<script language="javascript">
function fncDisplayInfo()
{
var xhttp=null;
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><b>User ID :&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp"+uid)
document.write("<br>User Name :&nbsp"+userName);
document.write("<br>Address :&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp "+Address);
document.write("<br>Phone no : &nbsp&nbsp&nbsp&nbsp&nbsp"+phone);
document.write("<br>E - Mail : &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp"+email);
flag =1;
break;
}
}
if(flag==0)
{
alert("InValid User");
}
}
</script>
</head>
<body>
<center>

www.mrcet.ac.in DEPARTMENT OF CSE Page 25


WEB TECHNOLOGIES LAB MRCET

<h1><b>User Information</h1>
<form name="frm">
User ID : <input type="text" name="uname"><br>
<input type="button" name="btn" value="Submit" onclick="fncDisplayInfo()">
</form>
</center>
</body>
</html>

OUTPUT:

Signature of the faculty

www.mrcet.ac.in DEPARTMENT OF CSE Page 26


WEB TECHNOLOGIES LAB MRCET

PROGRAM: 6 & 6-1 DATE:

Implement the following web applications using (a) PHP, (b) Servlets and (c) JSP.

6.1 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
Database and if the data matches, a successful login page is returned. Otherwise a failure
message is shown to the user.

Aim: User Authentication:


cologin.html:
<html>
<head>
<title> login Page </title>
<p style= "background:yellow; top:100px; left:250px; position:absolute; ">
</head>
<body>
<form ACTION="clogin">
<label> Login </label>
<input type="text" name="usr" size="20"> <br> <br>
<label> Password </label>
<input type="password" name="pwd" size="20"> <br> <br>
<input type="submit" value="submit">
</form>
</body>
</html>

Addcook.java:
import javax.servlet.* ;
import javax.servlet.http.*;
import java.io.*;
public class Addcook extends HttpServlet
{
String user,pas;
public void service(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
Cookie c1=new Cookie("usr1","mrcet");
Cookie p1=new Cookie("pwd1","122");
Cookie c2=new Cookie("usr2","abc");
Cookie p2=new Cookie("pwd2","123");
Cookie c3=new Cookie("usr3","def");
Cookie p3=new Cookie("pwd3","456");

www.mrcet.ac.in DEPARTMENT OF CSE Page 27


WEB TECHNOLOGIES LAB MRCET

Cookie c4=new Cookie("usr4","mno");


Cookie p4=new Cookie("pwd4","789");
res.addCookie(c1);
res.addCookie(p1);
res.addCookie(c2);
res.addCookie(p2);
res.addCookie(c3);
res.addCookie(p3);
res.addCookie(c4);
res.addCookie(p4);
out.println("COOKIE ADDED");
}
}

Clogin.java:
import javax.servlet.* ;
import javax.servlet.http.*;
import java.io.*;
public class Clogin extends HttpServlet
{
String user,pas;
public void service(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
user=req.getParameter("usr");
pas=req.getParameter("pwd");
Cookie[] c=req.getCookies();
for(int i=0;i<c.length;i++)
{
if((c[i].getName().equals("usr1")&&c[i+1].getName().equals("pwd1"))||
c[i].getName().equals("usr2") &&c[i+1].getName().equals("pwd2"))||
(c[i].getName().equals("usr3")&& c[i+1].getName().equals("pwd3"))||
(c[i].getName().equals("usr4")&& c[i+1].getName().equals("pwd4") ))
{
if((user.equals(c[i].getValue()) &&
pas.equals(c[i+1].getValue())) )
{
//RequestDispatcher
rd=req.getRequestDispatcher("/cart.html");
rd.forward(req,res);
}
else
{
out.println("YOU ARE NOT AUTHORISED USER ");

www.mrcet.ac.in DEPARTMENT OF CSE Page 28


WEB TECHNOLOGIES LAB MRCET

//res.sendRedirect("/cookdemo/cologin.html");
}
}
}
}
}

Web.xml:
<web-app>
<servlet>
<servlet-name>him</servlet-name>
<servlet-class>Clogin</servlet-class>
</servlet>
<servlet>
<servlet-name>him1</servlet-name>
<servlet-class>Addcook</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>him</servlet-name>
<url-pattern>/clogin</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>him1</servlet-name>
<url-pattern>/clogin1</url-pattern>
</servlet-mapping>
</web-app>

OUTPUT:

www.mrcet.ac.in DEPARTMENT OF CSE Page 29


WEB TECHNOLOGIES LAB MRCET

Signature of the faculty

www.mrcet.ac.in DEPARTMENT OF CSE Page 30


WEB TECHNOLOGIES LAB MRCET

PROGRAM: 6-2 DATE:

Modify the above program to use an XML file instead of database.

AIM: : Read the user id and passwords entered in the Login form and authenticate with the values
(user id and passwords) available in the cookies. Use init-parameters to do this. Store the user-names
and passwords in the webinf.xml and access them in the servlet by using the getInitParameters()
method. If he is a valid user (i.e., user-name and password match) you should welcome him by name
(user-name) else you should display “You are not an authenticated user “.

home.html:
<html>
<head>
<title>Authentication</title>
</head>
<body>
<form action="ex1">
<label>Username </label>
<input type="text"size="20" name="user"><br><br>
password<input type="text" size="20" name="pwd"><br><br>
<input type="submit" value="submit">
</form>
</body>
</html>

Example1.java
import javax.servlet.*;
import java.io.*;
public class Example1 extends GenericServlet
{
private String
user1,pwd1,user2,pwd2,user3,pwd3,user4,pwd4,user5,pwd5;
public void init(ServletConfig sc)
{
user1=sc.getInitParameter("username1");
pwd1=sc.getInitParameter("password1");
user2=sc.getInitParameter("username2");

www.mrcet.ac.in DEPARTMENT OF CSE Page 31


WEB TECHNOLOGIES LAB MRCET

pwd2=sc.getInitParameter("password2");
user3=sc.getInitParameter("username3");
pwd3=sc.getInitParameter("password3");
user4=sc.getInitParameter("username4");
pwd4=sc.getInitParameter("password4");
}
Public void service(ServletRequest req,ServletResponse res)throws
ServletException,IOException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
user5=req.getParameter("user");
pwd5=req.getParameter("pwd");
if((user5.equals(user1)&&pwd5.equals(pwd1))||
(user5.equals(user2)&&pwd5.equals(pwd2))||
(user5.equals(user3)&&pwd5.equals(pwd3))||
(user5.equals(user4)&&pwd5.equals(pwd4)))
out.println("<p> welcome to"+user5.toUpperCase());
else
out.println("You are not authorized user");
}
}

web.xml:
<web-app>
<servlet>
<servlet-name>Example</servlet-name>
<servlet-class>Example1</servlet-class>
<init-param>
<param-name>username1</param-name>
<param-value>mrcet</param-value>

www.mrcet.ac.in DEPARTMENT OF CSE Page 32


WEB TECHNOLOGIES LAB MRCET

</init-param>
<init-param>
<param-name>password1</param-name>
<param-value>cse</param-value>
</init-param>
<init-param>
<param-name>username2</param-name>
<param-value>1234</param-value>
</init-param>
<init-param>
<param-name>password2</param-name>
<param-value>4567</param-value>
</init-param>
<init-param>
<param-name>username3</param-name>
<param-value>cse</param-value>
</init-param>
<init-param>
<param-name>password3</param-name>
<param-value>pvpsit</param-value>
</init-param>
<init-param>
<param-name>username4</param-name>
<param-value>wt</param-value>
</init-param>
<init-param>
<param-name>password4</param-name>
<param-value>lab</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>Example</servlet-name>
<url-pattern>/ex1</url-pattern>
</servlet-mapping>
</web-app>

www.mrcet.ac.in DEPARTMENT OF CSE Page 33


WEB TECHNOLOGIES LAB MRCET

OUTPUT:

RESULT:

Thus the user authentication is carried out for four users by using both cookies and
getInitParameters successfully.

Signature of the faculty

www.mrcet.ac.in DEPARTMENT OF CSE Page 34


WEB TECHNOLOGIES LAB MRCET

PROGRAM: 6-III DATE:

AIM: Modify the above program using AJAX to show the result on the same page below the submit
button.

login.html

<html>
<head>
<script type="text/javascript" src="js/ajaxFrmSbmt.js"></script>
<title></title>
</head>
<body>
<form name="form1" method="post" onsubmit="getxmlHttpRequest('LoginServlet',
'form1', 'message', 'please wait...'); return false;">
Enter name <input type="text" name="username"/><br>
Password <input type="password" name="password"/>
<input type="submit" value="submit"/>
</form>
<div id="message"></div>
</body>
</html>

ajaxFrmSbmt.js

function getxmlHttpRequest(servletName,formname,responsediv,responsemsg) {
var xmlhttp = false;
var x = this;
// For the browsers Mozilla/Safari/Ie7
if (window.XMLHttpRequest) {
x.xmlhttp = new XMLHttpRequest();
}
// for the lower version of IE
else if (window.ActiveXObject) {
x.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
x.xmlhttp.open('POST', servletName, true);
x.xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
x.xmlhttp.onreadystatechange = function() {
if (x.xmlhttp.readyState == 4)
{
updatepage(x.xmlhttp.responseText,responsediv);
}
else
{
updatepage(responsemsg,responsediv);

www.mrcet.ac.in DEPARTMENT OF CSE Page 35


WEB TECHNOLOGIES LAB MRCET

} }
x.xmlhttp.send(getquerystring(formname));
}

function getquerystring(formname) {
var form = document.forms[formname];
var qstr = "";
function GetElemValue(name, value) {
qstr += (qstr.length > 0 ? "&" : "")
+ escape(name).replace(/\+/g, "%2B") + "="
+ escape(value ? value : "").replace(/\+/g, "%2B");
//+ escape(value ? value : "").replace(/\n/g, "%0D");
}
var elemArray = form.elements;
for (var i = 0; i < elemArray.length; i++) {
var element = elemArray[i];
var elemType = element.type.toUpperCase();
var elemName = element.name;
if (elemName) {
if (elemType == "TEXT" || elemType == "PASSWORD")
{
GetElemValue(elemName, element.value);
alert("welcome");
}
else if (elemType.indexOf("SELECT") != -1)
for (var j = 0; j < element.options.length; j++) {
var option = element.options[j];
if (option.selected)
GetElemValue(elemName,
option.value ? option.value : option.text);
}
}
}
return qstr;
}
function updatepage(str,responsediv){
document.getElementById(responsediv).innerHTML = str;
}

LoginServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

www.mrcet.ac.in DEPARTMENT OF CSE Page 36


WEB TECHNOLOGIES LAB MRCET

public class LoginServlet extends HttpServlet


{
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String uname=request.getParameter("username ");
String pwd=request.getParameter("password");
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@195.100.101.15
8:1521:CCLAB","scott","tiger");
Statement st=con.createStatement();

ResultSet rs=st.executeQuery("select name,password from personal


where name='"+uname+"' and password='"+pwd+"'");

if(rs.next())
{
{
out.println(" successfully logged in");
}
else
out.println(" password is invalid, failed login");
}
}
web.xml

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


<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>ajaxWithServlet</display-name>
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>LoginServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
</web-app>

www.mrcet.ac.in DEPARTMENT OF CSE Page 37


WEB TECHNOLOGIES LAB MRCET

OUTPUT:

Signature of the faculty

www.mrcet.ac.in DEPARTMENT OF CSE Page 38


WEB TECHNOLOGIES LAB MRCET

PROGRAM: 6-IV DATE:

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

Calculator.html (HTML with JavaScript)


<html>
<head>
<title>Arithmetic operations</title>
</head>
<script type="text/javascript">
function Addition()
{
x=parseFloat(calc.value1.value);
y=parseFloat(calc.value2.value);
z=(x+y);
alert("The Addition result is"+z);
calc.value3.value=z
}
function Subtraction()
{
var x,y,z;
x=calc.value1.value;
y=calc.value2.value;
z=x-y;
alert("The subtraction result is "+z);
calc.value3.value=z
}
function Multiplication()
{
var x,y,z;
x=calc.value1.value;
y=calc.value2.value;
z=x*y;
alert("The Multiplication result is "+z);
calc.value3.value=z
}
function Division()
{
var x,y,z;

www.mrcet.ac.in DEPARTMENT OF CSE Page 39


WEB TECHNOLOGIES LAB MRCET

x=calc.value1.value;
y=calc.value2.value;
z=x/y;
alert("The subtraction result is "+z);
calc.value3.value=z
}
</script>
</head>
<body>
<form name="calc">
<h1>Online Calculator</h1>
Enter first Numeric Value : <input type="number" id="value1"> </br>
Enter Second Numeric Value : <input type="number" id="value2"> </br>
</br>
Result of the Arithmetic operation is : <output type="number" id="value3"> </output></br>
<input type="button" Value="Addition" onClick=Addition()> </br>
<input type="button" Value="Subtraction" onClick=Subtraction()></br>
<input type="button" Value="Multiplication" onClick=Multiplication()></br>
<input type="button" Value="Division" onClick=Division()></br>
</form>
</body>
</html>

OUTPUT:

Signature of the faculty

www.mrcet.ac.in DEPARTMENT OF CSE Page 40


WEB TECHNOLOGIES LAB MRCET

PROGRAM: 6-IV.I DATE:

AIM: Calculator using Servlet

CalculateServlet.html
<html>
<head>
<title>Calculator in servlet</title>
</head>
<body>
<form method="get" action="./CalculateServlet">
Number 1 : <input type="text" name="no1"> <br>
Number 2 : <input type="text" name="no2"> <br>
Operator :
<select name="opt">
<option value="a"> + </option>
<option value="s"> - </option>
<option value="m"> * </option>
<option value="d"> / </option>
<option value="mod"> % </option>
</select>
<br>
<input type="submit" value="Go">
</form>
</body>
</html>

CalculateServlet.java
import java.io.*;
import javax.servlet.*;
//import javax.servlet.http.*;

public class CalculateServlet extends HttpServlet


{
public void doPost(HttpServletRequest request,HttpServletResponse response) throws
IOException,ServletException
{
display();
PrintWriter out = response.getWriter();
//out.println("hello");
String n1 = request.getParameter("no1");
String n2 = request.getParameter("no2");
String opt = request.getParameter("opt");
if(opt.equals("a"))

www.mrcet.ac.in DEPARTMENT OF CSE Page 41


WEB TECHNOLOGIES LAB MRCET

out.println(Integer.parseInt(n1) + Integer.parseInt(n2));
else if(opt.equals("s"))
out.println(Integer.parseInt(n1) - Integer.parseInt(n2));
else if(opt.equals("m"))
out.println(Integer.parseInt(n1) * Integer.parseInt(n2));
else if(opt.equals("d"))
out.println(Integer.parseInt(n1) / Integer.parseInt(n2));
else if(opt.equals("mod"))
out.println(Integer.parseInt(n1) % Integer.parseInt(n2));
}
public void doGet(HttpServletRequest request,HttpServletResponse response) throws
IOException,ServletException
{
doPost(request,response);
}

web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app metadata-complete="true">
<display-name>Tomcat Manager Application</display-name>
<description>
A scriptable management web application for the Tomcat Web Server;
Manager lets you view, load/unload/etc particular web applications.
</description>
<servlet>
<servlet-name><strong>CalculateServlet</strong></servlet-name>
<servlet-class><strong>CalculateServlet</strong></servlet-class>
</servlet>
<!-- Define the Manager Servlet Mapping -->
<servlet-mapping>
<servlet-name><strong>CalculateServlet</strong></servlet-name>
<url-pattern>/<strong>CalculateServlet</strong></url-pattern>
</servlet-mapping>
</web-app>

www.mrcet.ac.in DEPARTMENT OF CSE Page 42


WEB TECHNOLOGIES LAB MRCET

OUTPUT:

Signature of the faculty

www.mrcet.ac.in DEPARTMENT OF CSE Page 43


WEB TECHNOLOGIES LAB MRCET

PROGRAM: 6-IV.II DATE:

AIM: Calculator using PHP scripting language


Calculate.php:
<?php
ini_set('display_errors',0);
if( isset( $_REQUEST['calculate'] ))
{
$operator=$_REQUEST['operator'];
if($operator=="+")
{
$add1 = $_REQUEST['fvalue'];
$add2 = $_REQUEST['lvalue'];
$res= $add1+$add2;
}
if($operator=="-")
{
$add1 = $_REQUEST['fvalue'];
$add2 = $_REQUEST['lvalue'];
$res= $add1-$add2;
}
if($operator=="*")
{
$add1 = $_REQUEST['fvalue'];
$add2 = $_REQUEST['lvalue'];
$res =$add1*$add2;
}
if($operator=="/")
{
$add1 = $_REQUEST['fvalue'];
$add2 = $_REQUEST['lvalue'];
$res= $add1/$add2;
}
if($_REQUEST['fvalue']==NULL && $_REQUEST['lvalue']==NULL)
{
echo "<script language=javascript> alert(\"Please Enter values.\");</script>";
}
else if($_REQUEST['fvalue']==NULL)
{
echo "<script language=javascript> alert(\"Please Enter First value.\");</script>";
}
else if($_REQUEST['lvalue']==NULL)
{
echo "<script language=javascript> alert(\"Please Enter second value.\");</script>";
}

www.mrcet.ac.in DEPARTMENT OF CSE Page 44


WEB TECHNOLOGIES LAB MRCET

}
?>
<html>
<body>
<center>
<h1>CALCULATOR IN PHP</h1>
<form>
<table style="border:groove #00FF99">
<tr>
<td style="background-color:aqua; color:red; font-family:'Times New
Roman'">Enter First Number</td>
<td colspan="1">

<input name="fvalue" type="text" style="color:red"/></td>


<tr>
<td style="color:brown; font-family:'Times New Roman'">Select Operator</td>
<td>
<select name="operator" style="width: 63px">
<option>+</option>
<option>-</option>
<option>*</option>
<option>/</option>
</select>
</td>
</tr>
<tr>
<td style="background-color:aqua; color:red; font-family:'Times New Roman'">Enter First
Number</td>
<td class="auto-style5">
<input name="lvalue" type="text" style="color:red"/></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="calculate" value="Calculate"
style="color:wheat;background-color:rosybrown" /></td>

</tr>
<tr>
<td style="background-color:aqua;color:red">Output = </td>
<td style="color:darkblue"><?php echo $res;?></td>
</tr>
</table>
</form>
</center>
</body>
</html>

www.mrcet.ac.in DEPARTMENT OF CSE Page 45


WEB TECHNOLOGIES LAB MRCET

OUTPUT 1:

OUTPUT 2:

Signature of the faculty

www.mrcet.ac.in DEPARTMENT OF CSE Page 46


WEB TECHNOLOGIES LAB MRCET

PROGRAM: 6-V DATE:

AIM: Modify the above program such that it stores each query in a DB and checks the DB
first for the result. If the query is already available in 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.

Steps:
1) Create the following Servlet file in Eclipse
MyServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
response.setContentType("text/html"); // informing the client that which
format of data/response will be send
PrintWriter out= response.getWriter();
//All data entered into a "TEXT" field of form, is stored as "STRING"
//Hence if we enter "1" in a "TEXT" field of form, it will be stored as "ONE"
//To convert it to "INT", we use a predefined function called= "parseInt()"
int a1= Integer.parseInt(request.getParameter("n1"));
// using "getParameter()" to retrieve data entered by user in "n1" field
int a2= Integer.parseInt(request.getParameter("n2"));

if (request.getParameter("r1")!=null) // checking if 1st radio button checked or not?


{
out.println("<h3> Addition= </h3>"+(a1+a2));
}
else if(request.getParameter("r2")!=null) // checking if 2nd radio button checked or not?
{
out.println("<h3> Subtraction= </h3>"+(a1-a2));
}
else if(request.getParameter("r3")!=null) //checking if 3rd radio button
checked or not?
{
out.println("<h3> Multiply= </h3>"+(a1*a2));
}
else
{
out.println("<h3> Divide= </h3>"+(a1/a2));
} } }

www.mrcet.ac.in DEPARTMENT OF CSE Page 47


WEB TECHNOLOGIES LAB MRCET

2) Next create a HTML File


Right click on “WebContent” folder –> New –> HTML File

Enter File Name: “index.html” and click on “FINISH” button

www.mrcet.ac.in DEPARTMENT OF CSE Page 48


WEB TECHNOLOGIES LAB MRCET

3) Now replace the existing “index.html” file code with this


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<form action="MyServlet" method="get">


Enter 1st Number <input type="text" name="n1"><br>
Enter 2nd Number <input type="text" name="n2"><br>

<input type="radio" name="r1" value="Add">Add<br>


<input type="radio" name="r2" value="Subtract">Subtract<br>
<input type="radio" name="r3" value="Multiply">Multiply<br>
<input type="radio" name="r4" value="Divide">Divide<br>
<input type="Submit" value="Submit">

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

www.mrcet.ac.in DEPARTMENT OF CSE Page 49


WEB TECHNOLOGIES LAB MRCET

4) Now press “CTRL”+F11, you will get the following screen. Click on “FINISH
BUTTON”, selecting WEB SERVER.

5) You will get output

6) Enter two numbers and perform any option like:

Signature of the faculty

www.mrcet.ac.in DEPARTMENT OF CSE Page 50


WEB TECHNOLOGIES LAB MRCET

PROGRAM: 6-VI DATE:

AIM: 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 the logout button. On clicking this button, it should show a logout page with Thank
You<name> message with the duration of usage.(Use session to store name and time).

Login.jsp

<html>
<head>
</head>
<body>
<%
String logTime = request.getParameter("logtime");
if(logTime != null) {
session.setAttribute("loggedIn", logTime);
}
String pname = request.getParameter("pName");
if(pname != null) {
session.setAttribute("pname", pname);
}
String duration = request.getParameter("duration");
if(duration != null) {
session.setAttribute("duration", duration);
}
%>

<FORM NAME="form1" METHOD="POST">


Please Enter Name:
<input type="text" name="tname"/><br></p>
<input type="submit" value="Submit" onclick="showTime ()"/>
<input type="hidden" name="pName" value=""/>
<input type="hidden" name="duration" value=""/>
<input type="hidden" name="logtime" value=""/>
</FORM>

<SCRIPT LANGUAGE="JavaScript">

function showTime()

www.mrcet.ac.in DEPARTMENT OF CSE Page 51


WEB TECHNOLOGIES LAB MRCET

{
var name = document.form1.tname.value;
document.write("Hello " + name);
document.form1.pName.value = name;

var time = new Date();


var loggedInTime = time.getHours() + ":" + time.getMinutes() + ":" + time.getSeconds();
document.write("<br>" + "The Logged in Time : " +loggedInTime);

document.form1.logtime.value = loggedInTime;

var buttonnode= document.createElement("input");


buttonnode.setAttribute("type","button");
buttonnode.setAttribute("name","logout");
buttonnode.setAttribute("value","Log Out");

buttonnode.attachEvent("OnClick", showLoggedInDuration());

}
function showLoggedInDuration()
{
var time = new Date();
var loggedOutTime = time.getHours() + ":" + time.getMinutes() + ":" +
time.getSeconds();
document.write("<br>" + "The Logged in Time : " +loggedOutTime);

var loggedInTime = document.form1.logtime.value;


var duration = loggedOutTime - loggedInTime;
document.form1.duration.value = duration;

document.location.href = "x.jsp";
}
</SCRIPT>
</body>
</html>

www.mrcet.ac.in DEPARTMENT OF CSE Page 52


WEB TECHNOLOGIES LAB MRCET

Result.jsp
<html>
<body>
<%
String name = sessio.getAttribute("pname");
String duration = request.getAttribute("duration");
%>
<header>
<h2>Thank you "${name}" </h2>
<br>
<h2>The total session duration is : "${duration}" </h2>
</header>
</body>
</html>

OUTPUT:

Signature of the faculty

www.mrcet.ac.in DEPARTMENT OF CSE Page 53


WEB TECHNOLOGIES LAB MRCET

PROGRAM: 6-VII Using PHP DATE:

AIM: 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.

main.html
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
</body>
</html>

welcome.php
<html>
<body>
<?php
if( $_POST["name"] || $_POST["age"] )
{
if(($_POST[“age”]>=18)
{
echo "Welcome ". $_POST['name'].”to this site” "<br />";
echo "You are ". $_POST['age']. " years old.";
exit();
}
else
{
echo "Hello ". $_POST['name']. " you are not authorized to visit this site";
exit();
}
}
?>
</body>
</html>

www.mrcet.ac.in DEPARTMENT OF CSE Page 54


WEB TECHNOLOGIES LAB MRCET

Output1:
mrcet 18 Submit
Name: Age:

Welcome mrcet to this site


You are 18 years old

Output2:
mrcet 16 Submit
Name: Age:

Hello mrcet you are not authorized to visit this site

Signature of the faculty

www.mrcet.ac.in DEPARTMENT OF CSE Page 55


WEB TECHNOLOGIES LAB MRCET

PROGRAM: 6-VIII DATE:

AIM: 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 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 database (hint: use
session for storing data, submitted login name and password).

Registration.html:
<html>
<head>
<title>Registration page</title>
</head>
<body bgcolor="#00FFFf">
<form METHOD="POST" ACTION="register">
<CENTER>
<table>
<center>
<tr> <td> Username </td>
<td><input type="text" name="usr"> </td> </tr>
<tr><td> Password </td>
<td><input type="password" name="pwd"> </td> </tr>
<tr><td>Age</td>
<td><input type="text" name="age"> </td> </tr>
<tr> <td>Address</td>
<td> <input type="text" name="add"> </td> </tr>
<tr> <td>email</td>
<td> <input type="text" name="mail"> </td> </tr>
<tr> <td>Phone</td>
<td> <input type="text" name="phone"> </td> </tr>
<tr> <td colspan=2 align=center> <input type="submit"
value="submit"> </td> </tr>
</center>
</table>
</form> </body> </html>

www.mrcet.ac.in DEPARTMENT OF CSE Page 56


WEB TECHNOLOGIES LAB MRCET

Login.html
<html>
<head>
<title>Registration page</title>
</head>
<body bgcolor=pink> <center> <table>
<form METHOD="POST" ACTION="authent">
<tr> <td> Username </td>
<td><input type="text" name="usr"></td> </tr>
<tr> <td> Password </td>
<td> <input type="password" name="pwd"> </td> </tr>
<tr> <td align=center colspan="2"><input type="submit"
value="submit"></td> </tr>
</table> </center>
</form>
</body>
</html>

Ini.java:
import javax.servlet.*;
import java.sql.*;
import java.io.*;
public class Ini extends GenericServlet
{
private String user1,pwd1,email1;
public void service(ServletRequest req,ServletResponse res) throws
ServletException,IOException
{
user1=req.getParameter("user");
pwd1=req.getParameter("pwd");
email1=req.getParameter("email");
res.setContentType("text/html");
PrintWriter out=res.getWriter();
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=
DriverManager.getConnection("jdbc:oracle:thin:@195.100.101.158:1521:cclab","scott","tiger");
PreparedStatement st=con.prepareStatement("insert into personal values(?,?,?,?,?,?)");
st.setString(1,user1);

www.mrcet.ac.in DEPARTMENT OF CSE Page 57


WEB TECHNOLOGIES LAB MRCET

st.setString(2,pwd1);
st.setString(3,"25");
st.setString(4,"hyd");
st.setString(5,email1);
st.setString(6,"21234");
st.executeUpdate();
con.close();
}
catch(SQLException s)
{ out.println("not found "+s);
}
catch(ClassNotFoundException c)
{
out.println("not found "+c);
}
}
}

web.xml:
<web-app>
<servlet>
<servlet-name>init1</servlet-name>
<servlet-class>Ini</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>init1</servlet-name>
<url-pattern>/regis</url-pattern>
</servlet-mapping>
</web-app>

www.mrcet.ac.in DEPARTMENT OF CSE Page 58


WEB TECHNOLOGIES LAB MRCET

OUTPUT:

www.mrcet.ac.in DEPARTMENT OF CSE Page 59


WEB TECHNOLOGIES LAB MRCET

www.mrcet.ac.in DEPARTMENT OF CSE Page 60


WEB TECHNOLOGIES LAB MRCET

www.mrcet.ac.in DEPARTMENT OF CSE Page 61


WEB TECHNOLOGIES LAB MRCET

RESULT:

Thus a table is created and the details are entered into the table using jdbc from the
registration form successfully.

Signature of the faculty

www.mrcet.ac.in DEPARTMENT OF CSE Page 62


WEB TECHNOLOGIES LAB MRCET

PROGRAM: 6-VIII.1 DATE:

AIM: Write a JSP which does the following job

Insert the details of the 3 or 4 users who register with the web site by using registration form.
Authenticate the user when he submits the login form using the user name and password
from the database.

Login.html:
<!--Home.html-->
<html> <body>
<center><h1>XYZ Company Ltd.</h1></center>
<table border="1" width="100%" height="100%">
<tr>
<td valign="top" align="center"><br/>
<form action="auth.jsp"><table>
<tr>
<td colspan="2" align="center"><b>Login
Page</b></td>
</tr> <tr>
<td colspan="2"
align="center"><b>&nbsp;</td>
</tr>
<tr>
<td>User Name</td>
<td><input type="text" name="user"/></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password"
name="pwd"/></td>
</tr> <tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr> <tr>
<td colspan="2" align="center"><input type="submit"
value="LogIN"/></td>
</tr>
</table> </form> </td>
</tr> </table>
</body> </html>

www.mrcet.ac.in DEPARTMENT OF CSE Page 63


WEB TECHNOLOGIES LAB MRCET

Auth.jsp:
<%@page import="java.sql.*;"%>
<html>
<head>
<title>
This is simple data base example in JSP</title>
</title>
</head>
<body bgcolor="yellow">
<%!String uname,pwd;%>
<%
uname=request.getParameter("user");
pwd=request.getParameter("pwd");
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@195.100.101.15
8:1521:CCLAB","scott","tiger");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select name,password from personal
where name='"+uname+"' and password='"+pwd+"'");
if(rs.next())
{
out.println("Authorized person");
}
else
{
out.println("UnAuthorized person");
}
con.close();
}
catch(Exception e){out.println(""+e);}
%>
</body>
</html>

www.mrcet.ac.in DEPARTMENT OF CSE Page 64


WEB TECHNOLOGIES LAB MRCET

OUTPUT:

www.mrcet.ac.in DEPARTMENT OF CSE Page 65


WEB TECHNOLOGIES LAB MRCET

RESULT:

The user is authenticated when he submits the login form using the user name and
password from the database.

Signature of the faculty

www.mrcet.ac.in DEPARTMENT OF CSE Page 66


WEB TECHNOLOGIES LAB MRCET

PROGRAM: 6-IX DATE:

AIM: A web application that lists all cookies stored in the browser on clicking “List Cookies”
button. Add cookies if necessary.
AddCookie.html: Allows a user to specify a value for the cookie named
AddCookieServlet.java : Processes the submission of AddCookie.htm
GetCookiesServlet.java: Displays cookie values

AddCookie.html:
<html>
<body>
<center>
<form name="Form1" method="post"
action="http://localhost:8080/servlet/AddCookieServlet">
<B>Enter a value for MyCookie:</B>
<input type=textbox name="data" size=25 value="">
<input type=submit value="Submit">
</form>
</center>
</body>
</html>

AddCookieServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class AddCookieServlet extends HttpServlet
{
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String data = request.getParameter("data");
Cookie cookie = new Cookie("MyCookie", data);
response.addCookie(cookie);
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>MyCookie has been set to");
pw.println(data);
pw.close();
} }

www.mrcet.ac.in DEPARTMENT OF CSE Page 67


WEB TECHNOLOGIES LAB MRCET

GetCookiesServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class GetCookiesServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletE xception, IOException
{
Cookie[] cookies = request.getCookies();
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>");
for(int i = 0; i < cookies.length; i++)
{
String name = cookies[i].getName();
String value = cookies[i].getValue();
pw.println("name = " + name + "; value = " + value);
}
pw.close();
}
}

OUTPUT:
Your browser is sending the following cookies:
Cookie Name: ABCD
Cookie Value: 876543

Cookie Name: PQRS


Cookie Value: 1234567

Signature of the faculty

www.mrcet.ac.in DEPARTMENT OF CSE Page 68


WEB TECHNOLOGIES LAB MRCET

PROGRAM: 6-IX.I DATE:

AIM: Cookies using JSP

ShoppingCart.html
<html>
<head></head>
<body>
<form method="get" action="http://localhost:8888/india/ShoppingCart.jsp">
Enter Item Name <input type="text" name="item"><br>
Enter Item Quantity <input type="text" name="qty"><br>
<input type="submit" value="Add Cookie" name="add">
<input type="submit" value="List Cookies" name="list">
</form>
</body>
</html>

ShoppingCart.jsp

<body>
<%
String str1 = request.getParameter("item"); // item name
String str2 = request.getParameter("qty"); // item quantity
String str3 = request.getParameter("add"); // submit button by name add
String str4 = request.getParameter("list"); // submit button by name list
if(str3 != null)
{
Cookie c1 = new Cookie(str1, str2);
response.addCookie(c1);
response.sendRedirect("ShoppingCart.html");
}
else if(str4 != null)
{
Cookie clientCookies[] = request.getCookies();
for( int i = 0; i < clientCookies.length; i++)
{
out.print("<B>" + clientCookies[i].getName() + " : " + clientCookies[i].getValue() +
"</B><BR>");
}
}
%>
</body>

www.mrcet.ac.in DEPARTMENT OF CSE Page 69


WEB TECHNOLOGIES LAB MRCET

OUTPUT:

Signature of the faculty

www.mrcet.ac.in DEPARTMENT OF CSE Page 70

You might also like