CSE III-II SEM (Web Technologies Lab Manual)
CSE III-II SEM (Web Technologies Lab Manual)
LABORATORY MANUAL
B.TECH
(III YEAR – II SEM)
(2016-17)
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
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
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.
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.
PROGRAM-1.1 DATE:
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:
Name: JAVA_HOME
Value: C:\jdk
Name: JAVA_HOME
Value: install_dir/common/lib/servlet-api.jar
<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.
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:
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.
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.
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.
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.
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
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.
Aim: Install PHP and configure to work with Apache Web Server and MySQL.
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.
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:
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.
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.
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.
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;
}
numLength = rev.length;
var word = new Array();
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();
OUTPUT:
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)";>
OUTPUT:
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"> </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(',');
OUTPUT:
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>
<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>
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 :      "+uid)
document.write("<br>User Name : "+userName);
document.write("<br>Address :       "+Address);
document.write("<br>Phone no :      "+phone);
document.write("<br>E - Mail :       "+email);
flag =1;
break;
}
}
if(flag==0)
{
alert("InValid User");
}
}
</script>
</head>
<body>
<center>
<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:
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.
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");
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 ");
//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:
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");
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>
</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>
OUTPUT:
RESULT:
Thus the user authentication is carried out for four users by using both cookies and
getInitParameters successfully.
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);
} }
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;
if(rs.next())
{
{
out.println(" successfully logged in");
}
else
out.println(" password is invalid, failed login");
}
}
web.xml
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
</web-app>
OUTPUT:
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.
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:
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.*;
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>
OUTPUT:
}
?>
<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">
</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>
OUTPUT 1:
OUTPUT 2:
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"));
</form>
</body>
</html>
4) Now press “CTRL”+F11, you will get the following screen. Click on “FINISH
BUTTON”, selecting WEB SERVER.
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);
}
%>
<SCRIPT LANGUAGE="JavaScript">
function showTime()
{
var name = document.form1.tname.value;
document.write("Hello " + name);
document.form1.pName.value = name;
document.form1.logtime.value = loggedInTime;
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);
document.location.href = "x.jsp";
}
</SCRIPT>
</body>
</html>
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:
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>
Output1:
mrcet 18 Submit
Name: Age:
Output2:
mrcet 16 Submit
Name: Age:
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>
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);
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>
OUTPUT:
RESULT:
Thus a table is created and the details are entered into the table using jdbc from the
registration form successfully.
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> </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> </td>
<td> </td>
</tr> <tr>
<td colspan="2" align="center"><input type="submit"
value="LogIN"/></td>
</tr>
</table> </form> </td>
</tr> </table>
</body> </html>
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>
OUTPUT:
RESULT:
The user is authenticated when he submits the login form using the user name and
password from the database.
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();
} }
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
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>
OUTPUT: