You are on page 1of 63

lOMoARcPSD|17304208

Lab Mannual Web Tech - LABMANUAL OF COMPUTER


NETWORKS
bsdfhsdfksdfksbfks fkjashifd jashda dkajahr
Computer Networks Lab (Dr. A.P.J. Abdul Kalam Technical University)

Studocu is not sponsored or endorsed by any college or university


Downloaded by Arpit Pandey (arpit1111k@gmail.com)
lOMoARcPSD|17304208

MEERUT INSTITUTE OF ENGINEERING & TECHNOLOGY, MEERUT

N.H. 58, Delhi-Roorkee Highway, Baghpat Road Bypass Crossing, Meerut-250005

Department of Computer Science and Engineering

B. Tech. (Session 2020–21)

Lab Manual

WEB TECHNOLOGY LAB


KCS-652

Prepared by: Tanu


(1806813058)

Downloaded by Arpit Pandey (arpit1111k@gmail.com)


lOMoARcPSD|17304208

INDEX
S.No. Name of the Date Page No. Signature of
Experiment Concerned Faculty
1 Write HTML/Java 16/4/2021
scripts to display your
CV in navigator, your
Institute website,
Department Website and
Tutorial website for
specific subject.

2 Write an HTML 23/04/2021


program to design an
entry form of student
details and send it to
store at database server
like SQL, Oracle or MS
Access.

3 Write programs using 30/4/2021


Java script for Web Page
to display browsers
information.
4 Write a Java applet to 7/5/2021
display the Application
Program screen i.e.
calculator and other.

5 Writing program in 14/05/2021


XML for creation of
DTD, which specifies
set of rules. Create a
style sheet in CSS/ XSL
& display the document
in internet explorer.

6 Program to illustrate 21/05/2021


JDBC connectivity.
Program for maintaining
database by sending
queries. Design and
implement a simple
servlet book query with
the help of JDBC &

Downloaded by Arpit Pandey (arpit1111k@gmail.com)


lOMoARcPSD|17304208

SQL.
Create MS Access
Database, Create on
ODBC link, Compile &
execute JAVA JDVC
Socket.

7 Install TOMCAT web 28/05/2021


server and APACHE.
Access the above
developed static web
pages for books web
site, using these servers
by putting the web pages
developed.

8 Assume four users 4/6/2021


user1, user2, user3 and
user4 having the
passwords pwd1, pwd2,
pwd3 and pwd4
respectively. Write a
servlet for doing the
following. Create a
Cookie and add these
four user id’s and
passwords to this
Cookie. 2. Read the user
id and passwords
entered in the Login
form and authenticate
with the values available
in the cookies.

9 Install a database 11/6/2021


(MySQL or Oracle).
Create a table which
should contain at least
the following fields:
name, password, email-
id, phone number Write
a java
program/servlet/JSP to
connect to that database
and extract data from the
tables and display them.

Downloaded by Arpit Pandey (arpit1111k@gmail.com)


lOMoARcPSD|17304208

Insert the details of the


users who register with
the web site, whenever a
new user clicks the
submit button in the
registration page.

10 Write a JSP which insert 18/06/2021


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

Downloaded by Arpit Pandey (arpit1111k@gmail.com)


lOMoARcPSD|17304208

PROGRAM 1

Objective: Write HTML/Java scripts to display your CV in navigator, your Institute


website, Department Website and Tutorial website for specific subject.

Theory:
Introduction:

HTML stands for Hyper Text Markup Language. HTML is the computer language that is used to
create documents for display on the Web. Many editors exist to create Web Pages – Word, Front
Page, and Dream Weaver are just a few. Nevertheless, each of these software programs (editors)
performs the exact same task – they all generate HTML language.
The HTML language consists of a series of HTML tags. Learning HTML involves finding out
what tags are used to mark the parts of a document and how these tags are used in creating an
HTML document.
Tags are instructions that tell your browser what to show on a Web page. They break up your
document into basic sections. All tags start with a < (left bracket) and end with a > (right
bracket).

Basic HTML Tags

<HTML> </HTML>
This tag tells your browser that the file contains HTML-coded information. All html tags must be
placed between the open <HTML> tag and the closed tag </HTML> The file extension .html
also indicates the document is an HTML document. All html documents MUST be saved with
the .html file extension.

<HEAD> </HEAD>
The head tag identifies the first part of your HTML-coded document. The title tag (explained
below) must be places between the open <HEAD> tag and the closed </HEAD> tag.

<BODY> </BODY>
The largest part of your HTML document is the body, which contains the content of your
document (displayed within the text area of your browser window). All HTML tags that pertain
to the body of your HTML document must be places between the open <BODY> tag and the
closed </BODY> tag. The tag has attributes which you can use to set the colors of your
background, text, links, and also to include your own background image. They are as follows:
• BGCOLOR="white" Sets the background color (other color names: red, black, blue
etc)
• TEXT="black" Sets the body text color
• LINK="blue" Sets the unvisited hypertext links
• VLINK ="purple" Sets the visited hypertext links
• ALINK="red" Sets the active hypertext links (the color of the hypertext link when
you have your mouse button depressed)

Downloaded by Arpit Pandey (arpit1111k@gmail.com)


lOMoARcPSD|17304208

• BACKGROUND Let you use an image as the background <background=


Body attributes are used as part of the open <body> tag. For example:

<BODY BGCOLOR = "white" TEXT = "black" LINK = "blue" VLINK = "purple" ALINK =
"red">

Code :
<html>
<head>
<title>RESUME | JOHN DOE</title>
</head>
<body>
<!-- BEGIN DIV FOR OVERALL BOX -->
<div id="resume">
<!-- THIS DIV CENTERS OUR HEADING -->
<h1>John Doe</h1>
<h2>4242 Ghila Road</h2>
<h2>Tucson, AZ 85701</h2>
<br />
<!-- END CENTERING DIV -->
</div>
<h2>Profile</h2>
<p>
Desires a resident position in the Bastyr University Acupuncture and Oriental
Medicine Residency Program. Able to be effective in a practice of any size.
Draw on experience with a range of patient issues, including additional work
in women and children’s care. Interested in health education for homeless.
Strong desire to contribute to the success of a program through an ability to
initiate and maintain relationships. Creative developer and presenter of
educational information.
</p>
<br />
<h2>Education</h2>
<h3>Masters of Acupuncture and Oriental Medicine,
<br />
Graduating June 2003</h3>
<p>
Bastyr University, Kenmore, WA 1999
</p>
<ul>
<li>
Completing an accredited program of coursework and supervised practice in Acupuncture and
Oriental Medicine. Extensive exposure to issues involving
women and children.
</li>
</ul>

Downloaded by Arpit Pandey (arpit1111k@gmail.com)


lOMoARcPSD|17304208

<h3>Research Project</h3>
<ul>
<li>
Assisted the primary investigator in a double blind, randomized controlled
trail conducted at the Bastyr Center for Natural Health that evaluated the
effectiveness of Chinese herbs towards the control of Diabetes Mellitus in
post-menopausal women. Co-authored the research report that has been
submitted for publication to the Journal of Traditional Chinese Medicine.
</li>
</ul>
<h3>Bachelor of Science, Zoology</h3>
<p>
Miami University, Oxford, OH 1991 - 1995
</p>
<ul>
<li>
Participated in a community service project to increase citizen participation
in a cleanup campaign.
</li>
<li>
Served as project leader in a fund raising project sponsored by the University
Student Council towards helping homeless youth return back to school.
</li>
</ul>
<br />
<h2>Related Experience</h2>
<h3>Bastyr University, Kenmore, WA 1999-present</h3> <p>
Teaching Assistant
</p>
<ul>
<li>
Assists professor in the Anatomy & Physiology class.
</li>
<li>
Answers questions and demonstrate as needed.
</li>
</ul>
<h3>Kenmore Youth Ministry, Kenmore, WA 2000-2001</h3>
<p>
Camp Group Leader
</p>
<ul>
<li>
Participated in community youth group activities.
</li>
<li>

Downloaded by Arpit Pandey (arpit1111k@gmail.com)


lOMoARcPSD|17304208

Developed activity programs now utilized by the youth ministry in helping


Children improve reading skills.
</li>
</ul>
<h3>Franciscan Care Center Nursing Home,
<br />
Seattle, WA 1999 - 2000 </h3>
<p>
Volunteer Recreation Worker
</p>
<ul>
<li>
Provided social support to patients by reading to them, writing letters , and visiting with them.
</li>
<li>
Formed friendships which enriched lives of patients
</li>
</ul> <! -- THIS DIV CENTERS OUR LINKS -->
<div id="bottom">
<p>
<a href="index.html">RESUME HOME</a> | <a href="#">SIMPLE RESUME</a> | <a
href="resume.html">COMPLEX RESUME</a> | <a href="code.html" target="_blank">SEE
HTML</a> | <a href="resume.css" target="_blank">SEE CSS</a>
</p>
</div>
<!-- END CENTERING LINKS -->
<!-- END DIV FOR OVERALL BOX -->
</div>
</body>
</html>

Output:

Downloaded by Arpit Pandey (arpit1111k@gmail.com)


lOMoARcPSD|17304208

PROGRAM-2

Objective: Write an HTML program to design an entry form of student details and send it
to store at database server like SQL, Oracle or MS Access.

Theory:

HTML Forms
HTML Forms are required to collect different kinds of user inputs, such as contact details like
name, email address, phone numbers, or details like credit card information, etc.
Forms contain special elements called controls like inputbox, checkboxes, radio-buttons, submit
buttons, etc. Users generally complete a form by modifying its controls e.g. entering text,
selecting items, etc. and submitting this form to a web server for processing.
The <form> tag is used to create an HTML form. Here's a simple example of a login form:

Input Element

This is the most commonly used element within HTML forms.It allows you to specify various
types of user input fields, depending on the type attribute. An input element can be of type text
field, checkbox, password field, radio button, submit button, reset button, etc. and several new
input types introduced in HTML5.
The most used input types are described below.

Text Fields Text fields are one line areas that allow the user to input text.Single-line text input
controls are created using an <input> element, whose type attribute has a value of text. Here's an
example of a single-line text input used to take username:

Password Field
Password fields are similar to text fields. The only difference is; characters in a password field
are masked i.e. shown as asterisks or dots. This is to prevent others from reading the password on
the screen. This is also a single-line text input controls created using an <input> element whose
type attribute has a value of password.
Here's an example of a single-line password input used to take user password:
Radio Buttons:

Radio buttons are used to let the user select exactly one option from a pre-defined set of options.
It is created using an <input> element whose type attribute has a value of radio.
Checkboxes
Checkboxes allows the user to select one or more option from a pre-defined set of options. It is
created using an <input> element whose type attribute has a value of checkbox.

Downloaded by Arpit Pandey (arpit1111k@gmail.com)


lOMoARcPSD|17304208

File Select box

The file fields allow a user to browse for a local file and send it as an attachment to the form
data. It normally rendered as a text box with a button that enables the user to browse for a file.
However, the user can also type the path and name of the file in the text box.This is also created
using an <input> element, whose type attribute value is set to file.
Textarea

Textarea is a multiple-line text input control that allows a user to enter more than one line of text.
Multi-line text input controls are created using an <textarea> element.
Select Boxes
A select box is a drop down list of options that allows user to select one or more option from a
pull-down list of options. Select box is created using the <select> element and <option> element.
The option elements within the <select> element define each list item.
Submit and Reset Buttons

A submit button is used to send the form data to a web server. When submit button is clicked the
form data is sent to the file specified in the form's action attribute to process the submitted data.
A reset button resets all the forms control to default values.
Most frequently used form attributes are:

Attribute Description

Name The name of the form.


action URL of the program that processes the information submitted via form.
The HTTP method that the browser uses to submit the form. Possible values are get and
method
post.
target A name or keyword indicating the target page where the result of the script will be displayed
Code:

<html>
<head>
<script type="text/javascript" src="validate.js" ></script>
</head>
<body bgcolor="aqua" bolder="5">
<form action="register.jsp" name="StudentRegistration" method=”post”>
<table cellpadding="2" width="50%" border="10" align="center"cellspacing="2">
<tr>
<td colspan=2>
<center><font size=4><b>Student Registration Form</b></font></center>
</td>

Downloaded by Arpit Pandey (arpit1111k@gmail.com)


lOMoARcPSD|17304208

</tr>
<tr>
<td>Name</td>
<td><input type=text name=textnames id="textname" size="30"></td>
</tr>
<tr>
<td>Father Name</td>
<td><input type="text" name="fathername" id="fathername"
size="30"></td>
</tr>
<tr>
<td>Postal Address</td>
<td><input type="text" name="paddress" id="paddress" size="30"></td>
</tr>
<tr>
<td>Personal Address</td>
<td><input type="text" name="personaladdress"
id="personaladdress" size="30"></td>
</tr>
<tr>
<td>Sex</td>
<td><input type="radio" name="sex" value="male" size="10">Male
<input type="radio" name="sex" value="Female" size="10">Female</td>
</tr>
<tr>
<td>City</td>
<td><select name="City">
<option value="-1" selected>select..</option>
<option value="New Delhi">NEW DELHI</option>
<option value="Mumbai">MUMBAI</option>
<option value="Goa">GOA</option>
<option value="Patna">PATNA</option>
</select></td>
</tr>
<tr>
<td>Course</td>
<td><select name="Course">
<option value="-1" selected>select..</option>
<option value="B.Tech">B.TECH</option>
<option value="MCA">MCA</option>

Downloaded by Arpit Pandey (arpit1111k@gmail.com)


lOMoARcPSD|17304208

<option value="MBA">MBA</option>
<option value="BCA">BCA</option>
</select></td>
</tr>
<tr>
<td>District</td>
<td><select name="District">
<option value="-1" selected>select..</option>
<option value="Nalanda">NALANDA</option>
<option value="UP">UP</option>
<option value="Goa">GOA</option>
<option value="Patna">PATNA</option>
</select></td>
</tr>
<tr>
<td>State</td>
<td><select Name="State">
<option value="-1" selected>select..</option>
<option value="New Delhi">NEW DELHI</option>
<option value="Mumbai">MUMBAI</option>
<option value="Goa">GOA</option>
<option value="Bihar">BIHAR</option>
</select></td>
</tr>
<tr>
<td>PinCode</td>
<td><input type="text" name="pincode" id="pincode" size="30"></td>
</tr>
<tr>
<td>EmailId</td>
<td><input type="text" name="emailid" id="emailid" size="30"></td>
</tr>
<tr>
<td>DOB</td>
<td><input type="text" name="dob" id="dob" size="30"></td>
</tr>
<tr>
<td>MobileNo</td>
<td><input type="text" name="mobileno" id="mobileno" size="30"></td>
</tr>

Downloaded by Arpit Pandey (arpit1111k@gmail.com)


lOMoARcPSD|17304208

<tr>
<td><input type="reset"></td>
<td colspan="2"><input type="submit" value="Submit Form" /></td>
</tr>
</table>
</form><br><br>
<h1><a href="MainPage.html">Back</a></h1>
</body>
</html>

OUTPUT:

Downloaded by Arpit Pandey (arpit1111k@gmail.com)


lOMoARcPSD|17304208

PROGRAM 3

Objective: Write programs using Java script for Web Page to display browsers
information.

Theory:

The navigator object contains information about the browser.

Navigator Object Properties


Property Description

appCodeName Returns the code name of the browser

appName Returns the name of the browser

appVersion Returns the version information of the browser

cookieEnabled Determines whether cookies are enabled in the browser

geolocation Returns a Geolocation object that can be used to locate the user's position

language Returns the language of the browser

onLine Determines whether the browser is online

platform Returns for which platform the browser is compiled

product Returns the engine name of the browser

userAgent Returns the user-agent header sent by the browser to the server

Code:

<html xmlns="http://www.w3.org/1999/xhtml" >


<head runat="server">
<title>Browser Information</title>

<script language=javascript>
function show()
{

document.write("Name "+navigator.appName+"<br>");
document.write("Version "+navigator.appVersion +"<br>");
document.write("Codename " +navigator.appCodeName +"<br>");
document.write("Cookie enable"+navigator.cookieEnabled +"<br>");
document.write("Java Enable"+navigator.javaEnabled +"<br>");

Downloaded by Arpit Pandey (arpit1111k@gmail.com)


lOMoARcPSD|17304208

document.write("Mime type"+navigator.mimeTypes +"<br>");


document.write("Platform"+navigator.platform +"<br>");
document.write("Plug ins"+navigator.plugins +"<br>");
document.write("System Language"+navigator.systemLanguage +"<br>");
document.write("User language"+navigator.userAgent +"<br>");
document.write("User Agent"+navigator.userAgent +"<br>");

</script>
</head>
<body>
<form id="form1">
<div>
<input id="Button1" type="button" value="Click me" onclick="show()" />

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

OUTPUT :

for Mozilla browse:

Name Netscape
Version 5.0 (X11)
Codename Mozilla
Cookie enabletrue
Java Enablefunction javaEnabled() { [native code] }
Mime type[object MimeTypeArray]
PlatformLinux i686
Plug ins[object PluginArray]
System Languageundefined
User languageMozilla/5.0 (X11; Ubuntu; Linux i686; rv:59.0) Gecko/20100101 Firefox/59.0
User AgentMozilla/5.0 (X11; Ubuntu; Linux i686; rv:59.0) Gecko/20100101 Firefox/59.0

OUTPUT :

For Chromium browser:

Name Netscape
Version 5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu

Downloaded by Arpit Pandey (arpit1111k@gmail.com)


lOMoARcPSD|17304208

Chromium/64.0.3282.167 Chrome/64.0.3282.167 Safari/537.36


Codename Mozilla
Cookie enabletrue
Java Enablefunction javaEnabled() { [native code] }
Mime type[object MimeTypeArray]
PlatformLinux i686
Plug ins[object PluginArray]
System Languageundefined
User languageMozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko)
Ubuntu Chromium/64.0.3282.167 Chrome/64.0.3282.167 Safari/537.36
User AgentMozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu
Chromium/64.0.3282.167 Chrome/64.0.3282.167 Safari/537.36

Downloaded by Arpit Pandey (arpit1111k@gmail.com)


lOMoARcPSD|17304208

PROGRAM 4

Objective: Write a Java applet to display the Application Program screen i.e. calculator
and other.

Theory

:Applet is a special type of program that is embedded in the web page to generate the dynamic
content. It runs inside the browser and works at client side.

There are many advantages of applet. They are as follows


a)It works at client side so less response time
b)Secured
c)It can be executed by browsers running under many platforms, including Linux, Windows,
Mac Os etc.

1) Code for Calculator:

import java.awt.*;
import java.awt.event.*;
import java.applet.*;

/*
<applet code="Cal" width=300 height=300>
</applet>
*/

public class Cal extends Applet


implements ActionListener
{
String msg=" ";
int v1,v2,result;
TextField t1;
Button b[]=new Button[10];
Button add,sub,mul,div,clear,mod,EQ;
char OP;
public void init()
{
Color k=new Color(120,89,90);
setBackground(k);
t1=new TextField(10);
GridLayout gl=new GridLayout(4,5);
setLayout(gl);
for(int i=0;i<10;i++)
{

Downloaded by Arpit Pandey (arpit1111k@gmail.com)


lOMoARcPSD|17304208

b[i]=new Button(""+i);
}
add=new Button("add");
sub=new Button("sub");
mul=new Button("mul");
div=new Button("div");
mod=new Button("mod");
clear=new Button("clear");
EQ=new Button("EQ");
t1.addActionListener(this);
add(t1);
for(int i=0;i<10;i++)
{
add(b[i]);
}
add(add);
add(sub);
add(mul);
add(div);
add(mod);
add(clear);
add(EQ);
for(int i=0;i<10;i++)
{
b[i].addActionListener(this);
}
add.addActionListener(this);
sub.addActionListener(this);
mul.addActionListener(this);
div.addActionListener(this);
mod.addActionListener(this);
clear.addActionListener(this);
EQ.addActionListener(this);
}

public void actionPerformed(ActionEvent ae)


{
String str=ae.getActionCommand();
char ch=str.charAt(0);
if ( Character.isDigit(ch))
t1.setText(t1.getText()+str);
else
if(str.equals("add"))
{
v1=Integer.parseInt(t1.getText());
OP='+';

Downloaded by Arpit Pandey (arpit1111k@gmail.com)


lOMoARcPSD|17304208

t1.setText("");
}
else if(str.equals("sub"))
{
v1=Integer.parseInt(t1.getText());
OP='-';
t1.setText("");
}
else if(str.equals("mul"))
{
v1=Integer.parseInt(t1.getText());
OP='*';
t1.setText("");
}
else if(str.equals("div"))
{
v1=Integer.parseInt(t1.getText());
OP='/';
t1.setText("");
}
else if(str.equals("mod"))
{
v1=Integer.parseInt(t1.getText());
OP='%';
t1.setText("");
}
if(str.equals("EQ"))
{
v2=Integer.parseInt(t1.getText());
if(OP=='+')
result=v1+v2;
else if(OP=='-')
result=v1-v2;
else if(OP=='*')
result=v1*v2;
else if(OP=='/')
result=v1/v2;
else if(OP=='%')
result=v1%v2;
t1.setText(""+result);
}
if(str.equals("clear"))
{
t1.setText("");
}
}}

Downloaded by Arpit Pandey (arpit1111k@gmail.com)


lOMoARcPSD|17304208

OUTPUT:

Downloaded by Arpit Pandey (arpit1111k@gmail.com)


lOMoARcPSD|17304208

PROGRAM 5

Objective: Writing program in XML for creation of DTD, which specifies set of rules.
Create a style sheet in CSS/ XSL & display the document in internet explorer.

Theory:
XML Document Type Declaration, commonly known as DTD, is a way to describe precisely the
XML language. DTDs check the validity of structure and vocabulary of an XML document
against the grammatical rules of the appropriate XML language.
An XML document can be defined as:
• Well-formed: If the XML document adheres to all the general XML rules such as
tags must be properly nested, opening and closing tags must be balanced, and empty
tags must end with '/>', then it is called as well-formed.
OR
• Valid: An XML document said to be valid when it is not only well-formed, but it also
conforms to available DTD that specifies which tags it uses, what attributes those tags
can contain, and which tags can occur inside other tags, among other properties.
Types:
DTD can be classified on its declaration basis in the XML document, such as:

Internal DTD
• External DTD
When a DTD is declared within the file it is called Internal DTD and if it is declared in a
separate file it is called External DTD.
We will learn more about these in the chapter DTD Syntax

Syntax
Basic syntax of a DTD is as follows:
<!DOCTYPE element DTD identifier
[
declaration1
declaration2
........
]>

In the above syntax


• DTD starts with <!DOCTYPE> delimiter.
• An element tells the parser to parse the document from the specified root element.

Downloaded by Arpit Pandey (arpit1111k@gmail.com)


lOMoARcPSD|17304208

• DTD identifier is an identifier for the document type definition, which may be the
path to a file on the system or URL to a file on the internet. If the DTD is pointing to
external path, it is called external subset.
• The square brackets [ ] enclose an optional list of entity declarations called internal
subset.

Internal DTD
A DTD is referred to as an internal DTD if elements are declared within the XML files. To
reference it as internal DTD, standalone attribute in XML declaration must be set to yes. This
means the declaration works independent of external source.

Syntax
The syntax of internal DTD is as shown:

<!DOCTYPE root-element [element-declarations]>

where root-element is the name of root element and element-declarations is where you declare
the elements.

Example
Following is a simple example of internal DTD:
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<!DOCTYPE address [
<!ELEMENT address (name,company,phone)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT company (#PCDATA)>
<!ELEMENT phone (#PCDATA)>
]>
<address>
<name>Tanmay Patil</name>
<company>TutorialsPoint</company>
<phone>(011) 123-4567</phone>
</address>

External DTD
In external DTD elements are declared outside the XML file. They are accessed by specifying
the system attributes which may be either the legal .dtd file or a valid URL. To reference it as
external DTD, standalone attribute in the XML declaration must be set as no. This means,
declaration includes information from the external source.

Downloaded by Arpit Pandey (arpit1111k@gmail.com)


lOMoARcPSD|17304208

Syntax
Following is the syntax for external DTD:

<!DOCTYPE root-element SYSTEM "file-name">

where file-namen is the file with .dtd extension.

Example
The following example shows external DTD usage:
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<!DOCTYPE address SYSTEM "address.dtd">
<address>
<name>Tanmay Patil</name>
<company>TutorialsPoint</company>
<phone>(011) 123-4567</phone>
</address>

The content of the DTD file address.dtd are as shown:


<!ELEMENT address (name,company,phone)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT company (#PCDATA)>
<!ELEMENT phone (#PCDATA)>

Code:

1.XML :

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


<catalog>
<cd>
<title>Empire Burlesque</title>
<artist>Bob Dylan</artist>
<country>USA</country>
<company>Columbia</company>
<price>10.90</price>
<year>1985</year>
</cd>
<cd>
<title>Hide your heart</title>
<artist>Bonnie Tyler</artist>

Downloaded by Arpit Pandey (arpit1111k@gmail.com)


lOMoARcPSD|17304208

<country>UK</country>
<company>CBS Records</company>
<price>9.90</price>
<year>1988</year>
</cd>
</catalog>

XSL:
<html>
<body>
<h2>My CD Collection</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th style="text-align:left">Title</th>
<th style="text-align:left">Artist</th>
</tr>
<xsl:for-each select="catalog/cd">
<tr>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="artist"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>

Output:

In Internet Explorer

Title Artist
Empire Burlesque Bob Dylan
Hide your heart Bonnie Tyler

Downloaded by Arpit Pandey (arpit1111k@gmail.com)


lOMoARcPSD|17304208

2.XML

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


<!DOCTYPE note SYSTEM "Note.dtd">
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
DTD:
<!DOCTYPE note
[
<!ELEMENT note (to,from,heading,body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)><!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>
]>

OUTPUT:

Downloaded by Arpit Pandey (arpit1111k@gmail.com)


lOMoARcPSD|17304208

PROGRAM 6

Objective: Program to illustrate JDBC connectivity. Program for maintaining database by


sending queries. Design and implement a simple servlet book query with the help of JDBC
& SQL. Create MS Access Database, create on ODBC link, Compile & execute JAVA
JDVC Socket.

Theory:

Creating JDBC Application

There are following six steps involved in building a JDBC application −

• Import the packages: Requires that you include the packages containing the JDBC
classes needed for database programming. Most often, using import java.sql.* will
suffice.
• Register the JDBC driver: Requires that you initialize a driver so you can open a
communication channel with the database.
• Open a connection: Requires using the DriverManager.getConnection() method to
create a Connection object, which represents a physical connection with the database.
• Execute a query: Requires using an object of type Statement for building and submitting
an SQL statement to the database.
• Extract data from result set: Requires that you use the appropriate ResultSet.getXXX()
method to retrieve the data from the result set.
• Clean up the environment: Requires explicitly closing all database resources versus
relying on the JVM's garbage collection.

CODE:

//STEP 1. Import required packages


import java.sql.*;

public class FirstExample {


// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/EMP";

// Database credentials
static final String USER = "username";
static final String PASS = "password";

public static void main(String[] args) {


Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");

Downloaded by Arpit Pandey (arpit1111k@gmail.com)


lOMoARcPSD|17304208

//STEP 3: Open a connection


System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);

//STEP 4: Execute a query


System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);

//STEP 5: Extract data from result set


while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");

//Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
//STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();

Downloaded by Arpit Pandey (arpit1111k@gmail.com)


lOMoARcPSD|17304208

}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}//end FirstExample

Servlet And JDBC

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class JDBCServlet extends HttpServlet {

public void doGet(HttpServletRequest inRequest,


HttpServletResponse outResponse) throws ServletException,
IOException {

PrintWriter out = null;


Connection connection = null;
Statement statement;
ResultSet rs;

try {
Class.forName("com.mysql.jdbc.Driver");

connection = DriverManager
.getConnection("jdbc:mysql://localhost/products");
statement = connection.createStatement();

outResponse.setContentType("test/html");
out = outResponse.getWriter();

rs = statement.executeQuery("SELECT ID, title, price FROM product");

Downloaded by Arpit Pandey (arpit1111k@gmail.com)


lOMoARcPSD|17304208

out.println("<HTML><HEAD><TITLE>Products</TITLE></HEAD>");
out.println("<BODY>");
out.println("<UL>");

while (rs.next()) {
out.println("<LI>" + rs.getString("ID") + " "
+ rs.getString("title") + " " + rs.getString("price"));
}

out.println("</UL>");
out.println("</BODY></HTML>");
} catch (ClassNotFoundException e) {
out.println("Driver Error");
} catch (SQLException e) {
out.println("SQLException: " + e.getMessage());
}
}

public void doPost(HttpServletRequest inRequest,


HttpServletResponse outResponse) throws ServletException,
IOException {
doGet(inRequest, outResponse);
}
}

Downloaded by Arpit Pandey (arpit1111k@gmail.com)


lOMoARcPSD|17304208

PROGRAM 7

Objective: Install TOMCAT web server and APACHE. Access the above developed static
web pages for books web site, using these servers by putting the web pages developed .

Theory:

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, chooseSystem, 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, youhave to identify
the servlet classes to the compiler. The server already knows about theservlet 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 unknownclasses.

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 theserver's memory. This
slightly degrades performance in deployment situations, so isturned 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 beenloaded 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"/>

Downloaded by Arpit Pandey (arpit1111k@gmail.com)


lOMoARcPSD|17304208

Be sure to make a backup copy of server.xm before making the above change.

Enable the Invoker Servlet

The invoker servlet lets you run servlets without first making changes to yourWeb 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 isextremely convenient when you are
learning and even when you are doing your initialdevelopment.

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 copyof 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>

Downloaded by Arpit Pandey (arpit1111k@gmail.com)


lOMoARcPSD|17304208

PROGRAM 8

Objective: Assume four users user1, user2, user3 and user4 having the passwords pwd1,
pwd2, pwd3 and pwd4 respectively. Write a servlet for doing the following.
1. Create a Cookie and add these four user id’s and passwords to this Cookie.
2. Read the user id and passwords entered in the Login form (week1) and authenticate with
the values (user id and passwords) available in the cookies.

Theory:
Servlet Life cycle:
1. Servlet class loading
2. Servlet Instantiation
3. call the init method
4. call the service method
5. call destroy method

 Class loading and instantiation


If you consider a servlet to be just like any other Java program, except that it runs within a
servlet container, there has to be a process of loading the class and making it ready for requests.
Servlets do not have the exact equivalent of a main method that causes them to start execution.
When a web container starts it searches for the deployment descriptor (WEB.XML) for each of
its web applications. When it finds a servlet in the descriptor it will create an instance of the
servlet class. At this point the class is considered to be loaded (but not initialized).

 The init method


The HttpServlet class inherits the init method from GenericServlet. The init method performs a
role slightly similar to a constructor in an “ordinary” Java program in that it allows initialization
of an instance at start up. It is called automatically by the servlet container and as it causes the
application context (WEB.XML) to be parsed and any initialization will be performed. It comes
in two versions, one with a zero parameter constructor and one that takes a ServletConfig
parameter.
The servlet engine creates a request object and a response object. The servlet engine invokes the
servlet service() method, passing the request and response objects. Once the init method returns
the servlet is said to be placed into service. The process of using init to initialize servlets means
that it is possible to change configuration details by modifying the deployment descriptor
without having them hard coded in with your Java source and needing a re-compilation.
void init(ServletConfig sc)
Calling the service method
The service() method gets information about the request from the request object, processes the
request, and uses methods of the response object to create the client response. The service
method can invoke other methods to process the request, such as doGet(), doPost(), or methods
you write. The service method is called for each request processed and is not normally
overridden by the programmer.
The code that makes a servlet “go” is the. servlet
void service(ServletRequest req,ServletResponse res)

Downloaded by Arpit Pandey (arpit1111k@gmail.com)


lOMoARcPSD|17304208

 The destroy Method


Two typical reasons for the destroy method being called are if the container is shutting down or
if the container is low on resources. This can happen when the container keeps a pool of
instances of servlets to ensure adequate performance. If no requests have come in for a particular
servlet for a while it may destroy it to ensure resources are available for the servlets that are
being requested. The destroy method is called only once, before a servlet is unloaded and thus
you cannot be certain when and if it is called.
void destroy()
ServletConfig Class
ServletConfig object is used by the Servlet Container to pass information to the Servlet
during it's initialization. Servlet can obtain information regarding initialization parameters and
their values using different methods of ServletConfig class initialization parameters are
name/value pairs used to provide basic information to the Servlet during it's initialization like
JDBC driver name, path to database, username, password etc.
Methods of ServletConfig class
Following are the four methods of this class :
1. getInitParameter(String paramName) Returns value of the given parameter. If value of
parameter could not be found in web.xml file then a null value is returned.
2. GetInitParameterNames() Returns an Enumeration object containing all the names
of initialization parameters provided for this Servlet.
3. GetServletContext() Returns reference to the ServletContext object for this
Servlet. It is similar to getServletContext() method provided by
HttpServlet class.
4. GetServletName() Returns name of the Servlet as provided in the web.xml file or if none
is provided then returns complete class path to the Servlet.

CODE:
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">

Downloaded by Arpit Pandey (arpit1111k@gmail.com)


lOMoARcPSD|17304208

</form>
</body>
</html>
cologin1.html
<html>
<head>
<title> login Page </title>
<p style= "background:yellow; top:100px; left:250px; position:absolute; ">
</head>
<body>
<form ACTION="clogin1">
<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","suni");
Cookie p1=new Cookie("pwd1","ani");
Cookie c2=new Cookie("usr2","abc");
Cookie p2=new Cookie("pwd2","123");
Cookie c3=new Cookie("usr3","def");
Cookie p3=new Cookie("pwd3","456");
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);

Downloaded by Arpit Pandey (arpit1111k@gmail.com)


lOMoARcPSD|17304208

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 ");
//res.sendRedirect("/cookdemo/cologin.html");
}
}
}
}
}
Web.xml:
<web-app>
<servlet>

Downloaded by Arpit Pandey (arpit1111k@gmail.com)


lOMoARcPSD|17304208

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

Downloaded by Arpit Pandey (arpit1111k@gmail.com)


lOMoARcPSD|17304208

Downloaded by Arpit Pandey (arpit1111k@gmail.com)


lOMoARcPSD|17304208

2. Read the user id and passwords entered in the Login form (week1) and authenticate
with the values (user id and passwords) available in the cookies.

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>

Downloaded by Arpit Pandey (arpit1111k@gmail.com)


lOMoARcPSD|17304208

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>

Downloaded by Arpit Pandey (arpit1111k@gmail.com)


lOMoARcPSD|17304208

<init-param>
<param-name>username1</param-name>
<param-value>pvpsit</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>

Downloaded by Arpit Pandey (arpit1111k@gmail.com)


lOMoARcPSD|17304208

OUTPUT:

Downloaded by Arpit Pandey (arpit1111k@gmail.com)


lOMoARcPSD|17304208

PROGRAM 9

Objective: Install a database (Mysql or Oracle). Create a table which should contain at
least the following fields: name, password, email-id, phone number Write a java
program/servlet/JSP to connect to that database and extract data from the tables and
display them. Insert the details of the users who register with the web site, whenever a new
user clicks the submit button in the registration page.
Code:
CREATE TABLE `users` (
`user_name` VARCHAR(100) NOT NULL,
`password` VARCHAR(100) NOT NULL,
`phone_number` NUMBER(100) NOT NULL,
`email_address` VARCHAR(50) NOT NULL,
PRIMARY KEY (`user_name`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB

public static void executeQuery(String strQuery) throws Exception {


Connection conn = null;
try {
conn = getConnection();
Statement stmt = conn.createStatement();
stmt.executeUpdate(strQuery);
} catch (SQLException sqle) {
System.out.println("SQLException: Unable to execute query : "+strQuery);
throw sqle;
} catch (Exception e) {
System.out.println("Exception: Unable to execute query: "+strQuery);
throw e;
} finally {
closeConnection(conn);
}
}

RegistrationServlet.java
package com.techfreaks.registration.servlet;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Enumeration;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

Downloaded by Arpit Pandey (arpit1111k@gmail.com)


lOMoARcPSD|17304208

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.techfreaks.db.util.ConnectionUtil;
/**
* Servlet implementation class RegistrationServlet
*/
public class RegistrationServlet extends HttpServlet {
private static final String INSERT_QUERY_START = "insert into users values ('";
private static final String REGISTRATION_PAGE = "/RegistrationForm.jsp";
private static final String HOME_PAGE = "/Home.jsp"; /**
* Internally called to validate the request data. This method does a simple
* check for userName and password to be entered. However
* it can be extended to add more complex check at the server side like email address
validity etc.
* @param request - HttpServletRequest object
* @return boolean indicating success / failure of the validation
*/
private boolean validateData(HttpServletRequest request) {
boolean isValid = false;
String strUserName = request.getParameter("userName");
String strPassword = request.getParameter("password");
if(strUserName!=null && !strUserName.equals("") && strPassword!=null &&
!strPassword.equals("")) {
isValid = true;
}
return isValid;
}
/**
* Fancy way of looking through all the request parameters and setting in request
Attributes.
* @param request
*/
private void setRequestAttributes(HttpServletRequest request) {
Enumeration<String> enumKeys = request.getParameterNames();
while(enumKeys.hasMoreElements()) {
String key = enumKeys.nextElement();
request.setAttribute(key, request.getParameter(key)) ;
}
}
/**
* Pulls the request parameters and generates the insert query which would
* insert the new user being registered
* @param request
* @return String representing the insert query

Downloaded by Arpit Pandey (arpit1111k@gmail.com)


lOMoARcPSD|17304208

*/
private String generateInsertQuery(HttpServletRequest request) {
String strUserName = request.getParameter("userName");
String strPassword = request.getParameter("password");
String strEmail = request.getParameter("email");
String strFirstName = request.getParameter("phoneNumber");
StringBuffer strQuery = new StringBuffer(INSERT_QUERY_START);
S
strQuery.append(strUserName);
strQuery.append("', '");
strQuery.append(strPassword);
strQuery.append("')");
strQuery.append(strEmail);
strQuery.append("', '");
strQuery.append(strPhoneNumber);
strQuery.append("', '");
System.out.println("Insert query : "+strQuery.toString());

return strQuery.toString();
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
String strUserMsg = null;
HttpSession session = request.getSession();
RequestDispatcher reqDisp =
request.getRequestDispatcher(REGISTRATION_PAGE);
try {
//Check if data is valid
if(validateData(request)) {
ConnectionUtil.executeQuery(generateInsertQuery(request));
System.out.println("Insert into database successful");
session.setAttribute("userName",
request.getParameter("userName"));

response.sendRedirect(getServletContext().getContextPath()+HOME_PAGE);
} else {//If data is invalid
strUserMsg = "User Name and Password cannot be empty";
setRequestAttributes(request);
request.setAttribute("userMsg", strUserMsg);
reqDisp.forward(request, response);
}
} catch(SQLException sqle ) {
System.out.println("Unable to register user: "+sqle.getMessage());

Downloaded by Arpit Pandey (arpit1111k@gmail.com)


lOMoARcPSD|17304208

//Check if we are getting duplicate key exception on userName


if(sqle.getMessage().indexOf("Duplicate entry")!=-1) {
System.out.println("User already exists");
strUserMsg = "User name "+request.getParameter("userName")+"
already " +
"exists. Please try another user name.";
} else { //If other SQLException than dup key exception
strUserMsg = "Unable to register user
"+request.getParameter("userName")+
". Please try again later.";
}
setRequestAttributes(request);
request.setAttribute("userMsg", strUserMsg);
reqDisp.forward(request, response);

} catch(Exception e) {//If it goes into Exception other than SQLException


System.out.println("Unable to register user: "+e.getMessage());
strUserMsg = "Unable to register user
"+request.getParameter("userName")
+". Please try again later.";
setRequestAttributes(request);
request.setAttribute("userMsg", strUserMsg);
reqDisp.forward(request, response);
}}
}

RegistrationForm.jsp.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><%@page


language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
<html>
<head>
<title> Registration Form</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>
<p>Simple Registration Form</p>
<p><font color="#ff0000"><c:out value="${userMsg}"/></font></p>
<form name="frmRegistration" method="post" action="<c:out
value="${pageContext.servletContext.contextPath}" />/servlet/RegistrationServlet">
<table border="1">
<tbody>
<tr>

Downloaded by Arpit Pandey (arpit1111k@gmail.com)


lOMoARcPSD|17304208

<td>User Name</td>
<td><input type="text" name="userName" value ="<c:out
value="${userName}"/>" size="20"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="password" size="20"></td>
</tr>
<td>Email Address</td>
<td><input type="text" name="email" value ="<c:out
value="${email}"/>" size="20"></td>
</tr>
<tr>
<td>Phone Number</td>
<td><input type="text" name="phoneNumber" value ="<c:out
value="${phoneNumber}"/>" size="20"></td>
</tr>

<td><input type="submit" name="submit" value="Register"></td>


<td><input type="reset" value="Clear"></td>
</tr>
</tbody>
</table>
</form>
</body>
</html>

Downloaded by Arpit Pandey (arpit1111k@gmail.com)


lOMoARcPSD|17304208

PROGRAM 10:

Objective: Write a JSP which insert the details of the 3 or 4 users who register with the the
web site by using registration form. Authenticate the user when he submits the login form
using the username and password.

Theory:

For creating registration form, you must have a table in the database. You can write the database
logic in JSP file, but separating it from the JSP page is better approach. Here, we are going to use
DAO, Factory Method, DTO and Singletion design patterns. There are many files:
o index.jsp for getting the values from the user
o User.java, a bean class that have properties and setter and getter methods.
o process.jsp, a jsp file that processes the request and calls the methods
o Provider.java, an interface that contains many constants like DRIVER_CLASS,
CONNECTION_URL, USERNAME and PASSWORD
o ConnectionProvider.java, a class that returns an object of Connection. It uses the
Singleton and factory method design pattern.
o RegisterDao.java, a DAO class that is responsible to get access to the database

Registration Form in JSP


In this example, we are using the Oracle10g database to connect with the database. Let's first
create the table in the Oracle database:
CREATE TABLE "USER432"
( "NAME" VARCHAR2(4000),
"EMAIL" VARCHAR2(4000),
"PASS" VARCHAR2(4000)
)

We have created the table named user432 here.

index.jsp

We are having only three fields here, to make the concept clear and simplify the flow of the
application. You can have other fields also like country, hobby etc. according to your
requirement.
<form action="process.jsp">
<input type="text" name="uname" value="Name..." onclick="this.value=''"/><br/>

Downloaded by Arpit Pandey (arpit1111k@gmail.com)


lOMoARcPSD|17304208

<input type="text" name="uemail" value="Email ID..." onclick="this.value=''"/><br/>


<input type="password" name="upass" value="Password..." onclick="this.value=''"/><br/>
<input type="submit" value="register"/>
</form>

process.jsp

This jsp file contains all the incoming values to an object of bean class which is passed as an
argument in the register method of the RegisterDao class.
<%@page import="bean.RegisterDao"%>
<jsp:useBean id="obj" class="bean.User"/>
<jsp:setProperty property="*" name="obj"/>

<%
int status=RegisterDao.register(obj);
if(status>0)
out.print("You are successfully registered");

%>

User.java
It is the bean class that have 3 properties uname, uemail and upass with its setter and getter
methods.
package bean;

public class User {


private String uname,upass,uemail;

public String getUname() {


return uname;
}

public void setUname(String uname) {


this.uname = uname;
}

public String getUpass() {


return upass;

Downloaded by Arpit Pandey (arpit1111k@gmail.com)


lOMoARcPSD|17304208

public void setUpass(String upass) {


this.upass = upass;
}

public String getUemail() {


return uemail;
}

public void setUemail(String uemail) {


this.uemail = uemail;
}
}

Provider.java

This interface contains four constants that can vary from database to database.
package bean;

public interface Provider {


String DRIVER="oracle.jdbc.driver.OracleDriver";
String CONNECTION_URL="jdbc:oracle:thin:@localhost:1521:xe";
String USERNAME="system";
String PASSWORD="oracle";

ConnectionProvider.java

This class is responsible to return the object of Connection. Here, driver class is loaded only once
and connection object gets memory only once.
package bean;
import java.sql.*;
import static bean.Provider.*;

public class ConnectionProvider {


private static Connection con=null;
static{

Downloaded by Arpit Pandey (arpit1111k@gmail.com)


lOMoARcPSD|17304208

try{
Class.forName(DRIVER);
con=DriverManager.getConnection(CONNECTION_URL,USERNAME,PASSWORD);
}catch(Exception e){}
}

public static Connection getCon(){


return con;
}
}

RegisterDao.java

This class inserts the values of the bean component into the database.
package bean;
import java.sql.*;
public class RegisterDao {
public static int register(User u){
int status=0;
try{
Connection con=ConnectionProvider.getCon();
PreparedStatement ps=con.prepareStatement("insert into user432 values(?,?,?)");
ps.setString(1,u.getUname());
ps.setString(2,u.getUemail());
ps.setString(3,u.getUpass());

status=ps.executeUpdate();
}catch(Exception e){}

return status;
}}

Downloaded by Arpit Pandey (arpit1111k@gmail.com)


lOMoARcPSD|17304208

VALUE ADDITION

Objective: Design and implement a simple shopping cart example with session tracking
API.
Theory:
Based on the above analysis, let us summarize the components we had identified:
1. ModelList.jsp
2. ShoppingCart.jsp
3. CartBean.java
4. CartItemBean.java
5. CartController.java

CartBean:
• ArrayList of CartItemBean
• totalCost of items in cart

CartItemBean:
• Part number for the model
• Model description
• Unit cost
• Quantity
• Total item cost
Identifying methods:

CartController:
This servlet controller needs to implement the doGet/doPost methods. It needs to handle the
events for addToCart, updateCart and deleteCart. It is a better design to handle each of these
events separately. So, based on this discussion, the CartController will need to have the
following methods:
• doGet/doPost – Delegates request to different event methods like addToCart etc.
• addToCart – Handle the add to cart functionality
• updateCart – Handle the update cart item functionality
• deleteCart – Handle delete cart item from cart functionality

Downloaded by Arpit Pandey (arpit1111k@gmail.com)


lOMoARcPSD|17304208

Sequence diagram for Add To Cart:

Downloaded by Arpit Pandey (arpit1111k@gmail.com)


lOMoARcPSD|17304208

Setting up the environment for development:

The following will be approximate directory structure of the ShoppingCart project.


ShoppingCart
- ModelList.jsp
- ShoppingCart.jsp
WEB-INF
src
- in.techfreaks.shoppingcart.beans.CartBean.java
- in.techfreaks.shoppingcart.beans.CartItemBean.java
- in.techfreaks.shoppingcart.servlet.CartController.java
classes
lib
- jstl.jar
-standard.jar

Coding the Cart:


Such detailed design generally makes coding just a formality. Below is the code for each of the
element identified during design. The code is pretty straight forward.
CartItemBean:

package in.techfreaks.shoppingcart.beans;

public class CartItemBean {


private String strPartNumber;
private String strModelDescription;
private double dblUnitCost;
private int iQuantity;
private double dblTotalCost;

public String getPartNumber() {


return strPartNumber;
}
public void setPartNumber(String strPartNumber) {
this.strPartNumber = strPartNumber;
}
public String getModelDescription() {
return strModelDescription;
}
public void setModelDescription(String strModelDescription) {
this.strModelDescription = strModelDescription;

Downloaded by Arpit Pandey (arpit1111k@gmail.com)


lOMoARcPSD|17304208

}
public double getUnitCost() {
return dblUnitCost;
}
public void setUnitCost(double dblUnitCost) {
this.dblUnitCost = dblUnitCost;
}
public int getQuantity() {
return iQuantity;
}
public void setQuantity(int quantity) {
iQuantity = quantity;
}
public double getTotalCost() {
return dblTotalCost;
}
public void setTotalCost(double dblTotalCost) {
this.dblTotalCost = dblTotalCost;
}
}

CartBean:

package in.techfreaks.shoppingcart.beans;

import java.util.ArrayList;

public class CartBean {


private ArrayList alCartItems = new ArrayList();
private double dblOrderTotal ;

public int getLineItemCount() {


return alCartItems.size();
}

public void deleteCartItem(String strItemIndex) {


int iItemIndex = 0;
try {
iItemIndex = Integer.parseInt(strItemIndex);
alCartItems.remove(iItemIndex - 1);
calculateOrderTotal();
} catch(NumberFormatException nfe) {
System.out.println("Error while deleting cart item: "+nfe.getMessage());
nfe.printStackTrace();

Downloaded by Arpit Pandey (arpit1111k@gmail.com)


lOMoARcPSD|17304208

}
}

public void updateCartItem(String strItemIndex, String strQuantity) {


double dblTotalCost = 0.0;
double dblUnitCost = 0.0;
int iQuantity = 0;
int iItemIndex = 0;
CartItemBean cartItem = null;
try {
iItemIndex = Integer.parseInt(strItemIndex);
iQuantity = Integer.parseInt(strQuantity);
if(iQuantity>0) {
cartItem = (CartItemBean)alCartItems.get(iItemIndex-1);
dblUnitCost = cartItem.getUnitCost();
dblTotalCost = dblUnitCost*iQuantity;
cartItem.setQuantity(iQuantity);
cartItem.setTotalCost(dblTotalCost);
calculateOrderTotal();
}
} catch (NumberFormatException nfe) {
System.out.println("Error while updating cart: "+nfe.getMessage());
nfe.printStackTrace();
}

public void addCartItem(String strModelNo, String strDescription,


String strUnitCost, String strQuantity) {
double dblTotalCost = 0.0;
double dblUnitCost = 0.0;
int iQuantity = 0;
CartItemBean cartItem = new CartItemBean();
try {
dblUnitCost = Double.parseDouble(strUnitCost);
iQuantity = Integer.parseInt(strQuantity);
if(iQuantity>0) {
dblTotalCost = dblUnitCost*iQuantity;
cartItem.setPartNumber(strModelNo);
cartItem.setModelDescription(strDescription);
cartItem.setUnitCost(dblUnitCost);
cartItem.setQuantity(iQuantity);
cartItem.setTotalCost(dblTotalCost);
alCartItems.add(cartItem);
calculateOrderTotal();
}

Downloaded by Arpit Pandey (arpit1111k@gmail.com)


lOMoARcPSD|17304208

} catch (NumberFormatException nfe) {


System.out.println("Error while parsing from String to primitive types: "+nfe.getMessage());
nfe.printStackTrace();
}
}

public void addCartItem(CartItemBean cartItem) {


alCartItems.add(cartItem);
}

public CartItemBean getCartItem(int iItemIndex) {


CartItemBean cartItem = null;
if(alCartItems.size()>iItemIndex) {
cartItem = (CartItemBean) alCartItems.get(iItemIndex);
}
return cartItem;
}

public ArrayList getCartItems() {


return alCartItems;
}
public void setCartItems(ArrayList alCartItems) {
this.alCartItems = alCartItems;
}
public double getOrderTotal() {
return dblOrderTotal;
}
public void setOrderTotal(double dblOrderTotal) {
this.dblOrderTotal = dblOrderTotal;
}

protected void calculateOrderTotal() {


double dblTotal = 0;
for(int counter=0;counter<alCartItems.size();counter++) {
CartItemBean cartItem = (CartItemBean) alCartItems.get(counter);
dblTotal+=cartItem.getTotalCost();

}
setOrderTotal(dblTotal);
}
}
CartController:

package in.techfreaks.shoppingcart.servlet;

import in.techfreaks.shoppingcart.beans.CartBean;

Downloaded by Arpit Pandey (arpit1111k@gmail.com)


lOMoARcPSD|17304208

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class CartController extends HttpServlet {

//public static final String addToCart

public void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

String strAction = request.getParameter("action");

if(strAction!=null && !strAction.equals("")) {


if(strAction.equals("add")) {
addToCart(request);
} else if (strAction.equals("Update")) {
updateCart(request);
} else if (strAction.equals("Delete")) {
deleteCart(request);
}
}
response.sendRedirect("../ShoppingCart.jsp");
}

protected void deleteCart(HttpServletRequest request) {


HttpSession session = request.getSession();
String strItemIndex = request.getParameter("itemIndex");
CartBean cartBean = null;

Object objCartBean = session.getAttribute("cart");


if(objCartBean!=null) {
cartBean = (CartBean) objCartBean ;
} else {
cartBean = new CartBean();
}
cartBean.deleteCartItem(strItemIndex);
}

protected void updateCart(HttpServletRequest request) {

Downloaded by Arpit Pandey (arpit1111k@gmail.com)


lOMoARcPSD|17304208

HttpSession session = request.getSession();


String strQuantity = request.getParameter("quantity");
String strItemIndex = request.getParameter("itemIndex");

CartBean cartBean = null;

Object objCartBean = session.getAttribute("cart");


if(objCartBean!=null) {
cartBean = (CartBean) objCartBean ;
} else {
cartBean = new CartBean();
}
cartBean.updateCartItem(strItemIndex, strQuantity);
}

protected void addToCart(HttpServletRequest request) {


HttpSession session = request.getSession();
String strModelNo = request.getParameter("modelNo");
String strDescription = request.getParameter("description");
String strPrice = request.getParameter("price");
String strQuantity = request.getParameter("quantity");

CartBean cartBean = null;

Object objCartBean = session.getAttribute("cart");

if(objCartBean!=null) {
cartBean = (CartBean) objCartBean ;
} else {
cartBean = new CartBean();
session.setAttribute("cart", cartBean);
}

cartBean.addCartItem(strModelNo, strDescription, strPrice, strQuantity);


}

ModelList.jsp:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">


<html>
<head>
<title>www.tech-freaks.in - Model List</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>

Downloaded by Arpit Pandey (arpit1111k@gmail.com)


lOMoARcPSD|17304208

<body>
<p><font size="3" face="Verdana, Arial, Helvetica, sans-serif"><strong>Model List
</strong></font></p>
<a href="/ShoppingCart.jsp" mce_href="ShoppingCart.jsp">View Cart</a>
<p/>
<table width="75%" border="1">
<tr>
<td><form name="modelDetail1" method="POST" action="servlet/CartController">
<font size="2" face="Verdana, Arial, Helvetica, sans-serif"><strong>Model:</strong>
TF-Model1</font><input type="hidden" name="modelNo" value="TF-MODEL1">
<p><font size="2" face="Verdana, Arial, Helvetica, sans-
serif"><strong>Description:</strong>
Tech-Freaks imaginary model 1. </font><input type="hidden" name="description"
value="Tech-Freaks imaginary model 1."></p>
<p><font size="2" face="Verdana, Arial, Helvetica, sans-serif"><strong>Quantity:<input
type="text" size="2" value="1" name="quantity"></strong></font></p>
<p><font size="2" face="Verdana, Arial, Helvetica, sans-serif"><strong>Price:</strong>
$10.00</font><input type="hidden" name="price" value="10"></p><input type="hidden"
name="action" value="add"><input type="submit" name="addToCart" value="Add To Cart">
</form></td>
<td><form name="modelDetail2" method="POST" action="servlet/CartController"><font
size="2" face="Verdana, Arial, Helvetica, sans-serif"><strong>Model</strong>:
TF-Model2 </font><input type="hidden" name="modelNo" value="TF-MODEL2">
<font face="Verdana, Arial, Helvetica, sans-serif">
<p><font size="2"><strong>Description</strong>: Tech-Freaks imaginary model
2. </font><input type="hidden" name="description" value="Tech-Freaks imaginary model
2."></p>
<p><font size="2"><strong>Quantity</strong>: <input type="text" size="2" value="1"
name="quantity"></font></p>
<p><font size="2"><strong>Price</strong>: $20.00<input type="hidden" name="price"
value="20"></font></p>
<input type="hidden" name="action" value="add">
<input type="submit" name="addToCart" value="Add To Cart">
</font></form></td>
</tr>
<tr>
<td><form name="modelDetail3" method="POST" action="servlet/CartController"><p><font
size="2" face="Verdana, Arial, Helvetica, sans-serif"><strong>Model:</strong>
TF-Model3</font><input type="hidden" name="modelNo" value="TF-MODEL3"></p>
<p><font size="2" face="Verdana, Arial, Helvetica, sans-
serif"><strong>Description:</strong>
Tech-Freaks imaginary model 3. </font><input type="hidden" name="description"
value="Tech-Freaks imaginary model 3."></p>

Downloaded by Arpit Pandey (arpit1111k@gmail.com)


lOMoARcPSD|17304208

<p><font size="2" face="Verdana, Arial, Helvetica, sans-


serif"><strong>Quantity:</strong></font> <input type="text" size="2" value="1"
name="quantity"></p>
<p><font size="2" face="Verdana, Arial, Helvetica, sans-serif"><strong>Price:
$30.00</strong></font><input type="hidden" name="price" value="30"></p> <input
type="hidden" name="action" value="add">
<input type="submit" name="addToCart" value="Add To Cart">
</form></td>
<td><form name="modelDetail4" method="POST" action="servlet/CartController"><p><font
size="2" face="Verdana, Arial, Helvetica, sans-serif"><strong>Model</strong>:
TF-Model4</font><input type="hidden" name="modelNo" value="TF-MODEL4"></p>
<p><font size="2" face="Verdana, Arial, Helvetica, sans-
serif"><strong>Description</strong>:
Tech-Freaks imaginary model 4. </font><input type="hidden" name="description"
value="Tech-Freaks imaginary model 4."></p>
<p><font size="2" face="Verdana, Arial, Helvetica, sans-
serif"><strong>Quantity</strong>:</font> <input type="text" size="2" value="1"
name="quantity"></p>
<p><font size="2" face="Verdana, Arial, Helvetica, sans-serif"><strong>Price</strong>:
$40.00</font><input type="hidden" name="price" value="40"></p>
<input type="hidden" name="action" value="add"><input type="submit" name="addToCart"
value="Add To Cart"></form></td>
</tr>
</table>
<p> </p>
</body>
</html>

ShoppingCart.jsp:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">


<html>
<head>
<title>www.tech-freaks.in - Shopping Cart</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>

<body>
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<p><font face="Verdana, Arial, Helvetica, sans-serif"><strong>Shopping
Cart</strong></font></p>
<p><a href="/ModelList.jsp" mce_href="ModelList.jsp">Model List</a> </p>
<table width="75%" border="1">
<tr bgcolor="#CCCCCC">
<td><strong><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Model
Description</font></strong></td>

Downloaded by Arpit Pandey (arpit1111k@gmail.com)


lOMoARcPSD|17304208

<td><strong><font size="2" face="Verdana, Arial, Helvetica, sans-


serif">Quantity</font></strong></td>
<td><strong><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Unit
Price</font></strong></td>
<td><strong><font size="2" face="Verdana, Arial, Helvetica, sans-
serif">Total</font></strong></td>
</tr>
<jsp:useBean id="cart" scope="session" class="in.techfreaks.shoppingcart.beans.CartBean" />
<c:if test="${cart.lineItemCount==0}">
<tr>
<td colspan="4"><font size="2" face="Verdana, Arial, Helvetica, sans-serif">- Cart is currently
empty -<br/>
</tr>
</c:if>
<c:forEach var="cartItem" items="${cart.cartItems}" varStatus="counter">
<form name="item" method="POST" action="servlet/CartController">
<tr>
<td><font size="2" face="Verdana, Arial, Helvetica, sans-serif"><b><c:out
value="${cartItem.partNumber}"/></b><br/>
<c:out value="${cartItem.modelDescription}"/></font></td>
<td><font size="2" face="Verdana, Arial, Helvetica, sans-serif"><input type='hidden'
name='itemIndex' value='<c:out value="${counter.count}"/>'><input type='text'
name="quantity" value='<c:out value="${cartItem.quantity}"/>' size='2'> <input type="submit"
name="action" value="Update">
<br/> <input type="submit" name="action" value="Delete"></font></td>
<td><font size="2" face="Verdana, Arial, Helvetica, sans-serif">$<c:out
value="${cartItem.unitCost}"/></font></td>
<td><font size="2" face="Verdana, Arial, Helvetica, sans-serif">$<c:out
value="${cartItem.totalCost}"/></font></td>
</tr>
</form>
</c:forEach>
<tr>
<td colspan="2"> </td>
<td> </td>
<td><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Subtotal: $<c:out
value="${cart.orderTotal}"/></font></td>
</tr>
</table>
</body>
</html>

web.xml:

<?xml version="1.0" encoding="ISO-8859-1"?>


<web-app xmlns="http://java.sun.com/xml/ns/javaee"

Downloaded by Arpit Pandey (arpit1111k@gmail.com)


lOMoARcPSD|17304208

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">

<display-name>Shopping Cart</display-name>
<description>
Simple Shopping Cart
</description>

<servlet>
<servlet-name>CartController</servlet-name>
<servlet-class>in.techfreaks.shoppingcart.servlet.CartController</servlet-class>
</servlet>

<!-- Define the Manager Servlet Mapping -->


<servlet-mapping>
<servlet-name>CartController</servlet-name>
<url-pattern>/servlet/*</url-pattern>
</servlet-mapping>

</web-app>

Downloaded by Arpit Pandey (arpit1111k@gmail.com)

You might also like