WT Labs

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 59

MANGALMAY INSTITUTE OF ENNGINEERING AND

TECHNOLOGY

Lab File
Web Technology Lab
Subject Code: KCS-652
Semester: 6th

SUBMITDED BY SUBMITTED TO

SIMRAN Ms. POOJA SHARMA

ROLL NO: 2007860100067

Page1
MANGALMAY INSTITUTE OF ENNGINEERING AND
TECHNOLOGY
LISTOFEXPERIMENTS

Lab Topics To
No. Be Covered
1. Write HTML/Java scripts to display your CV in navigator, your Institute website,
Department Website and Tutorial website for specific subject.
2. 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.
3. Write programs using Java script for Web Page to display browsers information.

4. Write a Java applet to display the Application Program screen i.e. calculator and
other.
5. 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.
6. 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
7. 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.
8. Assume four users 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 (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.
10. Write a JSP which 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
11. Design and implement a simple shopping cart example with session tracking API.

Value Addition: Design and implement a simple shopping cart example with session tracking API.

Page3
PROGRAM 1

Objective: Write HTML/ Javascripts to display your CV in navigator, your Institute website,
Department Website and Tutorial website for specific subject.

<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

Page4
in Acupuncture and Oriental Medicine. Extensive exposure to issues
involving
women and children.
</li>
</ul>
<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 clean up campaign.
</li>
<li>
Served as project leader in a fund raising project sponsored by the
University
Student Council towards helping homeless youths’ 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.

Page5
</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>
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>

Page6
</body>
</html>

OUTPUT:

Page7
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.

INPUT:

<html>
<head>
<script type="text/javascript" src="validate.js"></script>
</head>
<body>
<form action="#" name="StudentRegistration" onsubmit="return(validate());">
<table cellpadding="2" width="20%" bgcolor="99FFFF" align="center"
cellspacing="2">
<tr>
<td colspan=2>
<center><font size=4><b>Student Registration Form</b></font></center>
</td>
</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>

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

Page9
</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>
<tr>
<td><input type="reset"></td>
<td colspan="2"><input type="submit" value="Submit Form" /></td>
</tr>
</table>
</form>
</body>
</html>

OUTPUT:

Page10
PROGRAM 3

Objective: Write programs usingJavascriptforWebPagetodisplaybrowsersinformation.

Theory:

Thenavigatorobjectcontains informationaboutthebrowser.

NavigatorObjectProperties
Property Description

Returnsthecodename of thebrowser

appName Returnsthenameofthebrowser

Returnstheversion informationof thebrowser

cookieEnabled Determineswhethercookiesareenabledinthebrowser

ReturnsaGeolocationobjectthat canbeusedtolocatetheuser'sposition

language Returnsthelanguageof thebrowser

Determineswhetherthe browserisonline

platform Returnsforwhichplatformthe browseriscompiled

Returnstheenginenameofthebrowser

userAgent Returnstheuser-agentheadersent bythebrowsertotheserver

OUTPUT:

forMozilla browse:

Name
Netscape
Version
5.0
(X11)Co
dename
Mozilla

Page11
cookieen
abletrue
JavaEnablefunctionjavaEnabled()
{[nativecode] }Mimetype[object
MimeTypeArray]
PlatformLinuxi686
Plugins[objectPlug
inArray]SystemLa
nguageundefined

UserlanguageMozilla/5.0(X11;Ubuntu; Linux
i686;rv:59.0)Gecko/20100101Firefox/59.0UserAgentMozilla/5.0(X11;Ubuntu;
Linuxi686;rv:59.0)Gecko/20100101Firefox/59.0

OUTPUT:

ForChromiumbrowser:

NameNetscape
Version5.0(X11;
Linuxi686)AppleWebKit/537.36(KHTML,likeGecko)UbuntuChromium/64.0.3282.167Chrome/
64.0.3282.167 Safari/537.36
Codenae Mozilla
Cookieena
bletrue
JavaEnablefunctionjavaEnabled(){[nativecode] }Mimetype[object MimeTypeArray]
PlatformLinuxi686
Plugins[objectPluginArray]SystemLanguageundefined
UserlanguageMozilla/5.0(X11; Linux
i686)AppleWebKit/537.36(KHTML,likeGecko)UbuntuChromium/64.0.3282.167
Chrome/64.0.3282.167 Safari/537.36
UserAgentMozilla/5.0(X11; Linux
i686)AppleWebKit/537.36(KHTML,likeGecko)UbuntuChromium/64.0.3282.167Chrome/64.0.3282.167
Safari/537.36

Page12
PROGRAM4

Objective:WriteaJavaapplettodisplaytheApplication Programscreeni.e.calculatorandother.

Theory
Appletisaspecialtypeofprogramthatis
embeddedinthewebpagetogeneratethedynamiccontent.Itruns insidethe browserand works at
client side.

Therearemanyadvantagesofapplet.Theyareasfollowsa)Itw
orksat client sideso less response time
b) Secured
c) Itcanbeexecutedbybrowsersrunningundermanyplatforms,includingLinux,Windows,MacOs
etc.

importjava.applet.Applet;
importjava.awt.Graphics;
importjava.awt.Button;
importjava.awt.Frame;
importjava.awt.TextField;
importjava.awt.event.ActionEvent;
importjava.awt.event.ActionListener;
importjavax.script.ScriptEngine;
importjavax.script.ScriptEngineManager;
importjavax.script.ScriptException;
publicclassCalculatorextendsAppletimplementsActionListener{
    publicstaticfinalString[]TEXT={"AC","BSp","%","/","7","8","9","*","4","5","6","-","1","2","3","+","RSET",
"0",".","="};
    TextField t1;
    TextField t2;
    StringBuffer value=newStringBuffer();
    publicvoidinit(){
        Frame title=(Frame)this.getParent().getParent();
        title.setTitle("Simple Calculator");
        setLayout(null);
        t1=newTextField("",4);
        t1.setBounds(50,10,200,50);
        add(t1);
        t2=newTextField("",4);
        t2.setBounds(50,60,200,50);
        add(t2);
        intx=50;
        inty=115;
        intk=1;
        Buttonb[]=newButton[20];

Page13
        for(inti=0;i<TEXT.length;i++){
            b[i]=newButton(""+TEXT[i]);
            b[i].setBounds(x*k,y,50,50);
            if(k%4==0){
                x=50;
                y+=50;
                k=0;
            }
            k++;
            add(b[i]);
            b[i].addActionListener(this);
        }
    }
    publicvoidpaint(Graphicsg){
    }
    publicvoidactionPerformed(ActionEvente){
        Strings=e.getActionCommand();
        if(s.equalsIgnoreCase("=")){
            System.out.println("generating result");
            t1.setText(calculate(value));
            value.setLength(0);
        }elseif(s.equalsIgnoreCase("AC")){
            System.out.println("AC: Resetting Input");
            value.setLength(0);
            t2.setText("");
        }elseif(s.equalsIgnoreCase("BSp")){
            System.out.println("BSp: Erasing a character");
            value.setLength(value.length()-1);
            t2.setText(value.toString());
        }elseif(s.equalsIgnoreCase("RSET")){
            System.out.println("Reset: Resetting Input output ");
            value.setLength(0);
            t1.setText("");
            t2.setText("");
        }else{
            value.append(s);
            t2.setText(value.toString());
        }
    }
    publicStringcalculate(StringBuffer sb){
        ScriptEngineManager mgr=newScriptEngineManager();
        ScriptEngine engine=mgr.getEngineByName("JavaScript");
        Objectresult=null;
        try{
            result=engine.eval(sb.toString());
            System.out.println(result);
        }catch(ScriptException ex){
            System.out.println("Exception : Check again your operator sequence");

Page14
            result="Error";
        }
        returnresult.toString();
    }
}

OUTPUT:

Page15
PROGRAM5

Objective: Writing program in XML for creation of DTD, which


specifies set of rules.Createa stylesheet in CSS/XSL & display
thedocumentin internet explorer.
Theory:
XML Document Type Declaration, commonly known as DTD, is a way to describe precisely
theXML language. DTDs check the validity of structure and vocabulary of an XML
documentagainstthe grammaticalrulesofthe appropriateXMLlanguage.
AnXMLdocument canbedefinedas:
 Well-formed:If the XML document adheresto allthe generalXML rules such astags
must be properly nested, opening and closing tags must be balanced, and
emptytagsmust 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
alsoconforms to available DTD that specifies which tags it uses, what attributes those
tagscancontain,andwhich tags canoccur inside other tags, amongotherproperties.
Types:
DTDcanbeclassifiedonitsdeclarationbasis intheXMLdocument,suchas:
InternalDTD
 ExternalDTD
WhenaDTDisdeclaredwithinthefileitiscalledInternalDTDandifitisdeclaredinaseparatefileit is
calledExternal DTD.
Wewilllearn moreaboutthesein thechapterDTDSyntax

Syntax
Basicsyntax of aDTD isas follows:
<!DOCTYPEelementDTD identifier

[
declaration1declaration2
........

]>
Inthe abovesyntax
 DTDstartswith<!DOCTYPE>delimiter.
 Anelementtellsthe parsertoparsethedocumentfromthespecifiedrootelement.

Page16
 DTD identifier is an identifier for the document type definition, which may be
thepath to a file on the system or URL to a file on the internet. If the DTD is pointing
toexternalpath, it is calledexternal subset.
 The square brackets [ ] enclose an optional list of entity declarations called
internalsubset.

InternalDTD
A DTD is referred to as an internal DTD if elements are declared within the XML files.
Toreference it as internal DTD, standalone attribute in XML declaration must be set to yes.
Thismeansthedeclaration works independent ofexternalsource.

Syntax
Thesyntaxof internalDTD isas shown:

whereroot-elementisthenameofrootelementandelement-
<!DOCTYPEroot-element[element-declarations]>
declarationsiswhereyoudeclaretheelements.

Example
Followingisa simpleexampleof internalDTD:
<?xmlversion="1.0"encoding="UTF-8"standalone="yes"?>
<!DOCTYPEaddress[
<!ELEMENTaddress(name,company,phone)>
<!ELEMENTname(#PCDATA)>
<!ELEMENTcompany(#PCDATA)>
<!ELEMENTphone(#PCDATA)>
]>
<address>
<name>TanmayPatil</name>
<company>TutorialsPoint</company>
<phone>(011)123-4567</phone>
</address>
ExternalDTD
InexternalDTDelementsaredeclaredoutsidetheXMLfile.Theyareaccessedbyspecifyingthe system
attributes which may be either the legal .dtd file or a valid URL. To reference it asexternal DTD,
standalone attribute in the XML declaration must be set as no. This means,declarationincludes
information from theexternal source.

Page17
Syntax
Followingis thesyntaxforexternal DTD:

wherefile-namen isthefile with .dtd extension.


<!DOCTYPEroot-elementSYSTEM"file-name">
Example
Thefollowingexampleshows externalDTDusage:
<?xmlversion="1.0"encoding="UTF-8"standalone="no"?>
<!DOCTYPEaddressSYSTEM"address.dtd">
<address>
<name>TanmayPatil</name>
<company>TutorialsPoint</company>
<phone>(011)123-4567</phone>
</address>
Thecontent oftheDTDfile address.dtdareas shown:
<!ELEMENTaddress(name,company,phone)>
<!ELEMENTname(#PCDATA)>
<!ELEMENT company(#PCDATA)>
<!ELEMENTphone(#PCDATA)>

XSLT
EXtensible Stylesheet Language Transformation commonly known as XSLT is a way to transform the XML document into other formats suchas XHTML.

<xsl:template>defines a way to reuse templates in order to generate the


desiredoutputfornodesofaparticulartype/context.varioustemplateareusedwiththetemplatelike
name,match,mode ,priority.
<xsl:value-of>tag puts the value of the selected node as per XPath expression, astext.

Declaration:
Followingisthesyntaxdeclarationof<xsl:value-of>element.
<xsl:value-of
select=Expression
disable-output-escaping="yes"|"no">
</xsl:value-of>

Page18
<xsl:for-each>tagappliesa templaterepeatedlyforeachnode.

Declaration
Followingisthesyntaxdeclarationof<xsl:for-each>element
<xsl:for-each
select=Expression>
</xsl:for-each>

<xsl:sort>tagspecifies a sort criteriaonthenodes.

Declaration
Followingisthesyntaxdeclarationof<xsl:sort>element.
<xsl:sort
select = string-
expressionlang={nmtoken}
data-type={"text"|"number"|
QName}order={"ascending"|"descending"}
case-order={"upper-first"|"lower-first"}>
</xsl:sort>

<xsl:if>tagspecifiesaconditionaltestagainstthecontentofnodes.

Declaration
Followingisthesyntaxdeclarationof<xsl:if>element.
<xsl:if
test=boolean-expression>
</xsl:if>

<xsl:choose>tagspecifiesamultipleconditionaltestsagainstthecontentofnodesinconjunctionwith
the<xsl:otherwise> and <xsl:when>elements.

Declaration
Followingisthesyntaxdeclarationof<xsl:choose>element.
<xsl:choose>
</xsl:choose>

Output:

InInternetExplorer
Title Artist
EmpireBurlesque BobDylan
Hideyourheart BonnieTyler

Page19
2.XML

<?xmlversion="1.0"encoding="UTF-8"?>
<!DOCTYPEnoteSYSTEM"Note.dtd">
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don'tforget methisweekend!</body>
</note>
DTD:
<!
DOCTYPEnote[
<!ELEMENTnote(to,from,heading,body)>
<!ELEMENTto(#PCDATA)>
<!ELEMENTfrom(#PCDATA)><!ELEMENTheading(#PCDATA)>
<!ELEMENTbody(#PCDATA)>
]>

OUTPUT:

Page20
PROGRAM6

Objective:ProgramtoillustrateJDBCconnectivity.Programformain
tainingdatabasebysending queries. Design and implement a simple
servlet book query with the help of
JDBC&SQL.CreateMSAccessDatabase,createonODBClink,Compi
le &execute JAVA JDVCSocket.

Theory:

Creating JDBCApplication
TherearefollowingsixstepsinvolvedinbuildingaJDBCapplication−

 Import the packages: Requires that you include the packages containing the
JDBCclasses needed for database programming. Most often, using import
java.sql.* willsuffice.
 RegistertheJDBCdriver:Requiresthatyouinitializeadriversoyoucanopenacommu
nicationchannelwith thedatabase.
 Open a connection: Requires using the DriverManager.getConnection() method
tocreateaConnectionobject,whichrepresentsaphysical connectionwiththedatabase.
 Executeaquery: Requiresusingan objectof type
StatementforbuildingandsubmittinganSQLstatement to thedatabase.
 Extractdatafromresult set:Requiresthatyou usetheappropriate ResultSet.getXXX()
methodtoretrievethedata fromthe resultset.
 Cleanuptheenvironment:Requiresexplicitlyclosingalldatabaseresourcesversusrelyin
gon the JVM's garbagecollection.

STEPS:

//
STEP1.Importrequiredpackagesimp
ortjava.sql.*;

publicclassFirstExample{
//JDBCdrivernameanddatabaseURL
staticfinalStringJDBC_DRIVER="com.mysql.jdbc.Driver";sta
ticfinal StringDB_URL="jdbc:mysql://localhost/EMP";

//Databasecredentials
staticfinalStringUSER="username";sta
ticfinalStringPASS ="password";

publicstaticvoidmain(String[]args)
{Connectionconn =null;
Statement stmt =
null;try{

Page21
//STEP2:RegisterJDBCdriver

Page22
Class.forName("com.mysql.jdbc.Driver");

//STEP 3: Open a
connectionSystem.out.println("Connectingtodat
abase...");
conn=DriverManager.getConnection(DB_URL,USER,PASS);

//STEP 4: Execute a
querySystem.out.println("Creatingstatement..
.");stmt= conn.createStatement();
Stringsql;
sql="SELECTid,first,last,ageFROMEmployees";Resu
ltSetrs =stmt.executeQuery(sql);

//
STEP5:Extractdatafromresultsetwhil
e(rs.next()){
//
Retrievebycolumnnameint
id=rs.getInt("id");
intage=rs.getInt("age");
Stringfirst=rs.getString("first");S
tringlast=rs.getString("last");

//Display
valuesSystem.out.print("ID: " +
id);System.out.print(", Age: " +
age);System.out.print(", First: " +
first);System.out.println(",Last:"+la
st);
}
//STEP 6: Clean-up
environmentrs.close();
stmt.close();
conn.close();
}catch(SQLExceptionse){
//
HandleerrorsforJDBCse.
printStackTrace();
}catch(Exceptione){
//Handle errors for
Class.forNamee.printStackTrace()
;
}finally{
//
finallyblockusedtocloseresourcestry{
if(stmt!
=null)stmt.c

Page23
lose();
}catch(SQLExceptionse2){
}//
nothingwecandotry{
if(conn!=null)

Page24
conn.close();
}catch(SQLExceptio
nse)
{se.printStackTrace
();
}//endfinallytry
}//end
trySystem.out.println("Goodbye!")
;
}//endmain
}//endFirstExample

Page25
Page26
PROGRAM7

Objective: InstallTOMCATwebserverandAPACHE.Accesstheabove
developedstaticwebpagesforbookswebsite, usingtheseservers byputting
thewebpagesdeveloped .

Theory:
How to Install Tomcat on Windows
In this section, we will cover two ways of installing the Tomcat web server:

 Via Windows Service Installer.


 From a zip archive.

Follow the steps below to download and install Tomcat.

Note: For maximum performance, try one of our 20 pre-configured Bare Metal Cloud instances. In
addition, Bare Metal Cloud deploys in a few clicks for as low as $0.10/h.
Kick start your development project today!
Step 1: Download Tomcat for Windows
To download the Tomcat installation file, follow the steps below:

1. Browse to the official Apache Tomcat website. Locate the Download section and click the latest
Tomcat version available. At the time of writing this article, the latest Tomcat version was version 10.
2. On the Download page, scroll down and locate the Binary Distributions area.

In the Core list, depending on the installation type you prefer, click the download link for the Windows
Service Installer or the 32bit/64bit Windows zip file.
Step 2: Install Tomcat
Install Tomcat via the Windows Service Installer for an automated and wizard-guided experience. The
service installer installs the Tomcat service and runs it automatically when the system boots.

For a portable experience, install Tomcat using the zip file and avoid installing the service. Easily
uninstall Tomcat when it is no longer needed by deleting the Tomcat directory, or move it around when
necessary.

Method 1: Install Tomcat Using the Windows Service Installer


Follow the steps below to install Tomcat using the Windows Service Installer.

1. Open the downloaded Windows Service Installer file to start the installation process.

2. In the Tomcat Setup welcome screen, click Next to proceed.


3. Read the License Agreement and if you agree to the terms, click I Agree to proceed to the next step.
4. In the Tomcat component selection screen, choose Full in the dropdown menu to ensure the wizard
installs the Tomcat Host Manager and Servlet and JSP examples web applications. Alternatively, keep
the default Normal installation type and click Next.

5. The next step configures the Tomcat server. For instance, enter the Administrator login
credentials or choose a different connection port. When finished, click Next to proceed to the next step.
6. The next step requires you to enter the full path to the JRE directory on your system. The wizard auto-
completes this if you have previously set up the Java environment variables. Click Next to proceed to
the next step.
7. Choose the Tomcat server install location or keep the default one and click Install.

8. Check the Run Apache Tomcat box to start the service after the installation finishes. Optionally,
check the Show Readme box to see the Readme file. To complete the installation, click Finish.
9. A popup window appears that starts the Tomcat service. After the process completes, the window
closes automatically. The Apache Tomcat web server is now successfully installed .

Method 2: Install Tomcat Using the zip Archive


Follow the steps below to set up the Tomcat server using the zip archive.

1. After downloading the 32bit/64bit Windows zip file, depending on your Windows version, unzip the


downloaded file. Right-click the file and select Extract all...

2. Choose where to extract the archive contents. For easier navigation, we recommend extracting it to
the hard drive's root. Optionally, give the directory a shorter name to facilitate server configuration later.
Click Extract to start the process.
3. Navigate to the conf sub-directory within the extracted directory and locate the server.xml file.

Important: Back up the .xml files before making any changes.

4. The default connection port is 8080. To choose a different port, edit the server.xml file with a text
editor, such as Notepad++, and locate the following lines:

<Connector port="8080" protocol="HTTP/1.1"


connectionTimeout="20000"
redirectPort="8443" />

Change the connector port number to any number between 1024 and 65535.

5. To enable directory browsing, locate the web.xml file in the conf directory and edit the file with a text
editor. Directory browsing helps when testing the system, and sometimes it may be the solution for a
403 forbidden error.

Locate the following lines and change the listings value from false to true:


<servlet>
<servlet-name>default</servlet-name>
<servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class>
<init-param>
<param-name>debug</param-name>
<param-value>0</param-value>
</init-param>
<init-param>
<param-name>listings</param-name>
<param-value>false</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>

6. Implement an auto-reload feature by editing the context.xml file. Above all, auto-reload is useful in


development to prevent restarting the server manually each time a change is made.

Using a text editor, open the context.xml file. Locate the following line and change the value
from false to true in each instance:

<Context reloadable="false" crossContext="false" parallelAnnotationScanning="false">


......
......
</Context>

7. After making the changes, start the server. Press the Windows key and type cmd. Press Enter to
open a Command Prompt window.

8. Move to the bin directory of your Tomcat server and run:

startup
8. Add an exception for Tomcat in the firewall:

9. A new Tomcat console window appears. This console receives error messages
and system.out.println() messages issued by the Java servlets.

Note: See how to check which Java version is installed on your Windows or Mac system.

10. Access the server using a browser as an HTTP client. Browse to http://localhost:8080 and access
the Tomcat welcome page to ensure the server works.
In addition, use the Developer Quick Start links to see more information about the server and start using
and configuring the server.

11. Shut down the Tomcat server by pressing Ctrl+C on the Tomcat console.

Step 3: Check if Apache Tomcat Service Is Running


Installing Tomcat using the Windows Service Installer installs Tomcat as a Windows service that
automatically runs on boot. Follow the steps below to ensure that Tomcat is started as a Windows
service.

1. Open the Start menu and search for Services.

2. Select the Services result.
3. In the Services window, locate the Apache Tomcat service. The Status column indicates whether the
service is running or not. Start or Stop the service using the buttons in the toolbar or by
pressing Stop or Restart on the left side of the service list.
Configure the service startup by right-clicking the Tomcat service and selecting Properties.

4. In the Properties window, under the Startup type dropdown menu, select how to run the Tomcat
service:

 Automatic (Delayed Start). Starts the service shortly after boot. A delayed start improves server
boot performance and has security benefits.
 Automatic. Automatically starts the service on boot.
 Manual. The service starts only when Windows or another service needs it or if invoked.
 Disabled. Disables the service startup, even if you try to start it.
Click OK to confirm the changes.

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

OUTPUT
PROGRAM8

Objective:Assumefourusers user1,user2,user3anduser4
havingthepasswordspwd1,pwd2,pwd3andpwd4respectively.Writeaservletfordoingthefollo
wing.
JSP Scripting Elements
JSP scripting elements let you insert Java code into the servlet that will be generated from
the current JSP page. There are three forms:
1. Expressions of the form <%= expression %> that are evaluated and inserted into the
output,
2. Scriptlets of the form <% code %> that are inserted into the servlet's service
method, and
3. Declarations of the form <%! code %> that are inserted into the body of the servlet
class, outside of any existing methods.
Each of these is described in more detail below.
JSP Expressions
A JSP expression is used to insert Java values directly into the output. It has the following
form:
<%= Java Expression %>
The Java expression is evaluated, converted to a string, and inserted in the page. This evaluation
is performed at run-time (when the page is requested), and thus has full access to information
about the request. For example, the following shows the date/time that the page was
requested:
Current time: <%= new java.util.Date() %>
Sree Vahini Institute Science of Technology 76
To simplify these expressions, there are a number of predefined variables that you can use.
These implicit objects are discussed in more detail later, but for the purpose of expressions, the
most important ones are:
• request, the HttpServletRequest;
• response, the HttpServletResponse;
• session, the HttpSession associated with the request (if any); and
• out, the PrintWriter (a buffered version of type JspWriter) used to send output to
the client.
JSP Scriptlets
If you want to do something more complex than insert a simple expression, JSP
scriptlets let you insert arbitrary code into the servlet method that will be built to generate the
page. Scriptlets have the following form:
<% Java Code %>
Scriptlets have access to the same automatically defined variables as expressions. So, for
example, if you want output to appear in the resultant page, you would use the out variable.
<%
String queryData = request.getQueryString();
out.println("Attached GET data: " + queryData);
%>
Note that code inside a scriptlet gets inserted exactly as written, and any static
HTML (template text) before or after a scriptlet gets converted to print statements. This
means that scriptlets need not contain complete Java statements, and blocks left open can
affect the static HTML outside of the scriptlets.
JSP Declarations
A JSP declaration lets you define methods or fields that get inserted into the main body
of the servlet class (outside of the service method processing the request). It has the following
form:
<%! Java Code %>
Since declarations do not generate any output, they are normally used in conjunction
with JSP expressions or scriptlets. For example, here is a JSP fragment that prints out the
Sree Vahini Institute Science of Technology 77
number of times the current page has been requested since the server booted (or the servlet
class was changed and reloaded):
<%! private int accessCount = 0; %>
PROGRAM:
Login.html:
<!--Home.html-->
<html><body>
<center><h1>XYZ Company Ltd.</h1></center>
<table border="1" width="100%" height="100%">
<tr>
<td valign="top" align="center"><br/>
<form action="auth.jsp"><table>
<tr>
<td colspan="2" align="center"><b>Login Page</b></td>
</tr>
<tr>
<td colspan="2" align="center"><b>&nbsp;</td>
</tr>
<tr>
<td>User Name</td>
<td><input type="text" name="user"/></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="pwd"/></td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
<tr>
Sree Vahini Institute Science of Technology 78
<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">
<%!Stringuname,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.158:1521:CCLAB","scott","
tiger
");
Statement st=con.createStatement();
ResultSetrs=st.executeQuery("select name,password from personal where name='"+uname+"'
and password='"+pwd+"'");
Sree Vahini Institute Science of Technology 79
if(rs.next())
{
out.println("Authorized person");
}
else
{
out.println("UnAuthorized person");
}
con.close();
}
catch(Exception e){out.println(""+e);}
%>
</body>
</html>
RESULT: The user is authenticated when he submits the login form using the user name and password from the
database.
PROGRAM9

Objective:Installadatabase(MysqlorOracle).Createatablewhichshouldcontainatl
eastthefollowingfields:name,password,email-
id,phonenumberWriteajavaprogram/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:
JDBC Driver Types  
There are four types of JDBC drivers in use:  
Type 1: JDBC-ODBC Bridge 
A Type 1 JDBC-ODBC Bridge provides application developers with a way to access JDBC drivers via the
JDBC API. Type 1 JDBC drivers translate the JDBC calls into ODBC calls and then send the calls to the ODBC
driver. Type 1 JDBC drivers are generally used when the database client libraries need to be loaded on every
client machine. 
Type 2: Native API/Partly Java Driver 
A Type 2 Native API/Partly Java Driver is a partial Java driver because it converts JDBC calls into
database specific calls. Type 2 Native API/Partly Java Driver communicates directly with the database server. 
Type 3: Pure Java Driver  
A Type 3 Pure Java Driver works in a three tiered architecture. The JDBC calls are passed via the network
to the middle tier server. This server translates the calls to the database specific native interface to further request
the server. JDBC drivers available from Simba are Type 3 drivers. 

Type 4: Native Protocol Java Driver  


The type 4 driver is written completely in Java and is hence platform independent. It is installed inside the
Java Virtual Machine of the client. It provides better performance over the type 1 and 2 drivers as it does not have
the overhead of conversion of calls into ODBC or database API calls. Unlike the type 3 drivers, it does not need
associated software to work.A Type 4 Native Protocol Java Driver converts JDBC calls into the database specific
calls so that the client applications can communicate directly with the server.

PROGRAM:
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>
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><tdalign=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(ServletRequestreq,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");
PreparedStatementst=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>
PROGRAM10:
Objective: Write a JSP which insert the details of the 3 or 4 users who register with the
theweb site by using registration form. Authenticate the user when he submits the login
formusingtheusernameand password.

Theory:

For creating registration form, you must have a table in the database. You can write the
databaselogic in JSP file, but separating it from the JSP page is better approach. Here, we are
going to useDAO,FactoryMethod,DTOand Singletion design patterns. Therearemanyfiles:
o index.jspforgettingthe valuesfrom theuser
o User.java, abeanclassthathavepropertiesandsetterandgettermethods.
o process.jsp,ajspfilethatprocessestherequestandcalls themethods
o Provider.java,an interface that contains manyconstants likeDRIVER_CLASS,
CONNECTION_URL,USERNAMEandPASSWORD
o ConnectionProvider.java,aclassthatreturnsanobjectofConnection.ItusestheSingletonand
factorymethod design pattern.
o RegisterDao.java, aDAOclassthatisresponsibletogetaccesstothedatabase

Output:
Page59

You might also like