Documente Academic
Documente Profesional
Documente Cultură
Software Required:-
S. No. Name of Software Specifications
1. Notepad --
2. Web Browser Google Chrome
Program Code:-
<html>
<head>
<title></title>
</head>
<body>
<div id="header">
</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>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>
</p>
<h3>Professional Experience</h3>
<h4 id="company-name">TCS</h4>
<p>
<ul>
<li>Interact with our engineering team to get software issues and bugs resolved</li>
</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>
<li>
<li>
</ul>
<h3>Technical Skills</h3>
<p>
<ul>
<li>
<li>
<li>
</p>
<h3>Certifications / Awards:</h3>
<p>
<ul>
<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>
<li>
</p>
<h3>Other Information</h3>
<p>
<ul>
<li>
<li>
<li>
</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
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:-
</div>
</body>
</html>
web.xml mapping
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 {
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/test",
"root", "root");
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);
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>
*/
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:
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
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.
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.
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:
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.
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.
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.
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">
<CENTER>
<table>
<center>
<tr><td>Age</td>
<tr> <td>Address</td>
<tr> <td>email</td>
<tr> <td>Phone</td>
</center>
</table>
</form>
</body>
Login.html
<html>
<head>
<title>Registration page</title>
</head>
<body bgcolor=pink> <center> <table>
</table> </center>
</form>
</body>
</html>
Ini.java:
import javax.servlet.*;
import java.sql.*;
import java.io.*;
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");
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)
catch(ClassNotFoundException 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:
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 <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 </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>
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>
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 <%
8 Class.forName("com.mysql.jdbc.Driver");
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 <%
5 Class.forName("com.mysql.jdbc.Driver");
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 %>
6
1
7
1
8
1
9
success.jsp
1 <%
4 %>
7 <%} else {
8 %>
9 Welcome <%=session.getAttribute("userid")%>
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: 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.
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).
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.
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.
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.
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.
As usual there exist two programs of Client HTML and server Servlet.
2 <body>
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.
<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>
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.*;
5 {
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 }
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{
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.
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.