Web Technology Lab Manual
Web Technology Lab Manual
Web Technology Lab Manual
Engineering
LAB MANUAL
WEB TECHNOLOGY LAB
K.VIGNESWARA REDDY,
ASST. PROF.
IT DEPARTMENT
Week-1
Date:
----------------------------------------------------------------------------------------------------------AIM: Design the static web pages required for an online book
store web site.
1) HOME PAGE
DESCRIPTION:
The static home page must contain three frames.
Top frame
PROGRAM:
Homepage
<head>
<frameset rows="20%,*">
<frame src="topframe.html"name="f1">
<frameset cols="20%,*">
<frame src="leftframe.html"name="f2">
<frame src="rightframe.html"name="f3">
</frameset>
</frameset>
</head>
OUTPUT
Top frame:
<html>
<body>
<p>
<img
Users\Documents\My
src="C:\Documents
Pictures\Sample
and
Settings\All
Pictures\Winter.jpg"
<a href="cart.html" target="f3">
Cart
</a>
</h2>
</p>
</body>
</html>
OUTPUT:
Leftframe:
<html>
<body>
<a
href=cse.html
target="f3"><h3>CSE</h3>
</a><br><br><br><br><br>
<a
href=ece.html
target="f3"><h3>ECE</h3></a><br><br><br><br><br>
<a
href=eee.html
target="f3"><h3>EEE</h3></a><br><br><br><br><br>
<a href=civil.html target="f3"><h3>Civil</h3></a>
</body>
</html>
OUTPUT:
Right frame:
<html>
<body bgcolor="pink">
<p><h2
<font
OUTPUT:
2) LOGIN PAGE
DESCRIPTION:
The login page contains the user name and the password of
the user to authenticate.
PROGRAM:
<html>
<head>
<p style= "background:yellow; top:100px; left:250px;
position:absolute; ">
</head>
<body background=E:\1.jpg>
<form action="index.jsp" method="get">
<label>
<font face="comic sans ms" color="green"
size="5">Login </font>
</label>
<input type="text" size="20" maxlength="20"
value=' '><br><br><br>
<label>
<font
face="comic
size="5">Password </font>
sans
ms"
color="green"
</label>
<input
type="submit"
value="submit">
<input type="reset">
</form>
</body>
</html>
OUTPUT:
3) CATOLOGUE PAGE
DESCRIPTION:
The catalogue page should contain the details of all the
books available in the web site in a table.
The details should contain the following:
10
11
Publisher:Wiesley
</font>
</pre>
</td>
<td> $40 </td>
<td> <a href="cart.html" target="_blank">
<img src="C:\Documents and Settings\All users\My
Documents\My
Pictures\cart.bmp"
width="150"
height="100"></img>
</a>
</td>
</tr>
<tr>
<td> <img src="C:\Documents and Settings\All users\My
Documents\My Pictures\java.bmp" width=100 height=50>
</img>
</td>
<td>
<pre>
<font face="comic sans ms" size=4 color="green" >
book:Java 2
Author:Watson
Publisher:BPB publications
</font>
</pre>
</td>
<td> $40 </td>
<td> <a href="cart.html" target="_blank">
12
Pictures\cart.bmp"
width="150"
height="100"></img>
</a>
</td>
</tr>
</table> </center>
</body>
</html>
OUTPUT:
13
RESULT:
Thus the home page, login page, catalogue page for the
online book store are created successfully
14
Week-2
Date:
----------------------------------------------------------------------------------------------------------AIM: Design of the cart page and the registration page required
for online book store.
4) CART PAGE
DESCRIPTION:
The cart page contains the details about the books which
are added to the cart.
PROGRAM:
<html>
<body>
<center><br><br><br>
<img src=E:\aa.jpg>
<table border=1 cellpadding=center>
<thead>
<tr>
<th>Book name</th>
<th>price</th>
<th>quantity</th>
<th>amount</th>
</tr>
</thead>
<tr>
15
<td>java 2</td>
<td>$45</td>
<td>2</td>
<td>$70</td>
</tr>
<tr>
<td> XML bible</td>
<td> $20</td>
<td> 5</td>
<td> $40</td>
</tr>
<th colspan=4>total amount=$110>
</th>
</tr>
</table>
</center>
</body>
</html>
OUTPUT:
16
5) REGISTRATION PAGE
DESCRIPTION:
Create a registration form with the following fields
1)Name(Textfield)
2) Password (password field)
3) E-mail id (text field)
4) Phone number (text field)
5) Sex (radio button)
6) Date of birth (3 select boxes)
17
18
<option>4</option>
<option>5</option>
</select>
<select>
<option>jan</option>
<option>feb</option>
<option>mar</option>
<option>apr</option>
</select>
<select>
<option>1980</option>
<option>1981</option>
<option>1982</option>
<option>1983</option>
</select> <br> <br> <br>
<label> Languages Known </label>
<input type="checkbox"> English
<input type="checkbox"> Telugu
<input type="checkbox"> Hindi
<input type="checkbox"> Tamil <br> <br> <br>
<label> Address </label>
<textarea rows=5 cols=20 scrolling="yes"> </textarea>
</center>
</body>
</html>
OUTPUT:
19
RESULT:
Thus the registration and cart pages for online book store
pages are created successfully
Week-3
Date:
20
is
simple
scripting
language
invented
21
in
the visitors
name, phone
number
and
22
regx=new RegExp(fish|fow1);
Functions:
test(string)- Tests a string for pattern matches. This method
returns a Boolean that indicates whether or not the specified
pattern exists within the searched string. This is the most
commonly used method for validation. It updates some of the
properties of the parent RegExp object following a successful
search.
exec(string)- Executes a search for a pattern within a string. If
the pattern is not found, exec() returns a null value. If it finds one
or more matches it returns an array of the match results. It also
updates some of the properties of the parent RegExp object
PROGRAM:
Valid.js
function fun()
{
var userv=document.forms[0].user.value;
var pwdv=document.forms[0].pwd.value;
var emailv=document.forms[0].email.value;
var phv=document.forms[0].ph.value;
var userreg=new RegExp("^[a-zA-Z][a-zA-Z0-9]*$");
var emailreg=new RegExp("^[a-zA-Z][a-zA-Z0-9_.]*@[a-zAZ][a-zA-Z0-9_.]*.[a-zA-Z][a-zA-Z0-9_.]{2}.[a-zA-Z][a-zA-Z0-9_.]
{2}$|^[a-zA-Z][a-zA-Z0-9_.]*@[a-zA-Z][a-zA-Z0-9_.]*.[a-zA-Z][azA-Z0-9_.]{3}$");
var phreg=new RegExp("^[0-9]{10}$");
23
var ruser=userreg.exec(userv);
var remail=emailreg.exec(emailv);
var rph=phreg.exec(phv);
if(ruser && remail && rph && (pwdv.length > 6))
{
alert("All values are valid");
return true;
}
else
{
if(!ruser) { alert("username
invalid");document.forms[0].user.focus();}
if(!remail) { alert("password
invalid");document.forms[0].user.focus();}
if(!rph) { alert("phone number
invalid");document.forms[0].ph.focus();}
if(pwdv.length < 6) { alert("password
invalid");document.forms[0].pwd.focus();}
return false;
}
}
Register.html
<html>
<body><center>
<fieldset>
<legend>Registration</legend>
<form action="Database" method="get" onSubmit="return
fun()">
24
<pre>Name
size="10"><br>
Password :<input type="password" name="pwd"
size="10"><br>
E-mail
size="10"><br>
Phone Number :<input type="text" name="ph"
size="10"><br>
<input type="submit" value="Register">
</pre>
</form>
</body>
<script src="valid.js"></script>
</html>
25
OUTPUT:
26
RESULT:
Thus the home page, login page, catalogue page for the
online book store are created successfully
27
Week-4
Date:
----------------------------------------------------------------------------------------------------------AIM:
Design a web page using CSS (Cascading Style Sheets)
which includes the following:
1) Use different font, styles: In the style definition you define
how each selector should work .Then, in the body of your
pages, you refer to these selectors to activate the styles.
2) Set a background image for both the page and single
elements on the page.
3) Control the repetition of the image with the backgroundrepeat property
DESCRIPTION:
28
consists
of
list
of
semicolon-separated
Syntax
The CSS syntax is made up of three parts: a selector, a
property and a value:
selector {property: value}
The selector is normally the HTML element/tag you wish to
define, the property is the attribute you wish to change, and each
property can take a value. The property and value are separated
by a colon, and surrounded by curly braces:
29
30
Inline Styles
An inline style loses many of the advantages of style sheets
by mixing content with presentation. Use this method sparingly,
such as when a style is to be applied to a single occurrence of an
element.
To use inline styles you use the style attribute in the relevant tag.
The style attribute can contain any CSS property.
<p style="color: sienna; margin-left: 20px">
This is a paragraph </p>
PROGRAM:
Cas.css:
a:link{color:black;}
a:visited{color:pink;}
a:active{color:red;}
a:hover{color:green;}
.right {
text-align:center;
text-decoration:underline;
font-weight:bold;
color:blue;
font-family:comic sans ms;
font-size:30; }
.image {
text-align:left;
31
font-family:"monotype corsiva";
font-weight:10;
}
.image1 {
background-image:url("C:\Documents and Settings\All
Users\My Documents\My Pictures\krishna.jpg");
background-attachment:fixed;
background-repeat:no-repeat;
width:150;
height:150; }
table { align:center;border:10;
border-style:ridge;
border-color:yellow;}
htm.html:
<html>
<head>
<link rel="stylesheet" href="cas.css" type="text/css">
<style>
.xlink{
text-decoration:none;font-
weight:bold;cursor:crosshair;}
.ylink{text-decoration:underline;fontweight:bold;cursor:help;}
</style>
</head>
32
<body class="image">
<p style="text-align:right;">
<a
href="registration.html"
class="xlink">
Reg
Link</a>
<a href="topframe.html" class="ylink"> Help Link</a>
</p>
<p class="right">PVPSIT</p>
<div
style="position:relative;font-size:90px;z-
index:5;color:purple;">PVPSIT</div>
<div style="position:relative;font-size:50px;z-index:1;top:70; left:5;color:blue;">CSE</div>
<div
style="position:relative;font-size:90px;z-
index:1;color:purple;">PVPSIT</div>
<div style="position:relative;font-size:50px;z-index:5;top:70; left:5;color:blue;">CSE</div>
<table align="center" class="image1">
<tr>
<td> Fruits</td>
<td> Mango</td>
</tr>
</table>
</body>
</html>
OUTPUT:
33
Week-5:
Date:
----------------------------------------------------------------------------------------------------------AIM: Write an XML file which will display the Book information.
It includes the following:
1) Title of the book
34
2) Author Name
3) ISBN number
4) Publisher name
5) Edition
6) Price
Write a Document Type Definition (DTD) to validate the above
XML file.
Display the XML file as follows.
The contents should be displayed in a table. The header of the
table should be in color GREY. And the Author names column
should be displayed in one color and should be capitalized and in
bold. Use your own colors for remaining columns.
Use XML schemas XSL and CSS for the above purpose.
DESCRIPTION:
DTD vs XML Schema
The DTD provides a basic grammar for defining an XML
Document in terms of the metadata that comprise the shape of
the document. An XML Schema provides this, plus a detailed way
to define what the data can and cannot contain. It provides far
more control for the developer over what is legal, and it provides
an Object Oriented approach, with all the benefits this entails.
Many systems interfaces are already defined as a DTD.
They are mature definitions, rich and complex. The effort in rewriting the definition may not be worthwhile.
35
36
<edition>3</edition>
<price>350</price>
</book>
<book>
<title>internet worldwideweb</title>
<author>ditel&ditel</author>
<ISBN>123-456-781</ISBN>
<publisher>person</publisher>
<edition>3</edition>
<price>450</price>
</book>
</bookstore>
XML document Validation using DTD
DTD document (bookstore.dtd)
<?xml version="1.0" encoding="UTF-8"?>
<!ELEMENT bookstore (book+)>
<!ELEMENT book (title,author,ISBN,publisher,edition,price)>
<!ELEMENT title (#PCDATA)>
<!ELEMENT author (#PCDATA)>
<!ELEMENT ISBN (#PCDATA)>
<!ELEMENT publisher (#PCDATA)>
<!ELEMENT edition (#PCDATA)>
<!ELEMENT price (#PCDATA)>
37
Bookstore.xml
<!DOCTYPE bookstore SYSTEM "C:\Documents and
Settings\Administrator\My Documents\bookstore.dtd">
<bookstore>
<book>
<title>web programming</title>
<author>chrisbates</author>
<ISBN>123-456-789</ISBN>
<publisher>wiley</publisher>
<edition>3</edition>
<price>350</price>
</book>
<book>
<title>internet worldwideweb</title>
<author>ditel&ditel</author>
<ISBN>123-456-781</ISBN>
<publisher>person</publisher>
<edition>3</edition>
<price>450</price>
</book>
</bookstore>
38
type="xs:int"></xs:element>
<xs:element name="price"type="xs:decimal"></xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
Bookstore.xml
39
<bookstore
xmlns:xsi="http://www.w3.org/2001/XMLSchemainstance"
xsi:noNamespaceSchemaLocation="C:\Documents and
Settings\Administrator\My Documents\bookstore.xsd">
<book>
<title>web programming</title>
<author>chrisbates</author>
<ISBN>123-456-789</ISBN>
<publisher>wiley</publisher>
<edition>3</edition>
<price>350</price>
</book>
<book>
<title>internet worldwideweb</title>
<author>ditel&ditel</author>
<ISBN>123-456-781</ISBN>
<publisher>person</publisher>
<edition>3</edition>
<price>450</price>
</book>
</bookstore>
40
PROGRAM:
XML:
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="bookstore.xsl"?>
<bookstore>
<book>
<title>Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book>
<title>Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book>
<title>Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
XSL:
41
<xsl:stylesheet
version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h2> My Books collection</h2>
<table border="1">
<tr bgcolor="red">
<th align="left">title</th>
<th align="left">author</th>
</tr>
<xsl:for-each select="bookstore/book">
<tr>
<td><xsl:value-of select="title"/></td>
<xsl:choose>
<xsl:when test="price > 30">
<td bgcolor="yellow"><xsl:value-of select="author"/></td>
</xsl:when>
<xsl:when test="price > 10">
<td bgcolor="magneta"><xsl:value-of select="author"/></td>
</xsl:when>
<xsl:otherwise>
<td><xsl:value-of select="author"/></td>
</xsl:otherwise>
</xsl:choose>
</tr>
</xsl:for-each>
</table>
42
</body>
</html>
</xsl:template>
</xsl:stylesheet>
OUTPUT:
Week-6:
Date:
----------------------------------------------------------------------------------------------------------43
VISUAL BEANS:
AIM:
set to true then the shape of the area is Square and it is Circle, if
it is false.
The color of the area should be changed dynamically for every
mouse click. The color should also be changed if we change the
color in the property window .
DESCRIPTION:
A Bean is a JavaBeans component. Beans are independent,
reusable software modules. Beans may be visible objects, like
AWT components, or invisible objects, like queues and stacks. A
builder/integration tool manipulates Beans to create applets and
applications.
Beans consist of three things:
Events
An event allows your Beans to communicate when
44
list
for
PropertyChangeEvents
via
the
45
In
addition
to
maintaining
list
of
Methods
Bean methods are available for anyone to call by just
making each public. However, you can restrict which methods are
visible to the Bean builder/integration tool by providing a
getMethodDescriptors method along with your Bean's BeanInfo.
Every Bean can provide a supporting BeanInfo class to customize
a Bean's appearance to an integration tool.
Procedural Steps to create a Java-Bean:
46
1) Creating
directory-
Create
new
directory
in
47
change();
}
public boolean getRectangular()
{
return rectangular;
}
public void setRectangular(boolean flag)
{
this.rectangular=flag;
repaint();
}
public void change()
{
color=randomColor();
repaint();
}
private Color randomColor()
{
int r=(int)(255*Math.random());
int g=(int)(255*Math.random());
int b=(int)(255*Math.random());
return new Color(r,g,b);
}
public void paint(Graphics g)
{
Dimension d=getSize();
int h=d.height;
int w=d.width;
48
g.setColor(color);
if(rectangular)
{
g.fillRect(0,0,w-1,h-1);
}
else
{
g.fillOval(0,0,w-1,h-1);
}
}
}
OUTPUT:
49
RESULT:
Thus the colors bean is created successfully.
Program 2:
Visual Beans (program 2)
Convert.java
package sunw.demo.convert;
import java.awt.*;
import java.awt.event.*;
public class convert extends Canvas
{
private double dollars=0.0;
private double rupees=0.0;
50
51
{
return rupees*dollars;
}
public void paint(Graphics g)
{
g.setColor(Color.red);
g.drawString(String.valueOf(dollarvalue),10,10);
}
}
Convert.mf
Name: sunw/demo/convert/convert.class
Java-Bean: True ( press Enter)
(Carriage return compulsory)
52
53
Result
Thus the convertion bean is created successfully
Program 3:
package sunw.demo.colors;
import java.awt.*;
import java.awt.event.*;
public class mouseclick extends Canvas {
public int count=0;
public mouseclick() {
54
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me) {
change();
}
});
setSize(100,100);
}
public void change() {
count++;
repaint();
}
public void paint(Graphics g) {
Dimension d = getSize();
int h = d.height;
int w = d.width;
g.setColor(Color.red);
g.fillRect(0,0,100,100);
g.setColor(Color.blue);
g.drawString(String.valueOf(count),50,50);
}
}
Mouseclick.mft
Name: sunw/demo/colors/mouseclick.class
Java-Bean: True
Output
55
Result
Thus the Mouse Clicks bean is created successfully
Week-7:
Date:
----------------------------------------------------------------------------------------------------------56
57
servlets, tag libraries, or other classes that use the servlet and
JSP APIs will fail with error messages about unknown classes.
Name: JAVA_HOME
Value: install_dir/common/lib/servlet-api.jar
name="localhost"
debug="0"
appBase="webapps" ...>
and then insert the following immediately below it:
<DefaultContext reloadable="true"/>
Be sure to make a backup copy of server.xml before making
the above change.
Enable the Invoker Servlet
58
59
60
Week-7:
Date:
----------------------------------------------------------------------------------------------------------AIM: Access the developed static web pages for books web site,
using these servers by putting the web pages developed in week1 and week-2 in the document root.
OUTPUT
61
62
RESULT:
Thus week-1 and week-2 pages are accessed using the TOMCAT
web server successfully.
Week-8:
Date:
----------------------------------------------------------------------------------------------------------AIM:
User Authentication:
Assume four users user1, user2, user3 and user4 having
the passwords pwd1, pwd2, pwd3 and pwd4 respectively.
Write a servelet for doing the following.
1. Create a Cookie and add these four user ids and
passwords to this Cookie.
63
64
HttpServlet
class
inherits
the
init
method
from
65
Class
66
Methods of ServletConfig
class
all
the
names
of
initialization
parameters
Returns
reference
to
the
Returns
name
of
the
Servlet
as
PROGRAM:
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>
67
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.*;
68
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);
res.addCookie(c4);
res.addCookie(p4);
out.println("COOKIE ADDED");
}
}
69
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("pwd
1"))||
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())) )
{
70
//RequestDispatcher
rd=req.getRequestDispatcher("/cart.html");
rd.forward(req,res);
}
else
{
out.println("YOU ARE NOT AUTHORISED USER ");
//res.sendRedirect("/cookdemo/cologin.html");
}
}
}
}
}
Web.xml:
<web-app>
<servlet>
<servlet-name>him</servlet-name>
<servlet-class>Clogin</servlet-class>
</servlet>
<servlet>
<servlet-name>him1</servlet-name>
<servlet-class>Addcook</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>him</servlet-name>
<url-pattern>/clogin</url-pattern>
</servlet-mapping>
71
<servlet-mapping>
<servlet-name>him1</servlet-name>
<url-pattern>/clogin1</url-pattern>
</servlet-mapping>
</web-app>
OUTPUT:
72
73
74
75
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());
76
else
out.println("You are not authorized user");
}
}
web.xml:
<web-app>
<servlet>
<servlet-name>Example</servlet-name>
<servlet-class>Example1</servlet-class>
<init-param>
<param-name>username1</param-name>
<param-value>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>
77
<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>
78
OUTPUT:
RESULT:
79
Week-9
Date:
-----------------------------------------------------------------------------------------------------------AIM:
Oracle).
Create a table which should contain at least the following
fields: name, password, email-id, phone number (these should
hold the data from the registration form).
Practice 'JDBC' connectivity.
Write a java program/servlet/JSP to connect to that database and
extract data from the tables and display them. Experiment with
various SQL queries.
80
Insert the details of the users who register with the web site,
whenever a new user clicks the submit button in the registration
page (week2).
DESCRIPTION:
81
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>
82
<td
colspan=2
align=center>
<input
type="submit"
83
<tr>
<td
align=center
colspan="2"><input
type="submit"
value="submit"></td> </tr>
</table> </center>
</form>
</body>
</html>
Ini.java:
import javax.servlet.*;
import java.sql.*;
import java.io.*;
public class Ini extends GenericServlet
{
private String user1,pwd1,email1;
public
void
service(ServletRequest
req,ServletResponse
res)
throws ServletException,IOException
{
user1=req.getParameter("user");
pwd1=req.getParameter("pwd");
email1=req.getParameter("email");
res.setContentType("text/html");
PrintWriter out=res.getWriter();
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
84
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@195.100.1
01.158:1521:cclab","scott","tiger");
PreparedStatement st=con.prepareStatement("insert into
personal values(?,?,?,?,?,?)");
st.setString(1,user1);
st.setString(2,pwd1);
st.setString(3,"25");
st.setString(4,"hyd");
st.setString(5,email1);
st.setString(6,"21234");
st.executeUpdate();
con.close();
}
catch(SQLException s)
{ out.println("not found "+s);
}
catch(ClassNotFoundException c)
{
out.println("not found "+c);
}
}}
web.xml:
<web-app>
<servlet>
<servlet-name>init1</servlet-name>
<servlet-class>Ini</servlet-class>
85
</servlet>
<servlet-mapping>
<servlet-name>init1</servlet-name>
<url-pattern>/regis</url-pattern>
</servlet-mapping>
</web-app>
OUTPUT:
86
87
88
89
RESULT:
Thus a table is created and the details are entered into the
table using jdbc from the registration form successfully.
90
Week-10
Date:
----------------------------------------------------------------------------------------------------------AIM: Write a JSP which does the following job
Insert the details of the 3 or 4 users who register with the
web site (week9) by using registration form. Authenticate the
user when he submits the login form using the user name and
password from
cookies).
DESCRIPTION:
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.
91
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() %>
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 %>
92
93
colspan="2"
align="center"><b> </td>
</tr>
<tr>
<td>User Name</td>
<td><input
type="text"
name="user"/></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password"
name="pwd"/></td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
<tr>
94
Auth.jsp:
<%@page import="java.sql.*;"%>
<html>
<head>
<title>
This is simple data base example in JSP</title>
</title>
</head>
<body bgcolor="yellow">
<%!String uname,pwd;%>
<%
uname=request.getParameter("user");
pwd=request.getParameter("pwd");
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
95
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@195.100.1
01.158:1521:CCLAB","scott","tiger");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select name,password from
personal where name='"+uname+"' and password='"+pwd+"'");
if(rs.next())
{
out.println("Authorized person");
}
else
{
out.println("UnAuthorized person");
}
con.close();
}
catch(Exception e){out.println(""+e);}
%>
</body>
</html>
OUTPUT:
96
97
RESULT:
The user is authenticated when he submits the login form using
the user name and password from the database.
Week-11:
Date:
----------------------------------------------------------------------------------------------------------AIM: Extract data from the tables and display them in the
catalogue page using JDBC.
DESCRIPTION:
Create tables in the database which contain the details of
items (books in our case like Book name, Price, Quantity,
Amount)) of each category. Modify your catalogue page (week 2)
in such a way that you should connect to the database and
extract data from the tables and display them in the catalogue
page using JDBC.
98
PROGRAM:
Retrieve.java:
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.io.*;
import java.util.*;
public class Retrieve extends HttpServlet
{
public void service(HttpServletRequest req,HttpServletResponse
res) throws ServletException,IOException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@195.100.1
01.158:1521:cclab","scott","tiger");
Statement s=con.createStatement();
ResultSet r=s.executeQuery("select * from cart");
out.println("<center> <table border=1>");
out.println("<thead> <th> Book name </th> <th> Price </th>
<th> Quantity </th> <th> Amount </th> </thead>");
while(r.next())
{
out.println("<tr> <td> "+r.getString(1)+"</td> ");
99
100
</servlet>
<servlet-mapping>
<servlet-name>set</servlet-name>
<url-pattern>/enterdata</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>display</servlet-name>
<url-pattern>/display1</url-pattern>
</servlet-mapping>
</web-app>
101
102
OUTPUT:
103
RESULT:
The data is extracted from the tables and displayed in the
catalogue page using JDBC.
Week-12:
Date:
----------------------------------------------------------------------------------------------------------AIM: Modify cart JSPpage to achieve the dynamism with the HTTP
protocol and session
management
DESCRIPTION:
HTTP is a stateless protocol. Session is required to
maintain the state.
Methods of session Object:
There are numerous methods available for session Object. Some
are:
getAttribute(String name)
104
getAttributeNames
isNew()
getCreationTime
getId
invalidate()
getLastAccessedTime
getMaxInactiveInterval
removeAttribute(String name)
setAttribute(String, object)
The <jsp:include> element allows you to include either static and
dynamic files in a JSP file.
Program :
Cart .java
import java.util.*;
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class Cart extends HttpServlet
{
public void init(ServletConfig config) throws
ServletException
105
{
super.init(config);
}
public void service(HttpServletRequest
req,HttpServletResponse res) throws
IOException,ServletException
{
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
HttpSession hs=req.getSession();
ArrayList cart=(ArrayList)hs.getAttribute("cart");
if(cart==null)
{
pw.println("No items in your cart");
cart=new ArrayList();
hs.setAttribute("cart",cart);
}
String itemselected[];
String item;
itemselected=req.getParameterValues("book");
if(itemselected!=null)
{
for(int i=0;i<itemselected.length;i++)
{
item=itemselected[i];
cart.add(item);
106
}}
pw.println("Items in the cart<br>");
Iterator it=cart.iterator();
while(it.hasNext())
{
pw.println("<br><b>"+it.next()+"</b>");
}
}
}
Catalogue.java
import java.util.*;
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class Catalogue extends HttpServlet
{
int itemcount=0;
public void init(ServletConfig config) throws
ServletException
{
super.init(config);
}
107
108
109
<init-param>
<param-name>username</param-name>
<param-value>syam</param-value>
</init-param>
<init-param>
<param-name>password</param-name>
<param-value>syam</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/login.do</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>cat</servlet-name>
<servlet-class>Catalogue</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>cat</servlet-name>
<url-pattern>/Cat</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>cart</servlet-name>
<servlet-class>Cart</servlet-class>
</servlet>
110
<servlet-mapping>
<servlet-name>cart</servlet-name>
<url-pattern>/cart</url-pattern>
</servlet-mapping>
</web-app>
111
112
Week 13:
Aim : Write a program to implement MVC architecture.
Description :
Model-View-Controller Pattern
Model-View-Controller (MVC) is a classic design pattern often
used by applications that need the ability to maintain multiple
views of the same data. The MVC pattern hinges on a clean
separation of objects into one of three categories models for
maintaining data, views for displaying all or a portion of the
data, and controllers for handling events that affect the model or
view(s).
Because of this separation, multiple views and controllers can
interface with the same model. Even new types of views and
controllers that never existed before can interface with a model
without forcing a change in the model design.
How It Works
The MVC abstraction can be graphically represented as follows.
113
114
The spinners data is held in a model that is shared with the text
field. The text field provides a view of the spinners current
value. Each button in the spinner is an event source, that
spawns an action event every time it is clicked. The buttons
can be hooked up to trampolines that receive action events, and
route them to an action listener that eventually handles that
event. Recall that a trampoline is a predefined action listener
that simply delegates action handling to another listener.
Depending on the source of the event, the ultimate action
listener either increments or decrements the value held in the
model The action listener is an example of a controller.
The trampolines that initially receive the action events fired by
the arrow buttons, are also controllers However, instead of
modifying the spinners model directly, they delegate the task to
a separate controller (action listener).
Multiple Controllers
The MVC pattern allows any number of controllers to modify the
same model. While we have so far focused only on the two arrow
buttons as likely source of events, there is, in fact, a third event
source in this example Whenever the text field has focus,
hitting the enter key fires off an action event that may
115
Program :
Eshop.jsp:
<%@ page session="true" %>
<html>
<head>
<title>BOOK STORE</title>
</head>
<body bgcolor="#33CCFF">
<font face="Times New Roman,Times" size="+3">
BOOK STORE
</font>
<hr><p>
<center>
<form name="shoppingForm"
action="ShoppingServlet"
method="POST">
116
<b>BOOK:</b>
<select name=BOOK>
<option> 10588 | Hans Bergsten | Java Server Pages | O'Reilly |
2 | 34.95</option>
<option> 10589 | Deitel | Internet |McGraw Hill | 4 |
44.95</option>
<option> 10590 | Winston | XML BIBLE |Wiley | 2 |
14.95</option>
</select>
<b>Quantity: </b><input type="text" name="qty" SIZE="3"
value=1>
<input type="hidden" name="action" value="ADD">
<input type="submit" name="Submit" value="Add to Cart">
</form>
</center>
<p>
<jsp:include page="Cart.jsp" flush="true" />
</body>
</html>
Cart.jsp:
<%@ page session="true" import="java.util.*, shopping.BOOK"
%>
<%
Vector
buylist
(Vector)
session.getValue("shopping.shoppingcart");
if (buylist != null && (buylist.size() > 0)) {
%>
117
<center>
<table
border="0"
cellpadding="0"
width="100%"
bgcolor="#FFFFFF">
<tr>
<td><b>ISBN</b></td>
<td><b>AUTHOR</b></td>
<td><b>TITLE</b></td>
<td><b>PUBLISHER</b></td>
<td><b>EDITION</b></td>
<td><b>PRICE</b></td>
<td><b>QUANTITY</b></td>
<td></td>
</tr>
<%
for (int index=0; index < buylist.size();index++) {
BOOK anOrder = (BOOK) buylist.elementAt(index);
%>
<tr>
<td><b><%= anOrder.getisbn() %></b></td>
<td><b><%= anOrder.getAuthor() %></b></td>
<td><b><%= anOrder.getTitle() %></b></td>
<td><b><%= anOrder.getPublisher() %></b></td>
<td><b><%= anOrder.getEdition() %></b></td>
<td><b><%= anOrder.getPrice() %></b></td>
<td><b><%= anOrder.getQuantity() %></b></td>
<td>
<form name="deleteForm"
action="ShoppingServlet"
118
method="POST">
<input type="submit" value="Delete">
<input type="hidden" name= "delindex" value='<%= index
%>'>
<input type="hidden" name="action" value="DELETE">
</form>
</td>
</tr>
<% } %>
</table>
<p>
<form name="checkoutForm"
action="ShoppingServlet"
method="POST">
<input type="hidden" name="action" value="CHECKOUT">
<input type="submit" name="Checkout" value="Checkout">
</form>
</center>
<% } %>
Checkout.jsp:
<%@ page session="true" import="java.util.*, shopping.BOOK"
%>
<html>
<head>
<title>BOOK STORE</title>
</head>
<body bgcolor="#33CCFF">
<font face="Times New Roman,Times" size=+3>
119
border="0"
cellpadding="0"
width="100%"
bgcolor="#FFFFFF">
<tr>
<td><b>ISBN</b></td>
<td><b>AUTHOR</b></td>
<td><b>TITLE</b></td>
<td><b>PUBLISHER</b></td>
<td><b>EDITION</b></td>
<td><b>PRICE</b></td>
<td><b>QUANTITY</b></td>
<td></td>
</tr>
<%
Vector
buylist
(Vector)
session.getValue("shopping.shoppingcart");
String amount = (String) request.getAttribute("amount");
for (int i=0; i < buylist.size();i++) {
BOOK anOrder = (BOOK) buylist.elementAt(i);
%>
<tr>
<td><b><%= anOrder.getisbn() %></b></td>
<td><b><%= anOrder.getAuthor() %></b></td>
<td><b><%= anOrder.getTitle() %></b></td>
<td><b><%= anOrder.getPublisher() %></b></td>
120
</td>
<td>
</td>
<td><b>TOTAL</b></td>
<td><b>$<%= amount %></b></td>
<td>
</td>
</tr>
</table>
<p>
<a href="Eshop.jsp">Shop some more!</a>
</center>
</body>
</html>
Error.html:
<html>
<body>
<h1>
Sorry, there was an unrecoverable error! <br>
Please
try
<a
href="/examples/jsp/shopping/EShop.jsp">again</a>.
121
</h1>
</body>
</html>
OUTPUT:
Web.xml:
<web-app>
<servlet>
<servlet-name>ShoppingServlet</servlet-name>
122
<servlet-class>ShoppingServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ShoppingServlet</servlet-name>
<url-pattern>/ShoppingServlet</url-pattern>
</servlet-mapping>
</web-app>
ShoppingServlet.java:
import java.util.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import shopping.BOOK;
public class ShoppingServlet extends HttpServlet {
public void init(ServletConfig conf) throws ServletException {
super.init(conf);
}
public
void
doPost
(HttpServletRequest
req,
HttpServletResponse res)
throws ServletException, IOException {
HttpSession session = req.getSession(false);
if (session == null) {
res.sendRedirect("/error.html");
}
Vector
buylist=(Vector)session.getValue("shopping.shoppingcart");
String action = req.getParameter("action");
123
if (!action.equals("CHECKOUT")) {
if (action.equals("DELETE")) {
String del = req.getParameter("delindex");
int d = (new Integer(del)).intValue();
buylist.removeElementAt(d);
} else if (action.equals("ADD")) {
boolean match=false;
BOOK aCD = getBOOK(req);
if (buylist==null) {
buylist = new Vector(); //first order
buylist.addElement(aCD);
} else { // not first buy
for (int i=0; i< buylist.size(); i++) {
BOOK cd = (BOOK) buylist.elementAt(i);
if (cd.getTitle().equals(aCD.getTitle())) {
cd.setQuantity(cd.getQuantity()+aCD.getQuantity());
buylist.setElementAt(cd,i);
match = true;
} //end of if name matches
} // end of for
if (!match)
buylist.addElement(aCD);
}
}
session.putValue("shopping.shoppingcart", buylist);
String url="/Eshop.jsp";
//
ServletContext sc = getServletContext();
RequestDispatcher rd = req.getRequestDispatcher(url);
124
rd.forward(req, res);
}
else if (action.equals("CHECKOUT")) {
float total =0;
for (int i=0; i< buylist.size();i++) {
BOOK anOrder = (BOOK) buylist.elementAt(i);
float price= anOrder.getPrice();
int qty = anOrder.getQuantity();
total += (price * qty);
}
total += 0.005;
String amount = new Float(total).toString();
int n = amount.indexOf('.');
amount = amount.substring(0,n+3);
req.setAttribute("amount",amount);
String url="/Checkout.jsp";
ServletContext sc = getServletContext();
RequestDispatcher rd = sc.getRequestDispatcher(url);
rd.forward(req,res);
}
}
private BOOK getBOOK(HttpServletRequest req) {
String myBOOK = req.getParameter("BOOK");
String qty = req.getParameter("qty");
StringTokenizer t = new StringTokenizer(myBOOK,"|");
String isbn= t.nextToken();
String author= t.nextToken();
125
126
author="";
title="";
publisher="";
Edition="";
price=0;
quantity=0;
}
public void setPublisher(String title1) {
publisher=title1;
}
public String getPublisher() {
return publisher;
}
public void setEdition(String group1) {
Edition=group1;
}
public String getEdition() {
return Edition;
}
public void setisbn(String title) {
isbn=title;
}
public String getisbn() {
return isbn;
}
public void setAuthor(String group) {
author=group;
}
127
128
OUTPUT:
129
130
RESULT: Thus the cart page is dynamited with HTTP sessions and
useBean concept.
Experiment :14
Aim : Write a program to implement custom tag libraries
in JSP
Description :
Program :
First.jsp
<%@ taglib uri="hello" prefix="examples"%>
<html>
<head>
<title>First Custom tags</title>
</head>
<body>
<i><examples:hello/>
</i>
</body>
</html>
Web.xml
<web-app>
<taglib>
<taglib-uri>hello</taglib-uri>
<taglib-location>/WEB-INF/tlds/hello.tld</taglib-location>
131
</taglib>
</web-app>
Create a folder called tlds in WEB-INF directory.
Hello.tld
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<tag>
<name>hello</name>
<tag-class>tagext.HelloTag</tag-class>
<body-content>JSP</body-content>
</tag>
</taglib>
HelloTag.java
package tagext;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.TagSupport;
import java.util.*;
public class HelloTag extends TagSupport
{
public int doStartTag()
{
return EVAL_BODY_INCLUDE;
}
132
name
is :"+getClass().getName()+"and it's"+date);
}catch(Exception e){}
return EVAL_PAGE;
}
}
133
Output
Result :
Thus the implementation of custom tag libraries in JSP is
done.
Experiment No : 14
Aim : Display Hello World using Struts Framework in
NetBeans.
134
Step 2:
135
Step 3:
Step 4:
136
step 5:
step 6:
137
step 7:
step 8:
138
step 9:
139