You are on page 1of 42

Exp No: 4.

Date:
Registration Page Validation using Java Script
Aim: To write a JavaScript program to validate the following fields of the registration page.
1. Name (Name should contain alphabets and the length should not be less than 6
characters).
2. Password (Password should not be less than 6 characters length).
3. E-mail id (should not contain any invalid and must follow the standard pattern
name@domain.com)
4. Phone number (Phone number should contain 10 digits only).

Description: To insert a JavaScript into a HTML page, we use the <script> tag. Inside the
<script> tag we use the type attribute to define the scripting language. We can use regular
expressions to validate the fields of the registration page. The fields are placed in the body part
of the document; at the time of submitting form those fields will be submitted to a JavaScript
function for validations.

Program:
<html>
<head><title>Sample Program</title>
<script language="javascript">
function validate_form()
{ var name_regex = /[^a-zA-Z ]/;
var email_regex = /^[a-zA-Z0-9._-]+@([a-zA-Z0-9.-]+\.)+[a-zA-Z0-9.-]{2,4}$/;
var phone_regex = /[^0-9]/;
var name = document.form.txtName.value;
var pass = document.form.txtPass.value;
var email = document.form.txtEmail.value;
var phone = document.form.txtPhone.value;
if( name_regex.test( name ) )
{ window.alert("Name must contain characters only");
return false;
}
if ( name.length < 6 )
{ window.alert("Name must contain atleast 6 characters");
return false;
}
if ( pass.length < 6 )
{ window.alert("Password must contain atleast 6 characters length");
return false;
}
if ( ( (email.length> 0) && ( email_regex.test( email ) ) ) != true )
{ window.alert("Email must follow the standard pattern name@domain.com ");
return false;
}
if( phone_regex.test( phone) )
{ window.alert("Phone number should contain digits only");
return false;

Web Technologies Lab Page 1


}
if ( phone.length != 10 )
{ window.alert("Phone number should contain 10 digits");
return false;
}
else
return true;
}
</script>
</head>
<body bgcolor="bisque">
<form name="form" method= "post" action="" onSubmit="return validate_form()">
<table align="center" >
<caption><h3>Registration Form </h3></caption>
<tr><td>Name</td>
<td><input type="text" size=30 name="txtName"></td></tr>
<tr><td>Password</td>
<td><input type="password" size=30 name="txtPass"></td></tr>
<tr><td>Email ID</td>
<td><input type="text" size=30 name="txtEmail"></td></tr>
<tr><td>Phone No.</td>
<td><input type="text" size=30 name="txtPhone"></td></tr>
<tr><td>Gender</td>
<td><input type="Radio" name="g1" value="Male">Male &nbsp;&nbsp;&nbsp;
<input type="Radio" name="g1" value="Female">Female</td></tr>
<tr><td>DOB</td>
<td><select name="dd">
<option value="1">1</option> <option value="2">2</option> <option value="3">3</option>
<option value="4">4</option> <option value="5">5</option> <option value="6">6</option>
<option value="7">7</option> <option value="8">8</option> <option value="9">9</option>
<option value="10">10</option> <option value="11">11</option> <option
value="12">12</option>
<option value="13">13</option> <option value="14">14</option> <option
value="15">15</option>
<option value="16">16</option> <option value="17">17</option> <option
value="18">18</option>
<option value="19">19</option> <option value="20">20</option> <option
value="21">21</option>
<option value="22">22</option> <option value="23">23</option> <option
value="24">24</option>
<option value="25">25</option> <option value="26">26</option> <option
value="27">27</option>
<option value="28">28</option> <option value="29">29</option> <option
value="30">30</option> <option value="31">31</option>
</select> &nbsp;&nbsp;&nbsp;
<select name="mm">
<option value="1">1</option> <option value="2">2</option> <option
value="3">3</option>

Web Technologies Lab Page 2


<option value="4">4</option> <option value="5">5</option> <option
value="6">6</option>
<option value="7">7</option> <option value="8">8</option> <option
value="9">9</option>
<option value="10">10</option> <option value="11">11</option> <option
value="12">12</option>
</select> &nbsp;&nbsp;&nbsp;
<select name="yyyy">
<option value="1991">1991</option> <option value="1992">1992</option>
<option value="1993">1993</option> <option value="1994">1994</option>
<option value="1995">1995</option> <option value="1996">1996</option>
<option value="1997">1997</option> <option value="1998">1998</option>
<option value="1999">1999</option> <option value="2000">2000</option>
<option value="2001">2001</option> <option value="2002">2002</option>
</select>
</td></tr>
<tr><td>Languages Known:</td>
<td><input type="checkbox" value="Telugu" name="ch1">Telugu &nbsp;&nbsp;&nbsp;
<input type="checkbox" value="English" name="ch2">English &nbsp;&nbsp;&nbsp;
<input type="checkbox" value="Hindi" name="ch3">Hindi&nbsp;&nbsp;&nbsp;
<input type="checkbox" value="Tamil" name="ch4">Tamil &nbsp;&nbsp;&nbsp;
</td></tr>
<tr><td><center><input type="submit" value="Submit" name="bt1"></center></td>
<td><center><input type="submit" value="Reset" name="bt2"></center></td>
</tr> </table></form>
</body></html>

Output:

Web Technologies Lab Page 3


Conclusion: The fields placed in the body part of the document are read using document object
when the form is submitted. The registration page is validated successfully using regular
expressions of Java Script.

Web Technologies Lab Page 4


Exp No: 5. Date:
DTD & XSL for XML File
Aim: To write an XML file which will display the Book information which includes the
following:
1) Title of the book 2) Author Name 3) ISBN number
4) Publisher name 5) Edition 6) Price
To write a Document Type Definition (DTD) to validate the above XML file and to display the
XML file as follows. The contents should be displayed in a table. The header of the table should
be in color GRAY and the Author names column should be displayed in one color and in bold.
By using our own colors for remaining columns the contents should be displayed.

Description: The XML document contains data whereas DTD file contains rules that apply to
the data. A DTD is a file with a dot dtd (filename.dtd) extension. The contents of these files are
purely textual in nature. A DOCTYPE declaration in an XML document specifies that we want to
include a reference to a DTD file. XSL is a language for expressing style sheets. With XSL a
template is created and this template is used to format XML elements which match a specified
pattern.

Program:
book.dtd

Web Technologies Lab Page 5


<!ELEMENT bookdetails (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)>
book.xml
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="book.xsl"?>
<!DOCTYPE book SYSTEM "book.dtd">
<bookdetails>
<book>
<title>XML Bible</title>
<author>Elliotte Rusty Harold</author>
<isbn>9876543210</isbn>
<publisher>Hungry Minds</publisher>
<edition>4th</edition>
<price>$21.99</price>
</book>
<book>
<title>Artificial Intelligence: A Modern Approach</title>
<author>Stuart J. Russell</author>
<isbn>9876543220</isbn>
<publisher>Princeton Hall</publisher>
<edition>6th</edition>
<price>$36.09</price>
</book>
<book>
<title>Beginning Java 2</title>
<author>Ivor Horton</author>
<isbn>9876543220</isbn>
<publisher>wrox</publisher>
<edition>3th</edition>
<price>$8.95</price>
</book>
<book>
<title>HTML5: Up and Running</title>
<author>Mark Pilgrim</author>
<isbn>1234567890</isbn>
<publisher>O'REILLY</publisher>
<edition>1st</edition>
<price>$17.99</price>
</book>
</bookdetails>
book.xsl
<?xml version="1.0" encoding="ISO-8859-1"?>

Web Technologies Lab Page 6


<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h2 style="color:green;" align="center">Books</h2>
<table border="1" align="center">
<tr style="color:gray;">
<th>Title</th><th>Author</th><th>ISBN</th>
<th>Publisher</th> <th>Edition</th> <th>Price</th>
</tr>
<xsl:for-each select="bookdetails/book">
<tr> <td style="font-family:'Comic Sans MS'; color:red;">
<xsl:value-of select="title"/></td>
<td style="text-transform: capitalize; font-weight:bold;"
align="center"> <xsl:value-of select="author"/></td>
<td style="color:blue">
<xsl:value-of select="isbn"/></td>
<td style="color:green; font-weight:bold;" align="center">
<xsl:value-of select="publisher"/></td>
<td style="pink" align="center">
<xsl:value-of select="edition"/></td>
<td style="color:violet; font-weight:bold;">
<xsl:value-of select="price"/></td> </tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>

Output:

Web Technologies Lab Page 7


Conclusion: XML file is validated using a Document Type Definition (DTD) and the contents
of the XML file are displayed in a table with different colors using XSL successfully.

Web Technologies Lab Page 8


Exp No: 6. Date:
Visual Beans
Aim: To create a simple visual bean with area filled with a color. The shape of the area depends
on the property shape. If it is 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:
Steps to create a Java-Bean:
1) Create a new directory in C:\beans\demo\sunw\demo with a new folder name colors
2) Create a java source file
3) Compile the java source file
4) Create a manifest file colors.mft in the directory called as C:\beans\demo
5) Create a jar file- to create a jar file type the following command in the command prompt
jar cfm ..\jars\colors.jar colors.mft sunw\demo\colors\*.class
6) Start the BDK
7) Check whether the colors bean is placed in toolbox or not
8) Create an Instance of the Colors Bean After you complete the preceding steps, create an
instance of the Colors Bean in the BeanBox window. Test your new component by
pressing the mouse anywhere within its borders. Its color immediately changes. Use the
Properties window to change the rectangular property from false to true. Its shape
immediately changes.

Program: Colors.java
package sunw.demo.colors;
import java.awt.*;
import java.awt.event.*;
public class Colors extends Canvas
{ transient private Color color;
private boolean rectangular;
public Colors()
{ addMouseListener(new MouseAdapter()
{ public void mousePressed(MouseEvent me)
{ change();
}
});
rectangular = false;
setSize(200, 200);
change();
}
public boolean getRectangular()
{ return rectangular;
}
public void setRectangular(boolean flag)
{ this.rectangular = flag;
repaint();
}

Web Technologies Lab Page 9


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;
g.setColor(color);
if(rectangular)
{ g.fillRect(0, 0, w-1, h-1);
}
else
{ g.fillOval(0, 0, w-1, h-1);
}
}
}

colors.mft
Name: sunw/demo/colors/Colors.class
Java-Bean: True

Output:

Web Technologies Lab Page 10


Conclusion: A simple visual bean with area filled with a color is created. Depends on the
property shape, it is set to Square or Circle. The color of the area is changed dynamically for
every mouse click successfully.

Exp No: 7. a) Date:


Tomcat Installation
Aim: To install TOMCAT web server and While installation assign port number 8000 to
TOMCAT. Make sure that this port is available i.e., no other process is using this port.

Procedure:

 By double clicking on the Apache Tomcat software it will get installed.

 Please review the license terms before installing Apache Tomcat.

Web Technologies Lab Page 11


 Choose which features of Apache Tomcat you want to install.

 By default Tomcat will take port no as 8080. If you want, you can change that port
number to 8000.

Web Technologies Lab Page 12


 Installation requires Java Virtual Machine path selection

Web Technologies Lab Page 13


 Choose installation location

 Apache Tomcat has been installed on your computer.

Web Technologies Lab Page 14


Conclusion: Apache Tomcat is installed successfully with the specified port number.

Exp No: 7. b) Date:


Accessing Web Pages Using Tomcat Server
Aim: To access the previous developed static web pages for books web site, using TOMCAT server by
putting the web pages developed in week-1 and week-2 in the document root.

Procedure: According to javasoft a web application is a collection of web resources. The web
resource can be a static resource like HTML/XML/WML etc or dynamic resource like CGI,
Servlet etc.
 Create a directory in C:\Program Files\Apache Software Foundation\Tomcat 7.0\
webapps\ to place everything related to the web application. This directory can be called
as webroot or document root. (e.g. \ourwapp)
 Under webroot create a directory with the name WEB-INF (e.g. \ourwapp\WEB-INF)
 Under WEB-INF create the following two directories and web.xml file:
o classes
o lib
o web.xml

The jar files that are required for the web application must be stored under the lib folder.
The java classes must be stored under classes folder. Place the static resources under the
webroot directory or subdirectory of webroot directory (i.e. HTML/XML files).

Web Technologies Lab Page 15


C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps\

ourwapp

WEB-INF

classes

lib

web.xml

login.html, registration.html, cart.html, home.html etc.

Output:

Conclusion: The web pages developed in week-1 and week-2 is placed in the document root and the
web pages are accessed successfully.

Web Technologies Lab Page 16


Exp No: 8. a) Date:
Setting Cookies
Aim: To write a servlet program to create a Cookie by getting values from login page. The login
page contains two fields one is login name and other one is password. While creating cookie
consider login name as cookie name and password as its value.

Description: First login name and password must be submitted from login page to the servlet.
In the servlet the parameters are read from login page and then cookie is created with that data.
To create cookie Cookie class is used. Java Servlets transparently supports HTTP cookies. Server
script sends a set of cookies to the browser. Browser stores this information on local machine for
future use. While creating a cookie we must provide a name and a value for that cookie. In this
program consider login name as cookie name and password as its value.

Program:
Login.html
<html><head><title>Login Page</title>
</head>
<body bgcolor="d3d3d3">
<form method=”post” action=”test1”>

Web Technologies Lab Page 17


<table border="0"align="center" cellspacing="5"cellpading="5">
<caption><h1>Login Page</h1></caption>
<tr> <td>Login:</td>
<td><input type="text" Name="textName" size="30"></td></tr>
<tr> <td>Password:</td>
<td><input type= "Password" name="Password1"size="30"></td></tr>
<tr> <td><input type="submit" name="submit" value="submit"></td>
<td><input type="submit" name="Submit" value="Reset"></td> </tr>
</table></form>
</body>
</html>
SetCookie.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class SetCookie extends HttpServlet
{ public void service(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
{
res.setContentType ("text/html");
PrintWriter out = res.getWriter();
//Getting values from the login form
String name = req.getParameter("textName");
String pass = req.getParameter("password1");
//setting cookie
Cookie c1=new Cookie (name,pass);
res.addCookie (c1);
out.println ("SUCCESSFUL IN SETTING COOKIE");
}
}
web.xml
<web-app> <servlet>
<servlet-name>abc</servlet-name>
<servlet-class>SetCookie</servlet-class>
</servlet>
<servlet-mapping> <servlet-name>abc</servlet-name>
<url-pattern>/test1</url-pattern>
</servlet-mapping>
</web-app>

Output:

Web Technologies Lab Page 18


Web Technologies Lab Page 19
Conclusion: Cookie class is used to create cookie with login form data and when the cookie is
created successfully, the message is displayed properly.

Web Technologies Lab Page 20


Exp No: 8. b) Date:
Reading Cookies
Aim: To Write a Servlet Program to read a cookie and to compare cookie name and its value
with initialization parameters. If cookie name and its value is equivalent with any one of the four
initialization parameter and its value then a welcome message with cookie name will be
displayed otherwise a message like “you are not a valid user” will be displayed.

Description: Java Servlets transparently supports HTTP cookies. Server script sends a set of
cookies to the browser. Browser stores this information on local machine for future use. Get
cookie name and its value by using getCookies() method and store these details in two variables
and then compare it with initialization parameters by reading it by using ServletConfig object to
two variables. Compare the variables respectively and if the match is found then display
welcome message otherwise display an error message.

Program: ShowCookie.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
public class ShowCookie extends HttpServlet
{ public void service (HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
{ String user1,pass1,user2,pass2;
PrintWriter out = null;
boolean flag = false;
res.setContentType ("text/html");
out = res.getWriter ();
Cookie ck []= req.getCookies ();
if (ck!=null)
{ user1 = ck [0].getName ();
pass1 = ck [0].getValue ();
// reading init parameters
ServletConfig config=getServletConfig ();
Enumeration en=config.getInitParameterNames ();
while (en.hasMoreElements ())
{ Object obj=en.nextElement ();
user2= (String) obj;
pass2=config.getInitParameter (user2);
if( user1.equals(user2) && pass1.equals(pass2) )
flag = true;
}
if( flag == true)
out.println("<h1>Welcome " + user1+"</h1>");
else
out.println("<h1>You are not an authenticated user");
}
else

Web Technologies Lab Page 21


{ System.out.println ("NO COOKIES PRESENT");
}
}
}
web.xml
<web-app>
<servlet><servlet-name>pqr</servlet-name>
<servlet-class>ShowCookie</servlet-class>
<init-param> <param-name>kishore</param-name>
<param-value>kumar</param-value>
</init-param>
<init-param> <param-name>hari</param-name>
<param-value>prasad</param-value>
</init-param>
<init-param> <param-name>Ravi Kumar</param-name>
<param-value>Krishna</param-value>
</init-param>
<init-param> <param-name>usha</param-name>
<param-value>priya</param-value>
</init-param>
</servlet>
<servlet-mapping> <servlet-name>pqr</servlet-name>
<url-pattern>/test2</url-pattern>
</servlet-mapping>
</web-app>

Output:

Web Technologies Lab Page 22


Conclusion: Cookies are read by using getCookies() method of request object and then the same
is compared with initialization parameters of servlet successfully and the respective message is
displayed properly.

Web Technologies Lab Page 23


Exp No: 9. Date:
Servlet Program to Store & Display Details using JDBC
Aim: To write a Servlet program to store details like name, password, email-id, phone number
using JDBC and display all the records.

Description: First we can create a table to store details like name, password, email-id, phone
number in oracle. By writing a Java Servlet program, first oracle thin driver can be loaded then
connection has to be established. After getting connection query the database using insert query
with the values by using prepared statement. After inserting the values into the database display
all the records that are available in that table.

Program:
registration table (ORACLE)
create table registration (uname varchar2(20), pass varchar2(20), email varchar2(20), phone
varchar2(20));
register.html
<html> <head><title>Registration page</title>
</head>
<body><form METHOD="POST" ACTION="rrr">
<CENTER><h1>REGISTRATION FORM</h1></center><br><br>

Web Technologies Lab Page 24


<center> <table>
<tr> <td> Username </td>
<td><input type="text" name="user"> </td> </tr>
<tr><td> Password </td>
<td><input type="password" name="pwd"> </td> </tr>
<tr> <td>Email</td>
<td> <input type="text" name="email"> </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>
</table> </center>
</form></body></html>
RegForm.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.io.*;
public class RegForm extends HttpServlet
{ String user1,pwd1,email1,phone1;
PrintWriter out = null;
Connection con =null;
PreparedStatement pstmt = null;
Statement stmt = null;
ResultSet rs = null;
public void service(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
{ user1=req.getParameter("user");
pwd1=req.getParameter("pwd");
email1=req.getParameter("email");
phone1 = req.getParameter("phone");
res.setContentType("text/html");
out=res.getWriter();
try
{ //code to store the record
Class.forName ("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:XE","system","manager");
pstmt=con.prepareStatement("insert into registration values (?,?,?,?)");
pstmt.setString(1,user1);
pstmt.setString(2,pwd1);
pstmt.setString(3,email1);
pstmt.setString(4,phone1);
pstmt.executeUpdate();
//code to retrieve and display all the records
stmt = con.createStatement();
rs = stmt.executeQuery("select * from registration");
out.println("<center><b>Registration Details</b><br><br>");

Web Technologies Lab Page 25


out.println("<table border=\"2\"><tr><th>User
Name</th><th>Password</th> <th>EmailId</th> <th>Phone Number</th></tr> " );
while( rs.next() )
{ out.println("<tr><td>" + rs.getString(1) + "</td>");
out.println("<td>" + rs.getString(2) + "</td>");
out.println("<td>" + rs.getString(3) + "</td>");
out.println("<td>" + rs.getString(4) + "</td></tr>");
}
out.println("</table></center>");
con.close();
}
catch(Exception e)
{ out.println( e );
}
}
}
web.xml
<web-app>
<servlet> <servlet-name>reg</servlet-name>
<servlet-class>RegForm</servlet-class>
</servlet>
<servlet-mapping> <servlet-name>reg</servlet-name>
<url-pattern>/rrr</url-pattern>
</servlet-mapping>
</web-app>

Output:

Web Technologies Lab Page 26


Web Technologies Lab Page 27
Conclusion: A table is created in oracle successfully. By using JDBC the values in the form are
accessed into servlet program first then the same is inserted into the database and finally all the
records in the database are displayed successfully.

Web Technologies Lab Page 28


Exp No: 10. Date:
JSP page to Authenticate Login Form

Aim: To write a JSP program to authenticate login information of a user by reading the data from
the database using JDBC connection.

Description: First we must create a database table with some values. After creating a table we
must design login web page and when submit button is clicked in the login web page the details
must be submitted to the JSP page. In the JSP page the user details will be fetched from the
database table and the same is compared with the login form data. If the match is found then
display welcome message otherwise display an error message.

Program:
registration table (ORACLE)
create table registration (uname varchar2(20), pass varchar2(20), email varchar2(20), phone
varchar2(20));
Login.html
<html><head>
<title>Login Page</title></head>
<body bgcolor="d3d3d3">
<form method="post" action="validate.jsp">
<table border="0"align="center" cellspacing="5"cellpading="5">
<caption><h1>Login Page</h1></caption>
<tr> <td>Login:</td>
<td><input type="text" Name="textName" size="30"></td>
</tr>
<tr> <td>Password:</td>
<td><input type= "Password" name="Password1"size="30"></td>
</tr>
<tr> <td><input type="submit" name="submit" value="submit"></td>
<td><input type="submit" name="Submit" value="Reset"></td>
</tr>
</table> </form>
</body>
</html>
validate.jsp
<%@ page import="java.sql.*" %>
<% String user1 = request.getParameter("textName");
String pass1 = request.getParameter("Password1");
boolean flag = false;
try
{ Class.forName ("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:XE","system","manager");
Statement stmt = con.createStatement();

Web Technologies Lab Page 29


ResultSet rs = stmt.executeQuery("select uname,pass from emp");
while( rs.next() )
{ String user2 = rs.getString(1);
String pass2 = rs.getString(2) ;
if( user1.equals(user2) && pass1.equals(pass2) )
flag = true;
}
if ( flag == true)
out.println("<h1>Welcome " + user1 + "</h1>");
else
out.println("<h1>You are not an authenticated user");
con.close();
}
catch(Exception e)
{ out.println( e );
}
%>

Output:

Web Technologies Lab Page 30


Conclusion: A table is created with some values in oracle successfully. The login form data is
read by using request implicit object and by using JDBC the values in the table are accessed into
JSP program then the same is compared; finally the respective message is displayed.

Web Technologies Lab Page 31


Exp No: 11. Date:
Modifying Catalogue Page

Aim: To create a table in the database which contains the details of items (books in our case like
Book name, Author, Publisher, Price) 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.

Description: First we must create a database table with some values. After creating a table we
must design modification web page with the field book name and submit button. When submit
button is clicked the details of the respective book will be displayed by using a JSP page. After
modifications and updations the details will be submitted to another JSP page which will update
the data to the database and by using the same JSP page the details in the database table will be
displayed back.

Program:
Book_details database (oracle)
Create table book_details( name varchar2(50), author varchar2(50), publisher varchar2(50), price
number);
Modify.html
<html><head>
<title>Catalogue Modification</title></head>
<body bgcolor=”d3d3d3”>
<form method=”post” action=”modify.jsp”>
<table border=”0”align=”center” cellspacing=”5”cellpading=”5”>
<caption><b>Modification of Catalogue</b></caption>
<tr><td>Book Name :</td>
<td><input type=”text” name=”bookname” length=”70”></td>
</tr>
<tr> <td><input type=”submit” name=”submit” value=”Get Details”></td>
<td><input type=”reset” name=”reset” value=”Reset”></td>
</tr></table>
</form>
</body>
</html>
modify.jsp
<%@ page import="java.sql.*" %>
<% response.setContentType("text/html");
String bname = request.getParameter("bookname");
try
{ Class.forName ("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:XE","system","manager");
PreparedStatement pstmt = con.prepareStatement("select * from book_details
where name = ?");
pstmt.setString( 1,bname);

Web Technologies Lab Page 32


ResultSet rs = pstmt.executeQuery();
while( rs.next() )
{
%>
<form method="post" action="getdata.jsp">
<center><h1>Modification of Catalogue Details</h1>
<table border="2"align="center" cellspacing="5"cellpading="5" bgcolor="bisque">
<tr><th><%= "Book Name" %></th><td><input type="text" name="bname" value = <
%= rs.getString(1)%> ></td></tr>
<tr><th><%= "Author" %></th><td><input type="text" name="bauthor" value = <%=
rs.getString(2)%> ></td></tr>
<tr><th><%= "Publisher" %></th><td><input type="text" name="bpublisher" value = <
%= rs.getString(3)%> ></td></tr>
<tr><th><%= "Price" %></th><td><input type="text" name="bprice" value = <%=
rs.getString(4)%> ></td></tr>
<tr><td><input type="submit" name="submit" value="submit"></td>
<td><input type="reset" name="reset" value="Reset"></td>
</tr></table></center></form>
<% }
con.close();
}
catch(Exception e)
{ out.println( e );
}
%>
getdata.jsp
<%@ page import="java.sql.*" %>
<% String name = request.getParameter("bname");
String author = request.getParameter("bauthor");
String publisher = request.getParameter("bpublisher");
double price = Double.parseDouble( request.getParameter("bprice") );
try
{ Class.forName ("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:XE","system","manager");
PreparedStatement pstmt = con.prepareStatement("update book_details set name
= ? , author = ? , publisher = ? , price = ? where name = ? ");
pstmt.setString(1, name);
pstmt.setString(2, author);
pstmt.setString(3, publisher);
pstmt.setDouble(4, price);
pstmt.setString(5, name);
pstmt.executeUpdate();
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from book_details");
%>
<center><h1>Modified Catalogue Details</h1>;

Web Technologies Lab Page 33


<table border="2" align="center" cellspacing="5" cellpading="5"
bgcolor="bisque" >
<tr><th>Book Name</th>
<th>Author</th>
<th>Publisher</th>
<th>Price</th></tr>
<% while( rs.next() )
{
%>

<tr><td><%= rs.getString(1)%> </td>


<td> <%= rs.getString(2)%></td>
<td><%= rs.getString(3)%> </td>
<td><%= rs.getString(4)%> </td></tr>
<% }
%> </tr></table></center></form>
<% con.close();
}
catch(Exception e)
{ out.println( e );
}
%>

Output:

Web Technologies Lab Page 34


Web Technologies Lab Page 35
Web Technologies Lab Page 36
Conclusion: The details from the database for the respective book are fetched by using JDBC
connection into a JSP page. After updating book details the updated details are stored
successfully back into the database and all the books information is displayed successfully.

Web Technologies Lab Page 37


Exp No: 12. Date:
Session Tracking

Aim: HTTP is a stateless protocol. Session is required to maintain the state. The user may add
some items to cart from the catalog page. He can check the cart page for items. He may visit
catalogue again and select some more items. Here our interest is the selected items should be
added to older cart rather than new cart.

Description: HttpSession object is used to store entire session with a specific client. We can
store, retrieve and remove attribute from HttpSession object. Any servlet can have access to
HttpSession object through the getSession() method of the HttpServletRequest object. On client's
first request, the Web Container generates a unique session ID and gives it back to the client with
response. The client sends back the session ID with each request. The Web Container uses this
ID, finds the matching session with the ID and associates the session with the request.

Program:
Catalogue.java
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

Web Technologies Lab Page 38


public class Catalogue extends HttpServlet
{ int itemcount=0;
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)
{
itemcount=cart.size();
}
pw.println("Select items in cart");
pw.println("<body><fieldset><legend>Catalogue</legend>" + "<form
action='cart' method='get'>" + "<input type='checkbox' value='XML Bible' name='book'>XML
Bible</input><br>");
pw.println("<input type='checkbox' name='book' value='Artificial Intelligence: A
Modern Approach'>Artificial Intelligence: A Modern Approach</input><br>");
pw.println("<input type='checkbox' name='book' value='Beginning
Java2'>Beginning Java 2</input><br>");
pw.println("<input type='checkbox' name='book' value='HTML5: Up and
Running'>HTML5: Up and Running</input><br>");
pw.println("<input type='submit' value='Add to cart'>");
pw.println("</fieldset>");
}
}

Cart.java
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Cart extends HttpServlet
{
public void service(HttpServletRequest req,HttpServletResponse res)throws
IOException, ServletException
{
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
HttpSession hs=req.getSession();
ArrayList<String> cart=(ArrayList<String>)hs.getAttribute("cart");
if(cart==null)
{
pw.println("No items in your cart");
cart=new ArrayList<String>();
hs.setAttribute("cart",cart);
}

Web Technologies Lab Page 39


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);
}
}
pw.println("Items in the cart<br>");
Iterator it=cart.iterator();
while(it.hasNext())
{
pw.println("<br><b>"+it.next()+"</b>");
}
}
}

web.xml
<web-app>
<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>
<servlet-mapping>
<servlet-name>cart</servlet-name>
<url-pattern>/cart</url-pattern>
</servlet-mapping>
</web-app>

Output:

Web Technologies Lab Page 40


Web Technologies Lab Page 41
Conclusion: The user can successfully add any number of items to the old cart page from the
catalogue page available. The items are added to the old cart page only with out creating new
cart page using session tracking mechanism.

Web Technologies Lab Page 42

You might also like