Sunteți pe pagina 1din 65

Program No:1

Objective: - To Write an HTML/Java Scripts code to display your CV in


navigator.

Software Required:-
S. No. Name of Software Specifications
1. Notepad --
2. Web Browser Google Chrome

Program Code:-
<html>

<head>

<link type="text/css" rel="stylesheet"


href="https://www.dropbox.com/s/trsldt0me90jzs8/resume.css"/>

<title></title>

</head>

<body>

<div id="header">

<p id="name">Aman Kumar</p>

<a href="mailto:amanbst32@gmail.com" target="_blank"><p


id="email">amanbst32@gmail.com</p></a>

</div>

<div class="left">

</div>

<div class="right">

<h3>CV Highlights</h3>

<p>

<ul>
<li>Currently going through Web Application Engineering and Structure & Interpretation of
Computer Programs</li>

<li>Learnt basic Python, JavaScript, HTML, CSS on w3schools.com.</li>

<li>An independent, dedicated, efficient person. These attributes are proved through the
series of courses I have taken or I am taking as of now independently through online platforms.</li>

<li>Good Communication Skills, Presentation Skills, attitude towards leadership,


authorisation and delegation, conflict resolution and negotiation and a very good team
worker.</li></ul>

</p>

<h3>Professional Experience</h3>

<h4 id="company-name">TCS</h4>

<p id="job-title"><strong>Support Engineer (Technical Support)</strong></p>

<p id="job-responsibilities">Job Responsbilities</p>

<p>

<ul>

<li>Answer customer queries over email / ticketing system</li>

<li>Interact with our engineering team to get software issues and bugs resolved</li>

<li>Occasionally interact with customers over Skype or telephone</li>

<li>Contribute ideas to the team on how customers can be delighted</li></ul>

</p>

<h3>Educational Qualifications</h3>

<table>

<tr id="heading">

<td>Qualification</td>

<td>Board</td>

<td>Percentage / Grades</td>

<td>Year</td>

</tr>

<tr>
<td>Class 10</td>

<td>ICSE</td>

<td>91%</td>

<td>2013</td>

</tr>

<tr>

<td>Class 12</td>

<td>ISC</td>

<td>93.2%</td>

<td>2015</td>

</tr>

<tr>

<td>Btech</td>

<td>AKTU</td>

<td>78.3</td>

<td>2020</td>

</tr>

</table>

<h3>Independent Courses</h3>

<p>

<ul>

<li>

<span id="course-name">HTML & CSS for Beginners – Web Fundamentals</span> –


w3schools.com</li>

<li>

<span id="course-name">Python – Fundamentals and Dynamic Programming </span> -


w3schools.com</li>
<li>

<span id="course-name">JavaScript – Programming Basics, JS Apps and Build Games


</span> - w3schools.com</li>

<li>

<span id="course-name">Introduction to Computer Science - Building a chat server</span>


- slideshare.com</li>

</ul>

<h3>Technical Skills</h3>

<p>

<ul>

<li>

<span id="course-name">Operating Systems:</span> DOS, Windows 98, Windows 2000,


Windows XP, Windows NT, Windows Server 2003, Windows Vista, Windows 7, Macintosh
Computers (OS X), Linux (Ubuntu, Fedora)</li>

<li>

<span id="course-name">Application Software:</span> Office 97-2003; Office XP, Office


2007, Office for Mac 2011, iWork ’09, Sage Accounting Software, Sage 50 (Accounting Software),
Excel 2003/2007 for Financial Modelling spreadsheets.</li>

<li>

<span id="course-name">Programming Skills:</span>HTML, JAVA,CSS, Python, JavaScript,


learning C and C++</li></ul>

</p>

<h3>Certifications / Awards:</h3>

<p>

<ul>

<li>Participated in coding contests – IT and CSE department,GL BAJAJ INSTITUTE OF


TECHNOLOGY AND MANAGEMENT</li>

<li> Attended several Seminars- Google Workshop,Big Data, Risk Assessment etc.</li>

</ul>

</p>
<h3>Personal Information:</h3>

<p>

<ul>

<li>

A young, determined hard and smart working person. I believe in task based roles and
complete ownership of work.

<li>

<span id="course-name">Languages Known:</span>English, Hindi</li>

<li>

<span id="course-name">Hobbies:</span>I love reading Programming and IT related books


/ magazines, playing Chess, listening music, surfing Internet, self-learning through e-courses.</li>
</ul>

</p>

<h3>Other Information</h3>

<p>

<ul>

<li>

<span id="course-name">Expected Salary:</span>As per company standards</li>

<li>

<span id="course-name">Area of Interest:</span>Software Development, Programming,


Start-ups, Coding, App Development, Technical Support, Support Engineer, Customer Happiness,
Client service, Data Analyst, Business Analysis</li>

<li>

<span id="course-name">Joining Date:</span>Immediate</li></ul>

</p>

<h3>Declaration</h3>

<p>

I hereby declare that the details furnished above are true and correct to the best of my
knowledge and belief.</p>

</div>
<div id="footer"></div>

</body>

</html>

OUTPUT:-
Program No:3

Objective: - Design HTML form for keeping student record and validate it
using Java script.

Software Required:-
S. No. Name of Software Specifications
1. Notepad --
2. Web Browser Mozilla Firefox

Program Code:-
<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>
<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>
</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>

Validate.js
function validate()
{
if( document.StudentRegistration.textnames.value == "" )
{
alert( "Please provide your Name!" );
document.StudentRegistration.textnames.focus() ;
return false;
}
if( document.StudentRegistration.fathername.value == "" )
{
alert( "Please provide your Father Name!" );
document.StudentRegistration.fathername.focus() ;
return false;
}
if( document.StudentRegistration.paddress.value == "" )
{
alert( "Please provide your Postal Address!" );
document.StudentRegistration.paddress.focus() ;
return false;
}
if( document.StudentRegistration.personaladdress.value == "" )
{
alert( "Please provide your Personal Address!" );
document.StudentRegistration.personaladdress.focus() ;
return false;
}
if ( ( StudentRegistration.sex[0].checked == false ) && ( StudentRegistration.sex[1].checked
== false ) )
{
alert ( "Please choose your Gender: Male or Female" );
return false;
}
if( document.StudentRegistration.City.value == "-1" )
{
alert( "Please provide your City!" );
document.StudentRegistration.City.focus() ; return false;
}
if( document.StudentRegistration.Course.value == "-1" )
{
alert( "Please provide your Course!" );
return false;
}
if( document.StudentRegistration.District.value == "-1" )
{
alert( "Please provide your Select District!" );
return false;
}
if( document.StudentRegistration.State.value == "-1" )
{
alert( "Please provide your Select State!" );
return false;
}
if( document.StudentRegistration.pincode.value == "" ||
isNaN( document.StudentRegistration.pincode.value) ||
document.StudentRegistration.pincode.value.length != 6 )
{
alert( "Please provide a pincode in the format ######." );
document.StudentRegistration.pincode.focus() ;
return false;
}
var email = document.StudentRegistration.emailid.value;
atpos = email.indexOf("@");
dotpos = email.lastIndexOf(".");
if (email == "" || atpos < 1 || ( dotpos - atpos < 2 ))
{
alert("Please enter correct email ID")
document.StudentRegistration.emailid.focus() ;
return false;
}
if( document.StudentRegistration.dob.value == "" )
{
alert( "Please provide your DOB!" );
document.StudentRegistration.dob.focus() ;
return false;
}
if( document.StudentRegistration.mobileno.value == "" ||
isNaN( document.StudentRegistration.mobileno.value) ||
document.StudentRegistration.mobileno.value.length != 10 )
{
alert( "Please provide a Mobile No in the format 123." );
document.StudentRegistration.mobileno.focus() ;
return false;
}
return( true );
}

OUTPUT:
Program No:4

Objective::- To 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.

Software Required:-
S. No. Name of Software Specifications
1. Notepad --
2. Web Browser Google Chrome
3. SDK kit 1.7
4. Tomcat Server 7.0
5. My Sql /MS Access 3.5

Program Code:-

Registration page (registration.jsp)

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>User Data</title>
</head>
<style>
div.ex {
text-align: right width:300px;
padding: 10px;
border: 5px solid grey;
margin: 0px
}
</style>
<body>
<h1>Registration Form</h1>
<div class="ex">
<form action="RegistrationController" method="post">
<table style="with: 50%">
<tr>
<td>Full Name</td>
<td><input type="text" name="fullname"
/></td>
</tr>
<tr>
<td>Username</td>
<td><input type="text" name="userName"
/></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="pass"
/></td>
</tr>
<tr>
<td>Address</td>
<td><input type="text" name="address" /></td>
</tr>
<tr>
<td>Age</td>
<td><input type="text" name="age" /></td>
</tr>
<tr>
<td>Qualification</td>
<td><input type="text" name="qual" /></td>
</tr>
<tr>
<td>Percentage</td>
<td><input type="text" name="percent" /></td>
</tr>
<tr>
<td>Year Passed</td>
<td><input type="text" name="yop" /></td>
</tr>
</table>
<input type="submit" value="register" />
</form>
<br>

create a student table in test database before registering this form


<br> Syntax : <br>
<i>create table student(name varchar(100), userName
varchar(100), pass varchar(100), addr varchar(100), age int, qual
varchar(100), percent varchar(100), year varchar(100));</i>

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

web.xml mapping

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


<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>registration</display-name>
<welcome-file-list>
<welcome-file>registration.jsp</welcome-file>
</welcome-file-list>
<servlet>
<description></description>
<display-name>RegistrationController</display-name>
<servlet-name>RegistrationController</servlet-name>
<servlet-class>com.candidjava.RegistrationController</servlet-
class>
</servlet>
<servlet-mapping>
<servlet-name>RegistrationController</servlet-name>
<url-pattern>/RegistrationController</url-pattern>
</servlet-mapping>
</web-app>

Servlet registration example with Mysql Database connectivity

1. package com.candidjava;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

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

/**
* Servlet implementation class UserDataServlet
*/
public class RegistrationController extends HttpServlet {

protected void doPost(HttpServletRequest request,


HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name = request.getParameter("fullname");
String userName = request.getParameter("userName");
String pass = request.getParameter("pass");
String addr = request.getParameter("address");
String age = request.getParameter("age");
String qual = request.getParameter("qual");
String percent = request.getParameter("percent");
String year = request.getParameter("yop");

// validate given input


if (name.isEmpty() || addr.isEmpty() || age.isEmpty() ||
qual.isEmpty() || percent.isEmpty() || year.isEmpty()) {
RequestDispatcher rd =
request.getRequestDispatcher("registration.jsp");
out.println("<font color=red>Please fill all the fields</font>");
rd.include(request, response);
} else {
// inserting data into mysql database
// create a test database and student table before running this to
create table
//create table student(name varchar(100), userName varchar(100),
pass varchar(100), addr varchar(100), age int, qual varchar(100),
percent varchar(100), year varchar(100));
try {
Class.forName("com.mysql.jdbc.Driver");
// loads mysql driver

Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/test",
"root", "root");

String query = "insert into student values(?,?,?,?,?,?,?,?)";

PreparedStatement ps = con.prepareStatement(query); // generates


sql query

ps.setString(1, name);
ps.setString(2, userName);
ps.setString(3, pass);
ps.setString(4, addr);
ps.setInt(5, Integer.parseInt(age));
ps.setString(6, qual);
ps.setString(7, percent);
ps.setString(8, year);

ps.executeUpdate(); // execute it on test database


System.out.println("successfuly inserted");
ps.close();
con.close();
} catch (ClassNotFoundException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
RequestDispatcher rd = request.getRequestDispatcher("home.jsp");
rd.forward(request, response);
}
}
}

Success page (home.jsp)

1. <%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-
1">
<title>Display</title>
<style>
table#nat{
width: 50%;
background-color: #c48ec5;
}
</style>
</head>
<body>
<%
String name = request.getParameter("fullname");
String userName = request.getParameter("userName");
String pass = request.getParameter("pass");
String addr = request.getParameter("address");
String age = request.getParameter("age");
String qual = request.getParameter("qual");
String percent = request.getParameter("percent");
String year = request.getParameter("yop");
%>
<table id ="nat">
<tr>
<td>Full Name</td>
<td><%= name %></td>
</tr>
<tr>
<td>User Name</td>
<td><%= userName %></td>
</tr>
<tr>
<td>Address</td>
<td><%= addr %></td>
</tr>
<tr>
<td>Age</td>
<td><%= age %></td>
</tr>
<tr>
<td>Qualification</td>
<td><%= qual %></td>
</tr>
<tr>
<td>Percentage</td>
<td><%= percent %></td>
</tr>
<tr>
<td>Year of Passout</td>
<td><%= year %></td>
</tr>
</table>
<br>
use " <i> select * from student; </i> " in mysql client to verify it.
</body>
</html>

OUTPUT:
Program No.5

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

Software Required:-
S. No. Name of Software Specifications
1. Notepad --
2. Web Browser Mozilla Firefox

Program Code:-
<html>
<head>
<title>Browser Information</title>
</head>
<body>
<h1>Browser Information</h1>
<hr>
<p>
The <b>navigator</b> object contains the following information
about the browser you are using.
</p>
<ul>
<script LANGUAGE="JavaScript" type="text/javascript">
document.To Write ("<li><b>Code Name:</b> " + navigator.appCodeName);
document.To Write ("<li><b>App Name:</b> " + navigator.appName);
document.To Write ("<li><b>App Version:</b> " + navigator.appVersion);
document.To Write ("<li><b>User Agent:</b> " + navigator.userAgent);
document.To Write ("<li><b>Language:</b> " + navigator.language);
document.To Write ("<li><b>Platform:</b> " + navigator.platform);
</script>
</ul>
<hr>
</body>
</html>

Output:-
Program No.6
Objective:- Write a Java applet to display the Application Program screen
i.e. flag and other.

Software Required:-
S. No. Name of Software Specifications
1. Notepad --
2. Web Browser Mozilla Firefox
3 SDK kit 1.7

Program Code:-
import java.awt.*;
import java.awt.event.*;
import java.applet.*;

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

public class Cal extends Applet


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

public void actionPerformed(ActionEvent ae)


{
String str=ae.getActionCommand();
char ch=str.charAt(0);
if ( Character.isDigit(ch))
t1.setText(t1.getText()+str);
else
if(str.equals("add"))
{
v1=Integer.parseInt(t1.getText());
OP='+';
t1.setText("");
}
else if(str.equals("sub"))
{
v1=Integer.parseInt(t1.getText());
OP='-';
t1.setText("");
}
else if(str.equals("mul"))
{
v1=Integer.parseInt(t1.getText());
OP='*';
t1.setText("");
}
else if(str.equals("div"))
{
v1=Integer.parseInt(t1.getText());
OP='/';
t1.setText("");
}
else if(str.equals("mod"))
{
v1=Integer.parseInt(t1.getText());
OP='%';
t1.setText("");
}
if(str.equals("EQ"))
{
v2=Integer.parseInt(t1.getText());
if(OP=='+')
result=v1+v2;
else if(OP=='-')
result=v1-v2;
else if(OP=='*')
result=v1*v2;
else if(OP=='/')
result=v1/v2;
else if(OP=='%')
result=v1%v2;
t1.setText(""+result);
}
if(str.equals("clear"))
{
t1.setText("");
}
}
}
Output:
Program No:7

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


set of rules. Create a style sheet in CSS/ XSL & display the document in
internet explorer.

Software Required:-
S. No. Name of Software Specifications
1. Notepad --
2. SDK kit 1.7
3 Web Browser Mozilla Firefox

Program Code:-
Action: An XML demonstration
Make a new XML file, doc9.xml. Copy and paste the content from here, making sure that you
scroll to get all of it:
<?xml version="1.0"?>
<!-- XML demonstration -->
<?xml-stylesheet type="text/css" href="style9.css"?>
<!DOCTYPE planet>
<planet>
<ocean>
<name>Arctic</name>
<area>13,000</area>
<depth>1,200</depth>
</ocean>
<ocean>
<name>Atlantic</name>
<area>87,000</area>
<depth>3,900</depth>
</ocean>
<ocean>
<name>Pacific</name>
<area>180,000</area>
<depth>4,000</depth>
</ocean>
<ocean>
<name>Indian</name>
<area>75,000</area>
<depth>3,900</depth>
</ocean>
<ocean>
<name>Southern</name>
<area>20,000</area>
<depth>4,500</depth>
</ocean>
</planet>
Make a new CSS file, style9.css. Copy and paste the content from here, making sure that you
scroll to get all of it:
/*** XML demonstration ***/

planet:before {
display: block;
width: 8em;
font-weight: bold;
font-size: 200%;
content: "Oceans";
margin: -.75em 0px .25em -.25em;
padding: .1em .25em;
background-color: #cdf;
}
planet {
display: block;
margin: 2em 1em;
border: 4px solid #cdf;
padding: 0px 1em;
background-color: white;
}

ocean {
display: block;
margin-bottom: 1em;
}
name {
display: block;
font-weight: bold;
font-size: 150%;
}
area {
display: block;
}
area:before {
content: "Area: ";
}
area:after {
content: " million km\B2";
}
depth {
display: block;
}
depth:before {
content: "Mean depth: ";
}
depth:after {
content: " m";
}
OUTPUT:

Open the document in your browser:

Notes about this demonstration:

o The superscript 2 (in "million km²") a Unicode character, coded as \B2 in the
CSS file.
o The heading, "Oceans", has a negative top margin, moving it up so it is
displayed on top of the border.
Program No:8

Objective: Install TOMCAT web server and APACHE. Access the


developed static web pages for web site, using these servers by putting the
web pages developed .

Software Required:-
S. No. Name of Software Specifications
1. Notepad --
2. Tomcat Sever
3 SDK kit 1.7

DESCRIPTION:
While installation assign port number 8080 to APACHE. Make sure that these ports are
available i.e., no other process is using this port.

Set the JAVA_HOME Variable


You must set the JAVA_HOME environment variable to tell Tomcat where to find Java.
Failing to properly set this variable prevents Tomcat from handling JSP pages. This variable
should list the base JDK installation directory, not the bin subdirectory.
On Windows XP, you could also go to the Start menu, select Control Panel, choose System,
click on the Advanced tab, press the Environment Variables button at the bottom, and enter
the JAVA_HOME variable and value directly as:
Name: JAVA_HOME
Value: C:\jdk

Set the CLASSPATH


Since servlets and JSP are not part of the Java 2 platform, standard edition, you have to identify
the servlet classes to the compiler. The server already knows about the servlet classes, but
the compiler (i.e., javac) you use for development probably doesn't. So, if you don't set
your CLASSPATH, attempts to compile servlets, tag libraries, or other classes that use the
servlet and JSP APIs will fail with error messages about unknown classes.
Name: JAVA_HOME
Value: install_dir/common/lib/servlet-api.jar

Turn on Servlet Reloading


The next step is to tell Tomcat to check the modification dates of the class files of requested
servlets and reload ones that have changed since they were loaded into the server's memory.
This slightly degrades performance in deployment situations, so is turned off by default.
However, if you fail to turn it on for your development server, you'll have to restart the server
every time you recompile a servlet that has already been loaded into the server's memory.
To turn on servlet reloading, edit install_dir/conf/server.xml and add
a DefaultContextsubelement to the main Host element and supply true for
the reloadable attribute. For example, in Tomcat 5.0.27, search for this entry:
<Host name="localhost" debug="0" appBase="webapps" ...>
and then insert the following immediately below it:
<DefaultContext reloadable="true"/>
Be sure to make a backup copy of server.xml before making the above change.

Enable the Invoker Servlet


The invoker servlet lets you run servlets without first making changes to your Web application's
deployment descriptor. Instead, you just drop your servlet into WEB-INF/classesand use the
URL http://host/servlet/ServletName. The invoker servlet is extremely convenient when you
are learning and even when you are doing your initial development.To enable the invoker
servlet, uncomment the following servlet and servlet-mappingelements
in install_dir/conf/web.xml. Finally, remember to make a backup copy of the original version
of this file before you make the changes.
<servlet>
<servlet-name>invoker</servlet-name>
<servlet-class>
org.apache.catalina.servlets.InvokerServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>invoker</servlet-name>
<url-pattern>/servlet/*</url-pattern>
</servlet-mapping>

OUTPUT:
Program No. 09
OBJECTIVE:
Assume four users user1, user2, user3 and user4 having the passwords pwd1, pwd2, pwd3 and pwd4
respectively. Write a servlet for doing the following. 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.

DESCRIPTION:
Servlet Life cycle:
1. Servlet class loading
2. Servlet Instantiation
3. call the init method
4. call the service method
5. call destroy method
Class loading and instantiation
If you consider a servlet to be just like any other Java program, except that it runs within a
servlet container, there has to be a process of loading the class and making it ready for requests. Servlets
do not have the exact equivalent of a main method that causes them to start execution.
When a web container starts it searches for the deployment descriptor (WEB.XML) for each of
its web applications. When it finds a servlet in the descriptor it will create an instance of the servlet
class. At this point the class is considered to be loaded (but not initialized).
The init method
The HttpServlet class inherits the init method from GenericServlet. The init method performs
a role slightly similar to a constructor in an “ordinary” Java program in that it allows initialization of an
instance at start up. It is called automatically by the servlet container and as it causes the application
context (WEB.XML) to be parsed and any initialization will be performed. It comes in two versions,
one with a zero parameter constructor and one that takes a ServletConfig parameter.
The servlet engine creates a request object and a response object. The servlet engine invokes the servlet
service() method, passing the request and response objects. Once the init method returns the servlet is
said to be placed into service. The process of using init to initialize servlets means that it is possible to
change configuration details by modifying the deployment descriptor without having them hard coded
in with your Java source and needing a re-compilation.
void init(ServletConfig sc)
Calling the service method
The service() method gets information about the request from the request object, processes the
request, and uses methods of the response object to create the client response. The service method can
invoke other methods to process the request, such as doGet(), doPost(), or methods you write. The
service method is called for each request processed and is not normally overridden by the programmer.
The code that makes a servlet “go” is the. servlet
void service(ServletRequest req,ServletResponse res)
The destroy Method
Two typical reasons for the destroy method being called are if the container is shutting down
or if the container is low on resources. This can happen when the container keeps a pool of instances of
servlets to ensure adequate performance. If no requests have come in for a particular servlet for a while
it may destroy it to ensure resources are available for the servlets that are being requested. The destroy
method is called only once, before a servlet is unloaded and thus you cannot be certain when and if it
is called.
void destroy()

ServletConfig Class
ServletConfig object is used by the Servlet Container to pass information to the Servlet during
it's initialization. Servlet can obtain information regarding initialization parameters and their values
using different methods of ServletConfig class initialization parameters are name/value pairs used to
provide basic information to the Servlet during it's initialization like JDBC driver name, path to
database, username, password etc.

Methods of ServletConfig class


Following are the four methods of this class :

● getInitParameter(String paramName) Returns value of the given parameter. If value of


parameter could not be found in web.xml file then a null value is returned.
● getInitParameterNames() Returns an Enumeration object containing all the names of
initialization parameters provided for this Servlet.
● getServletContext() Returns reference to the ServletContext object for this Servlet. It is similar
to getServletContext() method provided by HttpServlet class.
● getServletName() Returns name of the Servlet as provided in the web.xml file or if none is
provided then returns complete class path to the Servlet.

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>
<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>
cologin1.html
<html>
<head>
<title> login Page </title>
<p style= "background:yellow; top:100px; left:250px; position:absolute; ">
</head>
<body>
<form ACTION="clogin1">
<label> Login </label>
<input type="text" name="usr" size="20"> <br> <br>
<label> Password </label>
<input type="password" name="pwd" size="20"> <br> <br>
<input type="submit" value="submit">
</form>
</body>
</html>

Addcook.java:
import javax.servlet.* ;
import javax.servlet.http.*;
import java.io.*;
public class Addcook extends HttpServlet
{
String user,pas;
public void service(HttpServletRequest req,HttpServletResponse res) throws
ServletException,IOException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
Cookie c1=new Cookie("usr1","suni");
Cookie p1=new Cookie("pwd1","ani");
Cookie c2=new Cookie("usr2","abc");
Cookie p2=new Cookie("pwd2","123");
Cookie c3=new Cookie("usr3","def");
Cookie p3=new Cookie("pwd3","456");
Cookie c4=new Cookie("usr4","mno");
Cookie p4=new Cookie("pwd4","789");
res.addCookie(c1);
res.addCookie(p1);
res.addCookie(c2);
res.addCookie(p2);
res.addCookie(c3);
res.addCookie(p3);
res.addCookie(c4);
res.addCookie(p4);
out.println("COOKIE ADDED");
}
}
Clogin.java:
import javax.servlet.* ;
import javax.servlet.http.*;
import java.io.*;
public class Clogin extends HttpServlet
{
String user,pas;
public void service(HttpServletRequest req,HttpServletResponse res) throws
ServletException,IOException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
user=req.getParameter("usr");
pas=req.getParameter("pwd");
Cookie[] c=req.getCookies();
for(int i=0;i<c.length;i++)
{
if((c[i].getName().equals("usr1")&&c[i+1].getName().equals("pwd1"))|| c[i].getName().equals("usr2")
&&c[i+1].getName().equals("pwd2"))||(c[i].getName().equals("usr3")&&
c[i+1].getName().equals("pwd3"))||(c[i].getName().equals("usr4")&& c[i+1].getName().equals("pwd4") ))
{
if((user.equals(c[i].getValue()) && pas.equals(c[i+1].getValue())) )
{
//RequestDispatcher rd=req.getRequestDispatcher("/cart.html");
rd.forward(req,res);
}
else
{
out.println("YOU ARE NOT AUTHORISED USER ");
//res.sendRedirect("/cookdemo/cologin.html");
}
}
}
}
}

Web.xml:
<web-app>
<servlet>
<servlet-name>him</servlet-name>
<servlet-class>Clogin</servlet-class>
</servlet>
<servlet>
<servlet-name>him1</servlet-name>
<servlet-class>Addcook</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>him</servlet-name>
<url-pattern>/clogin</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>him1</servlet-name>
<url-pattern>/clogin1</url-pattern>
</servlet-mapping>
</web-app>

OUTPUT:
Program No. 10
OBJECTIVE:

Install a database (Mysql or Oracle). Create a table which should contain at least the following fields:
name, password, email-id, phone number Write a java program/servlet/JSP to connect to that database
and extract data from the tables and display them. Insert the details of the users who register with the
web site, whenever a new user clicks the submit button in the registration page.

DESCRIPTION:

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> <td align=center colspan="2"><input type="submit" value="submit"></td> </tr>

</table> </center>

</form>

</body>

</html>

Ini.java:

import javax.servlet.*;

import java.sql.*;

import java.io.*;

public class Ini extends GenericServlet

private String user1,pwd1,email1;

public void service(ServletRequest req,ServletResponse res) throws ServletException,IOException

user1=req.getParameter("user");

pwd1=req.getParameter("pwd");

email1=req.getParameter("email");

res.setContentType("text/html");

PrintWriter out=res.getWriter();

try

{
Class.forName("oracle.jdbc.driver.OracleDriver");

Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@195.100.101.158:1521:cclab","scott","tiger");

PreparedStatement st=con.prepareStatement("insert into personal values(?,?,?,?,?,?)");

st.setString(1,user1);

st.setString(2,pwd1);

st.setString(3,"25");

st.setString(4,"hyd");

st.setString(5,email1);

st.setString(6,"21234");

st.executeUpdate();

con.close();

catch(SQLException s)

{ out.println("not found "+s);

catch(ClassNotFoundException c)

out.println("not found "+c);

}}

web.xml:

<web-app>

<servlet>

<servlet-name>init1</servlet-name>

<servlet-class>Ini</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>init1</servlet-name>
<url-pattern>/regis</url-pattern>

</servlet-mapping>

</web-app>

OUTPUT:
Program No. 11
OBJECTIVE:

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

PROGRAM:

CREATE TABLE `members` (

`id` int(10) unsigned NOT NULL auto_increment,

`first_name` varchar(45) NOT NULL,

`last_name` varchar(45) NOT NULL,

`email` varchar(45) NOT NULL,

`uname` varchar(45) NOT NULL,

`pass` varchar(45) NOT NULL,

`regdate` date NOT NULL,

PRIMARY KEY (`id`)

) ENGINE=InnoDB DEFAULT CHARSET=latin1;

index.jsp
1
<%@page contentType="text/html" pageEncoding="UTF-8"%>
2
<!DOCTYPE html>
3
<html>
4
<head>
5
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
6
<title>JSP Example</title>
7
</head>
8
<body>
9
<form method="post" action="login.jsp">
1
<center>
0
1 <table border="1" width="30%" cellpadding="3">
1
<thead>
1
2 <tr>

1 <th colspan="2">Login Here</th>


3 </tr>
1 </thead>
4
<tbody>
1
5 <tr>

1 <td>User Name</td>
6
<td><input type="text" name="uname" value="" /></td>
1
</tr>
7
<tr>
1
8 <td>Password</td>
1 <td><input type="password" name="pass" value="" /></td>
9
</tr>
2
0 <tr>

2 <td><input type="submit" value="Login" /></td>


1
<td><input type="reset" value="Reset" /></td>
2
</tr>
2
<tr>
2
3 <td colspan="2">Yet Not Registered!! <a href="reg.jsp">Register
Here</a></td>
2
4 </tr>

2 </tbody>
5
</table>
2
6 </center>

2 </form>
7
2 </body>
8
</html>
2
9

3
0

3
1

3
2

3
3

3
4

3
5

3
6

3
7

3
8

reg.jsp
1 <%@page contentType="text/html" pageEncoding="UTF-8"%>

2 <!DOCTYPE html>

3 <html>

4 <head>

5 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

6 <title>Registration</title>

7 </head>

8 <body>
9 <form method="post" action="registration.jsp">

1 <center>
0
<table border="1" width="30%" cellpadding="5">
1
1 <thead>

1 <tr>
2 <th colspan="2">Enter Information Here</th>
1 </tr>
3
</thead>
1
4 <tbody>

1 <tr>
5
<td>First Name</td>
1
<td><input type="text" name="fname" value="" /></td>
6
</tr>
1
7 <tr>
1 <td>Last Name</td>
8
<td><input type="text" name="lname" value="" /></td>
1
9 </tr>

2 <tr>
0
<td>Email</td>
2
<td><input type="text" name="email" value="" /></td>
1
</tr>
2
2 <tr>

2 <td>User Name</td>
3
<td><input type="text" name="uname" value="" /></td>
2
4 </tr>

2 <tr>
5
<td>Password</td>
2 <td><input type="password" name="pass" value="" /></td>
6
</tr>
2
7 <tr>

2 <td><input type="submit" value="Submit" /></td>


8 <td><input type="reset" value="Reset" /></td>
2 </tr>
9
<tr>
3
0 <td colspan="2">Already registered!! <a href="index.jsp">Login
Here</a></td>
3
1 </tr>

3 </tbody>
2
</table>
3
</center>
3
</form>
3
4 </body>
3 </html>
5

3
6

3
7

3
8

3
9

4
0

4
1

4
2
4
3

4
4

4
5

4
6

4
7

4
8

4
9

5
0

registration.jsp
1 <%@ page import ="java.sql.*" %>

2 <%

3 String user = request.getParameter("uname");

4 String pwd = request.getParameter("pass");

5 String fname = request.getParameter("fname");

6 String lname = request.getParameter("lname");

7 String email = request.getParameter("email");

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

9 Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbname",

1 "root", "dbpass");
0
Statement st = con.createStatement();
1
1 //ResultSet rs;
1 int i = st.executeUpdate("insert into members(first_name, last_name, email, uname, pass,
2 regdate) values ('" + fname + "','" + lname + "','" + email + "','" + user + "','" + pwd + "',
CURDATE())");
1
3 if (i > 0) {

1 //session.setAttribute("userid", user);
4
response.sendRedirect("welcome.jsp");
1
5 // out.print("Registration Successfull!"+"<a href='index.jsp'>Go to Login</a>");

1 } else {
6 response.sendRedirect("index.jsp");
1 }
7
%>
1
8

1
9

2
0

2
1

welcome.jsp
Registration is Successful.
1
Please Login Here <a href='index.jsp'>Go to
2
Login</a>

login.jsp
1 <%@ page import ="java.sql.*" %>

2 <%

3 String userid = request.getParameter("uname");

4 String pwd = request.getParameter("pass");

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

6 Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbname",


7 "root", "dbpass");

8 Statement st = con.createStatement();

9 ResultSet rs;

1 rs = st.executeQuery("select * from members where uname='" + userid + "' and pass='" + pwd +
0 "'");

1 if (rs.next()) {
1
session.setAttribute("userid", userid);
1
2 //out.println("welcome " + userid);

1 //out.println("<a href='logout.jsp'>Log out</a>");


3 response.sendRedirect("success.jsp");
1 } else {
4
out.println("Invalid password <a href='index.jsp'>try again</a>");
1
5 }

1 %>
6

1
7

1
8

1
9

success.jsp
1 <%

2 if ((session.getAttribute("userid") == null) || (session.getAttribute("userid") == ""))


3 {

4 %>

5 You are not logged in<br/>

6 <a href="index.jsp">Please Login</a>

7 <%} else {
8 %>

9 Welcome <%=session.getAttribute("userid")%>

1 <a href='logout.jsp'>Log out</a>


0
<%
1
}
1

1 %>
2

logout.jsp

<%
1
session.setAttribute("userid", null);
2
session.invalidate();
3
response.sendRedirect("index.jsp")
4
;
5
%>

OUTPUT:
PROGRAM No. 12
OBJECTIVE:
Design and implement a simple shopping cart example with session tracking API.

Note: You can see the JESSIONID (Session ID) in the output screens at the end.

Note: For better understanding, the subject is discussed in Question/Answer format.

Note: Before going into this example, it is advised to go through the Cookie API methods and their
explanation because these methods are used in this example.

DESCRIPTION:

1. What is Cookie?

For us, Cookie is a class from javax.servlet.http package. But in the open world, a Cookie represents
a sweet Biscuit or Chocolate.

2. What a Cookie can store?

Cookie stores small strings of data. Cookies stay all through the session. Programmer can store the
session data with Cookie object. It is another style of tracking session data (the first way is using
HttpSession interface).

3. Who creates Cookies and where they are stored?

Servlet Cookies are created on the server (by Servlet container) and sent to the client’s browser for
temporary storage. The Servlet Cookies can be sent to and fro between client and server in their
conversation. Client is not aware of the entire process of Cookie management as everything is done
by the server and client is kept completely transparent.

4. What Cookie can do in Servlets?

Servlet Cookies are used mainly for tracking different types of client’s information. That is, the Web
server can store data on the client browser in the form of Cookie objects.

Typical uses of a Cookie are

1. To store User name and Password

2. To write Shopping cart in e-Commerce application

3. Advertisement on client browser


4. Customization of Web sites etc.

5. How Servlet Cookies stored on the client are recognized by the server later?

The Cookie object created on the server is attached to response object and sent to client. The Cookie
carries implicitly (as response header) the server information like name, path, host and connection
type etc. and the combination of this information is used by server to know cookie is coming from
which client.

6. All Cookies are same or any types exist?

Yes, there are two types of cookies and they are differentiated on their life span.

1. Session Cookies: Session cookies get expired and deleted from browser when the browser
closes, thereby, they do not carry any expiration time constraint parameter. They are stored
temporarily (just for the usage of session) in the RAM memory.

2. Persistent Cookies: As the name indicates, they persist long time on the client browser. The
time of expiration can be set programmatically for each Cookie. These Cookies are stored on
hard disk. The Cookie gets deleted automatically when the time or age expires.

With this knowledge of Cookies, let us go for an example. In this code, we create a cookie in the
Servlet, sent to client to store on the browser, later retrieved from client and information available
with the cookie is printed.

The entire program moves around a Shopping cart, an important module of e-Commerce application.
While going to a Shopping Mall, nearby to our house, physically we take a wheel cart to place the
items we would like to buy. But as our program represents an online Mall, here shopping cart is
imaginary but have all the operations you do on a physical cart like adding items, deleting, replacing,
searching etc. For simplicity, only I took two operations only of Adding items and Searching (or Listing)
items and these operations are performed through Servlet Cookies.

Example on Servlet Cookies

As usual there exist two programs of Client HTML and server Servlet.

HTML File: ShoppingCart.html

<h3>Cookie Example through Shopping Cart</h3>


<body>
<form method="get" action="http://localhost:8888/india/SC">

1 <h3>Cookie Example through Shopping Cart</h3>

2 <body>

3 <form method="get" action="http://localhost:8888/india/SC">


4

5 Enter Item Name <input type="text" name="item"><br>

6 Enter Item Quantity <input type="text" name="qty"><br>

7 <input type="submit" value="Add Cookie" name="add">

8 <input type="submit" value="List Cookies" name="list">

9 </form>

10 </body>

11

Observe, fist time we are having two submit buttons in a single <form> tag. Click any submit button,
the same servlet is called. Then how to differentiate the submit button clicked by the user and
accordingly action taken by the Programmer on Servlet? Observe, the names of two submit buttons
are add and list. We see this in Servlet program.

web.xml entry for ShoppingCart servlet

<servlet>
<servlet-name>snrao1</servlet-name>
<servlet-class>ShoppingCart</servlet-class>
</servlet>

1 <servlet>

2 <servlet-name>snrao1</servlet-name>

3 <servlet-class>ShoppingCart</servlet-class>

4 </servlet>

6 <servlet-mapping>

7 <servlet-name>snrao1</servlet-name>

8 <url-pattern>/SC</url-pattern>

9 </servlet-mapping>

Servlet File: ShoppingCart.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ShoppingCart extends HttpServlet
1 import java.io.*;

2 import javax.servlet.*;

3 import javax.servlet.http.*;

4 public class ShoppingCart extends HttpServlet

5 {

6 public void service(HttpServletRequest req,HttpServletResponse res) throws ServletException,


IOException
7
{
8
String str1 = req.getParameter("item"); // item name
9
String str2 = req.getParameter("qty"); // item quantity
10
String str3 = req.getParameter("add"); // submit button by name add
11
String str4 = req.getParameter("list"); // submit button by name list
12

13
res.setContentType("text/html");
14
PrintWriter out = res.getWriter();
15
if(str3 != null)
16
{
17
Cookie c1 = new Cookie(str1, str2);
18
res.addCookie(c1);
19
res.sendRedirect("ShoppingCart.html");
20
}
21
else if(str4 != null)
22
{
23
Cookie clientCookies[] = req.getCookies();
24
for( int i = 0; i < clientCookies.length; i++)
25
{
26
out.print("<B>" + clientCookies[i].getName() + " : " + clientCookies[i].getValue() +
27 "</B><BR>");
28 }

29 }

30 out.close( ) ;

31 }

32 }

Let us discuss the code linewise.

String str1 = req.getParameter("item"); // item name


String str2 = req.getParameter("qty"); // item quantity
String str3 = req.getParameter("add"); // submit button by name "add"
String str4 = req.getParameter("list"); // submit button by name "list"

1 String str1 = req.getParameter("item"); // item name

2 String str2 = req.getParameter("qty"); // item quantity

3 String str3 = req.getParameter("add"); // submit button by name "add"

4 String str4 = req.getParameter("list"); // submit button by name "list"

With the first two statements you are well aware of. Observe the last two statements are for submit
buttons. When user clicks add submit button, the str3 contains value Add Cookie and str4 contains
null. Similarly, when user clicks list submit button, the str4 contains the value List Cookies and str3
contains null. With null values of strings str3 and str4, the Programmer can differentiate from which
submit button the Servlet is invoked.

if(str3 != null)
{
Cookie c1 = new Cookie(str1, str2); // create a Cookie object
res.addCookie(c1); // send cookie object to client

1 if(str3 != null)

2{

3 Cookie c1 = new Cookie(str1, str2); // create a Cookie object

4 res.addCookie(c1); // send cookie object to client

5 res.sendRedirect("ShoppingCart.html"); // send a fresh form to client

6}

When str3 is not equal to null? It is obviously when user clicks add submit button. That is, above if
condition is executed when user clicked add submit button. A Cookie object c1 is created and its
constructor is passed with two string parameters str1 (item name) and str2 (item quantity). We know
earlier, the Cookie stores small strings of data. Later the Cookie object c1 is sent to client by calling
the method addCookie() of HttpServletResponse interface. To make the code user friendly, a fresh
static HTML form is sent to client with sendRedirect() method for filling next item and quantity.

Note: As server is sending the HTML form, copy the ShoppingCar.html to the base folder india.

else if(str4 != null)


{
Cookie clientCookies[] = req.getCookies(); // retrieve cookies from client
for( int i = 0; i < clientCookies.length; i++)

else if(str4 != null)


1
{
2
Cookie clientCookies[] = req.getCookies(); // retrieve cookies from client
3
for( int i = 0; i < clientCookies.length; i++)
4
{ // print item name and item quantity of each cookie
5
out.print("<B>" + clientCookies[i].getName() + " : " + clientCookies[i].getValue() +
6
"</B><BR>");
7
}
8
}

The above else if condition is executed when the user clicked list submit button. The code should
display all the items and their quantity selected by the user earlier. All the cookies sent to client earlier
are called back by the server by calling getCookies() method of request object. This method returns
an array of Cookie objects. All the cookies are iterated in a for loop. getName() and getValue() of
Cookie class returns the first parameter (item name) and second parameter (item quantity) passed
earlier to Cookie constructor.

OUTPUT:

Empty ShoppingCart:
When user types some item name and item quantity.

Output screen when List Cookies submit button is clicked (after adding few items).

Observe the string Session ID (known as JSESSIONID) length. It is more than 30 characters.

S-ar putea să vă placă și