Department of
computer science and engineering
|
LAB
MANUAL
|
WEB
TECHNOLOGIES
|
|
Ms.Y.DURGA BHARGAVI
|
Asst. Professor, CSE Dept
|
R 13 Regulation Academic
Year 2015-16
|
1. Write a HTML page including java
script that takes a number from one text
filed in a range of 0 to 999 and shows it in another text filed in words. If a
number is out of range, its should show “out of range” and if it is not a
number it should show “ not a number “ message in the result box
<html>
<head>
<script
type="text/javascript">
function update()
{
var output = '';
var numString =
document.getElementById('number').value;
var finlOutPut = new Array();
if (numString == 0) {
output="Zero is not
accepted";
document.calci.txt.value=output;
}
var i = numString.length;
i = i - 1;
//cut the number to grups of three digits and add them to the Arry
while (numString.length > 3)
{
var triDig = new Array(3);
triDig[2] =
numString.charAt(numString.length - 1);
triDig[1] =
numString.charAt(numString.length - 2);
triDig[0] =
numString.charAt(numString.length - 3);
var varToAdd = triDig[0] + triDig[1] +
triDig[2];
finlOutPut.push(varToAdd);
i--;
numString = numString.substring(0,
numString.length - 3);
}
finlOutPut.push(numString);
finlOutPut.reverse();
//conver each grup of three digits to english word
//if all digits are zero the triConvert
//function return the string "dontAddBigSufix"
for (j = 0; j < finlOutPut.length; j++)
{
finlOutPut[j] =
triConvert(parseInt(finlOutPut[j]));
}
//convert The output Arry to , more
printable string
for(n = 0; n<finlOutPut.length; n++){
output +=finlOutPut[n];
}
document.calci.txt.value=output;
}
//simple function to convert from
numbers to words from 1 to 999
function triConvert(num)
{
var ones = new Array('', ' one', ' two', ' three', ' four', ' five', '
six', ' seven', ' eight', ' nine', ' ten', ' eleven', ' twelve', ' thirteen', '
fourteen', ' fifteen', ' sixteen', ' seventeen', ' eighteen', ' nineteen');
var tens = new Array('', '', ' twenty', ' thirty', ' forty', ' fifty', '
sixty', ' seventy', ' eighty', ' ninety');
var hundred = ' hundred and';
var output = '';
var numString = num.toString();
if (num == 0) {
return;// ' DontAddBigSufix';
}
//the case of 10, 11, 12 ,13, .... 19
if (num < 20) {
output = ones[num];
return output;
}
//100 and more
if (numString.length == 3) {
output =
ones[parseInt(numString.charAt(0))] + hundred;
output += tens[parseInt(numString.charAt(1))];
output +=
ones[parseInt(numString.charAt(2))];
return output;
}
output += tens[parseInt(numString.charAt(0))];
output += ones[parseInt(numString.charAt(1))];
return output;
}
</script>
</head>
<body>
<form method="post"
name="calci">
<center><h3> Convert
Numbers to Text</h3><br/><br/>
<b>Enter Number
:</b><input type="text"
id="number"
size="50"
maxlength="4"
onkeyup="update();"
/*this code prevent non numeric letters*/
onkeydown="return (event.ctrlKey || event.altKey
|| (47<event.keyCode
&& event.keyCode<58 && event.shiftKey==false)
|| (95<event.keyCode
&& event.keyCode<106)
|| (event.keyCode==8) ||
(event.keyCode==9)
|| (event.keyCode>34
&& event.keyCode<40)
|| (event.keyCode==46)
)"/>
<br/><br/><br/><br/>
<b>Numbers to text</b>
<input type="text"
name="txt" onkeyup="update();" size="50"><br>
</center>
</form>
</body>
</html>
OUTPUT:
2) Write a
HTML page that has one input, which can take multi-line text and a submit button. Once users 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
<!DOCTYPE html PUBLIC
"-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html
xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Number of Characters</title>
<style type="text/css">
#TextArea1
{
height: 153px;
width: 800px;
}
#Button1
{
width: 100px;
height: 50px;
}
</style>
</head>
<body>
<center>
<p>
<textarea id="TextArea1"
name="S1"></textarea></p>
<p>
<button onclick="myFunction()">Submit</button>
<p id="demo">Given
Number of characters are </p>
<p id="demo1">Number
of words </p>
<script>
function myFunction()
{
var str = TextArea1.value;
var n = str.length;
document.getElementById("demo").innerHTML
= n ;
wordcount();
}
function
wordcount()
{
var
str = TextArea1.value;
var
wordCount = str.match(/(\w+)/g).length;
document.getElementById("demo1").innerHTML
= wordCount ;
}
</script>
</center>
</body>
</html>
OUTPUT:
3)
Write a 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)
<!DOCTYPE html>
<html>
<body bgcolor="cyan">
<center>
<br/><br/><br/>
<font size="20"
color="orange"><i><b><p>Select a Country for
Capital.</p>
<select id="country"
onchange="myCapital()">
<option value="Co" selected="selected">Choose
a Country</option>
<option value="Aus">Australia
<option value="Can">Canada
<option value="US">United States of America
<option value="IN">India
</select>
<p>Captial of Seleted Country
<br/></p>
<p id="demo"></p>
</b></i></font></center>
<script>
function myCapital() {
var x = document.getElementById("country").value;
if(x=="Aus")
{
document.getElementById("demo").innerHTML
= "Capital : Canberra ";
}
else
if(x=="Can")
{
document.getElementById("demo").innerHTML
= "Capital : Ottawa";
}
else
if(x=="US")
{
document.getElementById("demo").innerHTML
= "Capital : Washington, D.C.
";
}
else
if(x=="IN")
{
document.getElementById("demo").innerHTML
= "Capital : Delhi ";
}
else
if(x=="Co")
{
document.getElementById("demo").innerHTML
= "No Country is selected " ;
}
}
</script>
</body>
</html>
OUTPUT:
4)Create a
XML document that contains 10 users information. Write a java program,
which takes User Id as input and returns user details by taking the user
information from the XML document using
i) DOM parser
ReadXMLFile.java
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;
public class ReadXMLFile {
public static void main(String argv[]) {
try {
File
fXmlFile = new File("E:/Technical Stuff/2014/webtech/staff.xml");
DocumentBuilderFactory
dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder
dBuilder = dbFactory.newDocumentBuilder();
Document
doc = dBuilder.parse(fXmlFile);
//optional,
but recommended
//read
this -
http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
doc.getDocumentElement().normalize();
System.out.println("Root
element :" + doc.getDocumentElement().getNodeName());
NodeList
nList = doc.getElementsByTagName("staff");
System.out.println("----------------------------");
for
(int temp = 0; temp < nList.getLength(); temp++) {
Node
nNode = nList.item(temp);
System.out.println("\nCurrent
Element :" + nNode.getNodeName());
if
(nNode.getNodeType() == Node.ELEMENT_NODE) {
Element
eElement = (Element) nNode;
System.out.println("Staff
id : " + eElement.getAttribute("id"));
System.out.println("First
Name : " + eElement.getElementsByTagName("firstname").item(0).getTextContent());
System.out.println("Last
Name : " +
eElement.getElementsByTagName("lastname").item(0).getTextContent());
System.out.println("Nick
Name : " + eElement.getElementsByTagName("nickname").item(0).getTextContent());
System.out.println("Salary
: " +
eElement.getElementsByTagName("salary").item(0).getTextContent());
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
Staff.xml
<?xml version="1.0"?>
<company>
<staff
id="1001">
<firstname>Veera</firstname>
<lastname>Roy</lastname>
<nickname>Veera</nickname>
<salary>100000</salary>
</staff>
<staff
id="2001">
<firstname>Sirisha</firstname>
<lastname>Rao</lastname>
<nickname>Siri</nickname>
<salary>200000</salary>
</staff>
</company>
Execution steps
ii) SAX parser
ReadXMLFile1.java
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class ReadXMLFile1 {
public static void main(String argv[]) {
try {
SAXParserFactory
factory = SAXParserFactory.newInstance();
SAXParser
saxParser = factory.newSAXParser();
DefaultHandler
handler = new DefaultHandler() {
boolean
bfname = false;
boolean
blname = false;
boolean
bnname = false;
boolean
bsalary = false;
public
void startElement(String uri, String localName,String qName,
Attributes attributes) throws
SAXException {
System.out.println("Start
Element :" + qName);
if
(qName.equalsIgnoreCase("FIRSTNAME")) {
bfname
= true;
}
if
(qName.equalsIgnoreCase("LASTNAME")) {
blname
= true;
}
if
(qName.equalsIgnoreCase("NICKNAME")) {
bnname
= true;
}
if
(qName.equalsIgnoreCase("SALARY")) {
bsalary
= true;
}
}
public
void endElement(String uri, String localName,
String
qName) throws SAXException {
System.out.println("End
Element :" + qName);
}
public
void characters(char ch[], int start, int length) throws SAXException {
if
(bfname) {
System.out.println("First
Name : " + new String(ch, start, length));
bfname
= false;
}
if
(blname) {
System.out.println("Last
Name : " + new String(ch, start, length));
blname
= false;
}
if
(bnname) {
System.out.println("Nick
Name : " + new String(ch, start, length));
bnname
= false;
}
if
(bsalary) {
System.out.println("Salary
: " + new String(ch, start, length));
bsalary
= false;
}
}
};
saxParser.parse("E:/Technical Stuff/2014/webtech/file.xml",
handler);
} catch (Exception e) {
e.printStackTrace();
}
}
}
// Java Document
File.xml
<?xml version="1.0"?>
<class>
<student rollno="393">
<firstname>dinkar</firstname>
<lastname>kad</lastname>
<nickname>dinkar</nickname>
<salary>85</salary>
</student>
<student rollno="493">
<firstname>Vaneet</firstname>
<lastname>Gupta</lastname>
<nickname>vinni</nickname>
<salary>95</salary>
</student>
<student rollno="593">
<firstname>jasvir</firstname>
<lastname>singn</lastname>
<nickname>jazz</nickname>
<salary>90</salary>
</student>
</class>
Output:
6)
Implement the following web applications using
a)
PHP
b)Servlets
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 the data matches, a successful login page
is returned otherwise a failure message is shown to the user. Using PHP
Step
1: Download and Install XAMP in the Computer
Step
2: Start Apache and Mysql server and database.
Step 3: Check whether the XAMP sever
is running or not
Type http://localhost
in the address bar in any browser
Step 4: Go to the following path
C:\xampp\htdocs
Create a folder of your choice and
save programs in that folder
Step 5: create database program should
be executed
db_create.php
<html>
<body>
<?php
$dbhost = 'localhost:3306';
$dbuser = 'root';
$dbpass = '';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysqli_error());
}
echo 'Connected successfully';
mysqli_close($conn);
?>
</body>
</html>
insertDB.php
<?php
$con =
mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db",
$con);
$sql="INSERT INTO Persons
(username, pword)
VALUES
('$_POST[username]','$_POST[pword]')";
//$select= "select * from login
where username = '".$_POST['username']."' and
pword='".$_POST['pword']."'";
//$select= "select * from login
where username = '$_POST[username]' and pword='$_POST[pword]'";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con)
?>
Login.html
<html>
<head>
<title>
Login Page </title>
</head>
<body bgcolor=”#bfff00”>
<center>
<br><br><br>
<h2>Login Page</h2>
<fieldset
style="width:250px">
<legend>Enter login details</legend>
<form method="POST"
action="validate.php">
<br/>Username: <input
type="text" name="username"
id="username"><br/>
<br>Password: <input
type="password" name="pword"
id="pword"><br/>
<br/>
<button
type="submit">Submit</button><br/> <a
href="register.html">click to register </a>
</center>
</form>
</fieldset>
</body>
</html>
Validate.php
<?php
$con =
mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db",
$con);
//$query="select * from persons
where username = '$_POST[username]' and pword='$_POST[pword]'";
//echo $query;
//exit;
$result = mysql_query("select *
from persons where username = '$_POST[username]' and
pword='$_POST[pword]'",$con);
if($result)
{
$count=mysql_num_rows($result);
if ($count>0)
{
header('Location:
/DB-connect/link/main.html');
echo
"user found";
}
else
{
header('Location: /DB-connect/link/error.html');
echo "not registered";
//break;
}
}
else
{
echo "not registered";
}
mysql_close($con);
?>
Main.html
<html>
<head>
</head>
<body bgcolor="#00bfff"
background="xyz.jpg">
<center><h1><font color="black">
<i>Welcome to My Webpage</i></h1>
<br><br><br>
<p><h4>
</h4></p></font>
</center>
</body>
</html>
Error.html
<html>
<head>
</head>
<body
bgcolor="#00bfff">
<center><h2><font
color="red"> <i>Error found</i></h2>
<br><br><br>
<p><h4> Enter correct
username and password</h4></p></font>
<a
href="/DB-connect/Login.html"> Click here to continue </a>
</center>
</body>
</html>
register.html
<html>
<head>
</head>
<body>
<fieldset width="2">
<legend>
Registration Form</legend>
<form
method = "post" action = "insertDB.php">
<span style = "color:
blue">
Please fill out the fields
below.<br />
</span>
<br/>Username: <input
type="text" name="username"
id="username"><br/>
<br>Password: <input
type="password" name="pword"
id="pword"><br/>
<br/>
<button
type="submit">Submit</button><br/>
</form>
</fieldset>
</body>
</html>
Error page when user name and password
are invalid
Check the Database for table values
ii) A Simple calculator web
application that takes two numbers and an operator(+,-,/,*,%) from a HTML page
and returns the result page with the operation performed on the operands.
<html>
<head>
<style>
.k{
background-color:blue;
left:500px;
top:200px;
border:thin
groove;
width:500px;
position:fixed;
height:300px;
text-align:center;
}
</style>
</head>
<body>
<div
class="k">
<p
align="center"><font color="yellow">
<h2>Calculator </h2></font></p>
<form
name="calci">
<input
type="text" name="txt"><br><br/>
<input
type="button" value="1"
onclick="document.calci.txt.value+='1'">
<input
type="button" value="2"
onclick="document.calci.txt.value+='2'">
<input
type="button" value="3"
onclick="document.calci.txt.value+='3'">
<input
type="button" value="+" onclick="document.calci.txt.value+='+'"><br/><br/>
<input
type="button" value="4"
onclick="document.calci.txt.value+='4'">
<input
type="button" value="5"
onclick="document.calci.txt.value+='5'">
<input
type="button" value="6"
onclick="document.calci.txt.value+='6'">
<input
type="button" value="-"
onclick="document.calci.txt.value+='-'"><br/><br/>
<input
type="button" value="7"
onclick="document.calci.txt.value+='7'">
<input
type="button" value="8"
onclick="document.calci.txt.value+='8'">
<input
type="button" value="9"
onclick="document.calci.txt.value+='9'">
<input
type="button" value="*"
onclick="document.calci.txt.value+='*'"><br/><br/>
<input
type="button" value="/"
onclick="document.calci.txt.value+='/'">
<input
type="button" value="0" onclick="document.calci.txt.value+='0">
<input
type="reset" value="C">
<input
type="button" value="="
onclick="document.calci.txt.value=eval(document.calci.txt.value)">
</div>
</body>
</html>
Output:
iii) Modify the above program such that it
stores each query in database and checks the database first for 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.
<html>
<body>
<h2>Welcome</h2>
<fieldset
style="width:280px">
<legend>Calculator</legend>
<form method="post">
<br/>Number 1: <input
type="text" name="num1" id="num1"><br/>
<br/>Number 2: <input type="text"
name="num2" id="num2"><br/>
<br/>Operation:
+ <input type="radio"
name="Operation" id="add" value="+"
checked="checked">
- <input type="radio"
name="Operation" id="sub" value="-">
* <input type="radio"
name="Operation" id="mul" value="*">
/ <input type="radio"
name="Operation" id="div" value="/">
<br/><br/>
<input type="submit"
name="submit" id="submit" />
<br/>
</form>
</fieldset>
<?php
if($_POST)
{
echo '<fieldset
style="width:280px">
<legend>Result</legend>';
if($_POST["num1"]==""
|| $_POST["num2"]=="")
{
if($_POST["num1"]=="")
echo
"Please enter Number 1 <br/>";
if($_POST["num2"]=="")
echo
"Please enter Number 2 <br/>";
}else
if($_POST["num2"]==0)
{
echo
"Number 2 should not be Zero. this is divided by zero error.";
}
else
{
echo
$_POST["num1"] . " " . $_POST["Operation"] .
" " . $_POST["num2"] . " = ";
$servername
= "localhost";
$username
= "root";
$password
= "";
$dbname
= "calc";
//
Create connection
$conn
= new mysqli($servername, $username, $password, $dbname);
//
Check connection
if
($conn->connect_error) {
die("Connection
failed: " . $conn->connect_error);
}
$sql
= "SELECT result FROM operations where number1=".$_POST["num1"]."
and number2=".$_POST["num2"]." and
operation='".$_POST["Operation"]."'" ;
$result
= $conn->query($sql);
if
($result->num_rows > 0) {
//
output data of each row
while($row
= $result->fetch_assoc()) {
echo
$row["result"];
}
echo
"<br/> Result is displayed from database";
}
else {
$resultVal=0;
switch($_POST["Operation"])
{
case
"-":
echo $resultVal=$_POST["num1"] -
$_POST["num2"];
break;
case
"*":
echo $resultVal=$_POST["num1"] * $_POST["num2"];
break;
case
"/":
echo $resultVal=$_POST["num1"] /
$_POST["num2"];
break;
default:
echo $resultVal=$_POST["num1"] +
$_POST["num2"];
break;
}
$sql
= "INSERT INTO `employee`.`operations`
(`number1`,
`number2`,
`operation`,
`result`)
VALUES
(".$_POST["num1"].",
".$_POST["num2"].",
'".$_POST["Operation"]."',
".$resultVal.");";
$result
= $conn->query($sql);
echo
"<br/> This is first time operation is queried.";
}
$conn->close();
}
echo
"</fieldset>";
}
?>
</body>
</html>
Output:
Validations performed on above program
Database
iv) A web application takes name as input
and on submit it shows a hello
<name> page where <name> is taken form a request . Its shows a
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 duration of usage (hint : use session to store name and time)
login.php
<html>
<body>
<script>
function validate() {
var usrName=
document.getElementById("username").value;
if (usrName.length == 0) {
alert("Please enter your Name.");
return false;
}
else{
return true;
}
return
false;
}
</script>
<h2>Welcome</h2>
<fieldset
style="width:250px">
<legend>Enter Your Name</legend>
<form method="POST"
action="dashboard.php">
<br/>Name: <input
type="text" name="username"
id="username"><br/>
<br/>
<button type="submit"
onclick="return validate()">Submit</button><br/>
</form>
</fieldset>
</body>
</html>
Dashboard.php
<html>
<body bgcolor="#F08080">
<div width="100%">
<div style="width:300px;float:left;">
<?php
session_start();
if($_POST)
{
echo "Hello ";
echo
$_SESSION["Username"]=$_POST["username"];
}
?>
</div>
<div
style="width:300px;float:right;">
<?php
$_SESSION["StartDate"]=
date("Y-m-d h:i:sa");
echo date("d-m-Y h:i:sa");
?>
<button
onclick="window.location.href='logout.php'">Logout</button>
</div>
</div>
</body>
</html>
Logout.php
<html>
<body bgcolor="orange">
<div width="100%">
<?php
session_start();
if($_SESSION)
{
echo "Thank you ";
echo $_SESSION["Username"];
$d=strtotime($_SESSION["StartDate"]);
echo "<br/>Your session time is
";
$diff=date_diff(date_create(date("Y-m-d
h:i:sa")),date_create(date("Y-m-d h:i:sa",$d)));
echo " Hours : ". $diff->h .
" Minutes: ". $diff->m . " Seconds ".$diff->s;
session_destroy();
}else
{
echo
"Sorry no sessions found";
}
?>
<br/>
<br/>
<button
onclick="window.location.href='login.php'">Return to Login
Page</button>
</div>
</body>
</html>
v) 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 “helloo <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.
Sign.html
<html>
<head>
<script type="">
</script>
</head>
<body align="center">
<fieldset
style="width:300px">
<legend> <h3>Sign in</h3>
</legend>
<form name="login"
method="post" action="validate.php">
<br/>
Name
: <input type="text"
name="nam"><br/><br/>
Age :
<input
type="number" name="age"><br/><br/>
<input
type="submit" value="sign in">
</form>
</fieldset>
</body>
</html>
Validate.php
<html>
<head>
<?php
$name= $_POST['nam'];
$age=$_POST['age'];
if
($age>18)
{
echo
'<h2> <font color=green>Welcome '.$name.' to the
website</font></h2>';
}
else
{
echo
'<h2> <font color=red>Hello '.$name.' You are not authorized.</font></h2>';
}
?>
</head>
</html>