[go: up one dir, main page]

0% found this document useful (0 votes)
13 views23 pages

Webtechnologies - CIE-356 T - Unit 2 Notes

The document provides an overview of JavaScript, highlighting its role as a programming language for the web that can manipulate HTML and CSS. It covers key concepts such as client-side vs. server-side scripting, JavaScript variables and objects, and the HTML DOM, explaining how JavaScript interacts with HTML elements. Additionally, it discusses form validation techniques and the importance of data validation in web development.

Uploaded by

Vidyansh Sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views23 pages

Webtechnologies - CIE-356 T - Unit 2 Notes

The document provides an overview of JavaScript, highlighting its role as a programming language for the web that can manipulate HTML and CSS. It covers key concepts such as client-side vs. server-side scripting, JavaScript variables and objects, and the HTML DOM, explaining how JavaScript interacts with HTML elements. Additionally, it discusses form validation techniques and the importance of data validation in web development.

Uploaded by

Vidyansh Sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

JIMS Engineering Management Technical Campus

Unit 2 Notes
WebTechnologies(CIE-356T)

What is JavaScript?

JavaScript is the programming language of the web.

It can update and change both HTML and CSS.

It can calculate, manipulate and validate data.

Why Study JavaScript?

JavaScript is one of the 3 languages all web developers must learn:

1. HTML to define the content of web pages

2. CSS to specify the layout of web pages

3. JavaScript to program the behavior of web pages

JavaScript Can Change HTML Content

One of many JavaScript HTML methods is getElementById().

The example below "finds" an HTML element (with id="demo"), and changes the
element content (innerHTML) to "Hello JavaScript":

Example

<!DOCTYPE html>

<html>

<body>

<h2>What Can JavaScript Do?</h2>

<p id="demo">JavaScript can change HTML content.</p>

<button type="button" onclick='document.getElementById("demo").innerHTML = "Hello


JavaScript!"'>Click Me!</button>

</body>

Dr. Shilpi Singh,Associate Professor,JIMS,Greater Noida


JIMS Engineering Management Technical Campus
Unit 2 Notes
WebTechnologies(CIE-356T)

</html>JavaScript accepts both double and single quotes:

Example

document.getElementById('demo').innerHTML = 'Hello JavaScript';

JavaScript Can Change HTML Attribute Values

In this example JavaScript changes the value of the src (source) attribute of
an <img> tag:

<!DOCTYPE html>

<html>

<body>

<h2>What Can JavaScript Do?</h2>

<p>JavaScript can change HTML attribute values.</p>

<p>In this case JavaScript changes the value of the src (source) attribute of an
image.</p>

<button onclick="document.getElementById('myImage').src='pic_bulbon.gif'">Turn
on the light</button>

<img id="myImage" src="pic_bulboff.gif" style="width:100px">

<button onclick="document.getElementById('myImage').src='pic_bulboff.gif'">Turn
off the light</button>

</body>

</html>

The Light Bulb

Turn on the light Turn off the light

Dr. Shilpi Singh,Associate Professor,JIMS,Greater Noida


JIMS Engineering Management Technical Campus
Unit 2 Notes
WebTechnologies(CIE-356T)

Difference between client-side scripting and server-side scripting :

Client-side scripting Server-side scripting

Source code is not visible to the user


because its output
Source code is visible to the user.
of server-sideside is an HTML page.

Its primary function is to manipulate and


Its main function is to provide the
provide access to the respective database
requested output to the end user.
as per the request.

In this any server-side technology can be


It usually depends on the browser and its used and it does not
version. depend on the client.

It runs on the user’s computer. It runs on the webserver.

There are many advantages linked with The primary advantage is its ability to
this like faster. highly customize, response
response times, a more interactive requirements, access rights based on
application. user.

It does not provide security for data. It provides more security for data.

It is a technique used in web It is a technique that uses scripts on the


development in which scripts run on the webserver to produce a response that is
client’s browser. customized for each client’s request.

HTML, CSS, and javascript are used. PHP, Python, Java, Ruby are used.

No need of interaction with the server. It is all about interacting with the servers.

It reduces load on processing unit of the


It surge the processing load on the server.
server.

JavaScript Variables

JavaScript variables are containers for data values.

This code assigns a simple value (Fiat) to a variable named car:

Dr. Shilpi Singh,Associate Professor,JIMS,Greater Noida


JIMS Engineering Management Technical Campus
Unit 2 Notes
WebTechnologies(CIE-356T)

Example

let car = "Fiat";

JavaScript Objects

A javaScript object is an entity having state and behavior (properties and method). For
example: car, pen, bike, chair, glass, keyboard, monitor etc.

JavaScript is an object-based language. Everything is an object in JavaScript.

JavaScript is template based not class based. Here, we don't create class to get the
object. But, we direct create objects.

Creating Objects in JavaScript

There are 3 ways to create objects.

1. By object literal
2. By creating instance of Object directly (using new keyword)
3. By using an object constructor (using new keyword)

1) JavaScript Object by object literal

The syntax of creating object using object literal is given below:

. object={property1:value1,property2:value2.....propertyN:valueN}
As you can see, property and value is separated by : (colon).

Let’s see the simple example of creating object in JavaScript.

. <script>
. emp={id:102,name:"Shyam Kumar",salary:40000}
. document.write(emp.id+" "+emp.name+" "+emp.salary);
. </script>

Output of the above example

102 Shyam Kumar 40000

Dr. Shilpi Singh,Associate Professor,JIMS,Greater Noida


JIMS Engineering Management Technical Campus
Unit 2 Notes
WebTechnologies(CIE-356T)

2) By creating instance of Object

The syntax of creating object directly is given below:

. var objectname=new Object();


Here, new keyword is used to create object.

Let’s see the example of creating object directly.

. <script>
. var emp=new Object();
. emp.id=101;
. emp.name="Ravi Malik";
. emp.salary=50000;
. document.write(emp.id+" "+emp.name+" "+emp.salary);
. </script>

Output of the above example

101 Ravi 50000

3) By using an Object constructor

Here, you need to create function with arguments. Each argument value can be
assigned in the current object by using this keyword.

The this keyword refers to the current object.

The example of creating object by object constructor is given below.

. <script>
. function emp(id,name,salary){
. this.id=id;
. this.name=name;
. this.salary=salary;
. }
. e=new emp(103,"Vimal Jaiswal",30000);
.
. document.write(e.id+" "+e.name+" "+e.salary);
. </script>

Output of the above example

103 Vimal Jaiswal 30000

Dr. Shilpi Singh,Associate Professor,JIMS,Greater Noida


JIMS Engineering Management Technical Campus
Unit 2 Notes
WebTechnologies(CIE-356T)

Defining method in JavaScript Object

We can define method in JavaScript object. But before defining method, we need to
add property in the function with same name as method.

The example of defining method in object is given below.

. <script>
. function emp(id,name,salary){
. this.id=id;
. this.name=name;
. this.salary=salary;
.
. this.changeSalary=changeSalary;
. function changeSalary(otherSalary){
. this.salary=otherSalary;
. }
. }
. e=new emp(103,"Sonoo Jaiswal",30000);
. document.write(e.id+" "+e.name+" "+e.salary);
. e.changeSalary(45000);
. document.write("<br>"+e.id+" "+e.name+" "+e.salary);
. </script>

Output of the above example

103 Sonoo Jaiswal 30000


103 Sonoo Jaiswal 45000

JavaScript HTML DOM

With the HTML DOM, JavaScript can access and change all the elements of an
HTML document.

The HTML DOM (Document Object Model)

When a web page is loaded, the browser creates a Document Object Model of the
page.

The HTML DOM model is constructed as a tree of Objects:

The HTML DOM Tree of Objects

Dr. Shilpi Singh,Associate Professor,JIMS,Greater Noida


JIMS Engineering Management Technical Campus
Unit 2 Notes
WebTechnologies(CIE-356T)

With the object model, JavaScript gets all the power it needs to create dynamic
HTML:

• JavaScript can change all the HTML elements in the page


• JavaScript can change all the HTML attributes in the page
• JavaScript can change all the CSS styles in the page
• JavaScript can remove existing HTML elements and attributes
• JavaScript can add new HTML elements and attributes
• JavaScript can react to all existing HTML events in the page
• JavaScript can create new HTML events in the page

What is the DOM?

The DOM is a W3C (World Wide Web Consortium) standard.

The DOM defines a standard for accessing documents:

"The W3C Document Object Model (DOM) is a platform and language-neutral


interface that allows programs and scripts to dynamically access and update the
content, structure, and style of a document."

The DOM is separated into 3 different parts:

• Core DOM - standard model for all document types


• XML DOM - standard model for XML documents
• HTML DOM - standard model for HTML documents

What is the HTML DOM?

Dr. Shilpi Singh,Associate Professor,JIMS,Greater Noida


JIMS Engineering Management Technical Campus
Unit 2 Notes
WebTechnologies(CIE-356T)

The HTML DOM is a standard object model and programming interface for HTML.
It defines:

• The HTML elements as objects


• The properties of all HTML elements
• The methods to access all HTML elements
• The events for all HTML elements

In other words: The HTML DOM is a standard for how to get, change, add, or
delete HTML elements.

JavaScript - HTML DOM Methods

HTML DOM methods are actions you can perform (on HTML Elements).

HTML DOM properties are values (of HTML Elements) that you can set or change.

The DOM Programming Interface

The HTML DOM can be accessed with JavaScript (and with other programming
languages).

In the DOM, all HTML elements are defined as objects.

The programming interface is the properties and methods of each object.

A property is a value that you can get or set (like changing the content of an HTML
element).

A method is an action you can do (like add or deleting an HTML element).

Example

The following example changes the content (the innerHTML) of the <p> element
with id="demo":

Example

<html>
<body>

<p id="demo"></p>

Dr. Shilpi Singh,Associate Professor,JIMS,Greater Noida


JIMS Engineering Management Technical Campus
Unit 2 Notes
WebTechnologies(CIE-356T)

<script>
document.getElementById("demo").innerHTML = "Hello World!";
</script>

</body>
</html>

In the example above, getElementById is a method, while innerHTML is a property.

The getElementById Method

The most common way to access an HTML element is to use the id of the element.

In the example above the getElementById method used id="demo" to find the element.

The innerHTML Property

The easiest way to get the content of an element is by using the innerHTML property.

The innerHTML property is useful for getting or replacing the content of HTML
elements.

JavaScript HTML DOM - Changing HTML

The HTML DOM allows JavaScript to change the content of HTML elements.

Changing HTML Content

The easiest way to modify the content of an HTML element is by using


the innerHTML property.

To change the content of an HTML element, use this syntax:

document.getElementById(id).innerHTML = new HTML

This example changes the content of a <p> element:

Example

Dr. Shilpi Singh,Associate Professor,JIMS,Greater Noida


JIMS Engineering Management Technical Campus
Unit 2 Notes
WebTechnologies(CIE-356T)

<html>
<body>

<p id="p1">Hello World!</p>

<script>
document.getElementById("p1").innerHTML = "New text!";
</script>

</body>
</html>

Example explained:

• The HTML document above contains a <p> element with id="p1"


• We use the HTML DOM to get the element with id="p1"
• A JavaScript changes the content (innerHTML) of that element to "New text!"

This example changes the content of an <h1> element:

Example

<!DOCTYPE html>
<html>
<body>

<h1 id="id01">Old Heading</h1>

<script>
const element = document.getElementById("id01");
element.innerHTML = "New Heading";
</script>

</body>
</html>

Example explained:

• The HTML document above contains an <h1> element with id="id01"


• We use the HTML DOM to get the element with id="id01"
• A JavaScript changes the content (innerHTML) of that element to "New
Heading"

Changing the Value of an Attribute

To change the value of an HTML attribute, use this syntax:

Dr. Shilpi Singh,Associate Professor,JIMS,Greater Noida


JIMS Engineering Management Technical Campus
Unit 2 Notes
WebTechnologies(CIE-356T)

document.getElementById(id).attribute = new value

This example changes the value of the src attribute of an <img> element:

Example

<!DOCTYPE html>
<html>
<body>

<img id="myImage" src="smiley.gif">

<script>
document.getElementById("myImage").src = "landscape.jpg";
</script>

</body>
</html>

Example explained:

• The HTML document above contains an <img> element with id="myImage"


• We use the HTML DOM to get the element with id="myImage"
• A JavaScript changes the src attribute of that element from "smiley.gif" to
"landscape.jpg"

Dynamic HTML content

JavaScript can create dynamic HTML content:

Date : Wed Feb 19 2025 11:27:57 GMT+0530 (India Standard Time)

Example

<!DOCTYPE html>
<html>
<body>

<script>
document.getElementById("demo").innerHTML = "Date : " + Date(); </script>

</body>
</html>

Dr. Shilpi Singh,Associate Professor,JIMS,Greater Noida


JIMS Engineering Management Technical Campus
Unit 2 Notes
WebTechnologies(CIE-356T)

document.write()

In JavaScript, document.write() can be used to write directly to the HTML output


stream:

Example

<!DOCTYPE html>
<html>
<body>

<p>Bla bla bla</p>

<script>
document.write(Date());
</script>

<p>Bla bla bla</p>

</body>
</html>

JavaScript Forms

JavaScript Form Validation

HTML form validation can be done by JavaScript.

If a form field (fname) is empty, this function alerts a message, and returns false, to
prevent the form from being submitted:

JavaScript Example

function validateForm() {
let x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}

The function can be called when the form is submitted:

Dr. Shilpi Singh,Associate Professor,JIMS,Greater Noida


JIMS Engineering Management Technical Campus
Unit 2 Notes
WebTechnologies(CIE-356T)

HTML Form Example

<form name="myForm" action="/action_page.php" onsubmit="return


validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>

JavaScript Can Validate Numeric Input

JavaScript is often used to validate numeric input:

Please input a number between 1 and 10

Submit

Automatic HTML Form Validation

HTML form validation can be performed automatically by the browser:

If a form field (fname) is empty, the required attribute prevents this form from being
submitted:

HTML Form Example

<form action="/action_page.php" method="post">


<input type="text" name="fname" required>
<input type="submit" value="Submit">
</form>

Automatic HTML form validation does not work in Internet Explorer 9 or earlier.

Data Validation

Data validation is the process of ensuring that user input is clean, correct, and useful.

Typical validation tasks are:

Dr. Shilpi Singh,Associate Professor,JIMS,Greater Noida


JIMS Engineering Management Technical Campus
Unit 2 Notes
WebTechnologies(CIE-356T)

• has the user filled in all required fields?


• has the user entered a valid date?
• has the user entered text in a numeric field?

Most often, the purpose of data validation is to ensure correct user input.

Validation can be defined by many different methods, and deployed in many different
ways.

Server side validation is performed by a web server, after input has been sent to the
server.

Client side validation is performed by a web browser, before input is sent to a web
server.

HTML Constraint Validation

HTML5 introduced a new HTML validation concept called constraint validation.

HTML constraint validation is based on:

• Constraint validation HTML Input Attributes


• Constraint validation CSS Pseudo Selectors
• Constraint validation DOM Properties and Methods

Constraint Validation HTML Input Attributes


Attribute Description
disabled Specifies that the input element should be disabled
max Specifies the maximum value of an input element
min Specifies the minimum value of an input element
pattern Specifies the value pattern of an input element
required Specifies that the input field requires an element
type Specifies the type of an input element

Constraint Validation CSS Pseudo Selectors


Selector Description

Dr. Shilpi Singh,Associate Professor,JIMS,Greater Noida


JIMS Engineering Management Technical Campus
Unit 2 Notes
WebTechnologies(CIE-356T)

:disabled Selects input elements with the "disabled" attribute specified


:invalid Selects input elements with invalid values
:optional Selects input elements with no "required" attribute specified
:required Selects input elements with the "required" attribute specified
:valid Selects input elements with valid values

Introduction to JSP

JavaServer Pages (JSP) is a server-side technology that creates dynamic web


applications. It allows developers to embed Java code directly into HTML or XML
pages and it makes web development more efficient.
JSP is an advanced version of Servlets. It provides enhanced capabilities for
building scalable and platform-independent web pages.

How is JSP More Advantageous than Servlets?

JSP simplifies web development by combining the strengths of Java with the
flexibility of HTML. Some of the advantages of JSP over Servlets are listed below:
• JSP code is easier to manage than Servlets as it separates UI and business
logic.
• JSP minimizes the amount of code required for web applications.
• Easily generates content dynamically in response to user interactions.
• It provides access to the complete range of Java APIs for robust application
development.
• JSP is suitable for applications with growing user bases.

Key Features of JSP

• Platform Independence: Write once, run anywhere.


• It simplifies database interactions for dynamic content.
• It contains predefined objects like request, response, session, and application
reduce development time.
• It has built-in mechanisms for exception and error management.
• It supports custom tags and tag libraries.
JSP Architecture
JSP follows a three-layer architecture:
1. Client Layer: The browser sends a request to the server.
2. Web Server Layer: The server processes the request using a JSP engine.
3. Database/Backend Layer: Interacts with the database and returns the
response to the client.

Dr. Shilpi Singh,Associate Professor,JIMS,Greater Noida


JIMS Engineering Management Technical Campus
Unit 2 Notes
WebTechnologies(CIE-356T)

Differences Between JSP and Servlets

Features JSP Servlet

Code Length Jsp required less code Servlets required more code

Ease of Use Jsp is simple to use Servlet is more complex to use

Dynamic Content Easily embedded in Requires HTML generation in


HTML code

Page Easier to maintain More challenging


Maintenance

Steps to Create a JSP Application


JSP allows us to embed Java code within HTML pages and making it easy to create
dynamic content. Let us start with a simple exercise to convert an existing HTML
file into a JSP file.

Steps to Create a JSP

1. Take any HTML file you have previously created.


2. Change the file extension from .html to .jsp.
3. Load the new .jsp file in browser.
When we load a JSP file for the first time:
• The JSP is converted into a Java file.
• The Java file is compiled into a servlet.
• The compiled servlet is loaded and executed.

Adding Dynamic Content with JSP

Here is an example to demonstrate how JSP can generate dynamic content:


hello.jsp:
<!DOCTYPE html><html><body>
Hello! The time is now <%= new java.util.Date() %></body></html>
Explanation:
• The <%= %> tags enclose a Java expression.
• The new java.util.Date() expression retrieves the current date and time.
• When the JSP page is loaded in the browser, the Java expression is evaluated
at runtime, and the output is embedded into the HTML.
• Each time you reload the page, it displays the current time, demonstrating
how JSP dynamically generates HTML content based on Java logic.

Dr. Shilpi Singh,Associate Professor,JIMS,Greater Noida


JIMS Engineering Management Technical Campus
Unit 2 Notes
WebTechnologies(CIE-356T)

JSP Elements

We will learn about the several elements available in JSP with suitable examples. In
JSP elements can be divided into 4 different types.
• Expression
• Scriplets
• Directives
• Declarations

1. Expression

This tag is used to output any data on the generated page. These data are
automatically converted to a string and printed on the output stream.
Syntax:
<%= “Anything” %>
Note: JSP Expressions start with Syntax of JSP Scriptles are with <%=and ends
with %>. Between these, you can put anything that will convert to the String and
that will be displayed.
Example:
<%=”HelloWorld!” %>

2. Scriplets

This allows inserting any amount of valid Java code. These codes are placed in the
_jspService() method by the JSP engine.
Syntax:
<%
// Java codes
%>
Note: JSP Scriptlets begins with <% and ends %> . We can embed any amount of
Java code in the JSP Scriptlets. JSP Engine places these codes in the _jspService()
method.
Example:
<%
String name = “Geek”;
out.println(“Hello, ” + name);
%>
Variables available to the JSP Scriptlets are:
• Request
• Response

Dr. Shilpi Singh,Associate Professor,JIMS,Greater Noida


JIMS Engineering Management Technical Campus
Unit 2 Notes
WebTechnologies(CIE-356T)

• Session
• Out

3. Directives

A JSP directive starts with <%@ characters. In the directives, we can import
packages, define error-handling pages, or configure session information for the JSP
page.
Syntax:
<%@ directive attribute=”value” %>
Types of Directives:
• page: It defines page settings.
• include: It includes other files.
• taglib: It declares a custom tag library.

4. Declarations

This is used for defining functions and variables to be used in the JSP.
Syntax:
<%!
//java codes
%>
Note: JSP Declaratives begins with <%! and ends %> with We can embed any
amount of java code in the JSP Declaratives. Variables and functions defined in the
declaratives are class-level and can be used anywhere on the JSP page.
Example:
<%@ page import="java.util.*" %><html><body>
<%!
Date theDate = new Date();
Date getDate() {
System.out.println("In getDate() method");
return theDate;
}
%>
Hello! The time is now <%= getDate() %></body></html>

Example of a JSP Web Page

Example:
<!DOCTYPE html><html><head>
<title>A Web Page</title></head><body>

Dr. Shilpi Singh,Associate Professor,JIMS,Greater Noida


JIMS Engineering Management Technical Campus
Unit 2 Notes
WebTechnologies(CIE-356T)

<% out.println("Hello there!"); %></body></html>


Running a Simple JSP Page

Steps to Run JSP

1. Save the JSP file using the .jsp extension (e.g., hello.jsp).
2. Start the server (e.g., Apache Tomcat).
3. Place your application inside the appropriate folder (e.g., webapps for
Tomcat).
4. Open the browser and enter the JSP page URL:
http://localhost:portnumber/YourApplicationContextRoot/jspfile
The JSP file is compiled and executed.

The Lifecycle of a JSP Page

The JSP pages follow these phases:

o Translation of JSP Page


o Compilation of JSP Page
o Classloading (the classloader loads class file)
o Instantiation (Object of the Generated Servlet is created).
o Initialization ( the container invokes jspInit() method).
o Request processing ( the container invokes _jspService() method).
o Destroy ( the container invokes jspDestroy() method).
Note: jspInit(), _jspService() and jspDestroy() are the life cycle methods of JSP.

As depicted in the above diagram, JSP page is translated into Servlet by the help of
JSP translator. The JSP translator is a part of the web server which is responsible for
translating the JSP page into Servlet. After that, Servlet page is compiled by the

Dr. Shilpi Singh,Associate Professor,JIMS,Greater Noida


JIMS Engineering Management Technical Campus
Unit 2 Notes
WebTechnologies(CIE-356T)

compiler and gets converted into the class file. Moreover, all the processes that
happen in Servlet are performed on JSP later like initialization, committing response
to the browser and destroy.

Creating a simple JSP Page

To create the first JSP page, write some HTML code as given below, and save it
by .jsp extension. We have saved this file as index.jsp. Put it in a folder and paste the
folder in the web-apps directory in apache tomcat to run the JSP page.

index.jsp
Let's see the simple example of JSP where we are using the scriptlet tag to put Java
code in the JSP page. We will learn scriptlet tag later.

. <html>
. <body>
. <% out.print(2*5); %>
. </body>
. </html>
It will print 10 on the browser.

How to run a simple JSP Page?

Follow the following steps to execute this JSP page:

o Start the server


o Put the JSP file in a folder and deploy on the server
o Visit the browser by the URL http://localhost:portno/contextRoot/jspfile, for
example, http://localhost:8888/myapplication/index.jsp

The Directory structure of JSP

The directory structure of JSP page is same as Servlet. We contain the JSP page
outside the WEB-INF folder or in any directory.

Dr. Shilpi Singh,Associate Professor,JIMS,Greater Noida


JIMS Engineering Management Technical Campus
Unit 2 Notes
WebTechnologies(CIE-356T)

In JSP (Java Server Pages), session tracking is essential for maintaining user-
specific data across multiple requests. Two commonly used techniques for session
tracking in JSP are:

1. Using Cookies
2. Using HttpSession (Session Object)

1. Session Tracking Using Cookies

Cookies are small pieces of data stored on the client’s browser and sent to the server
with each request.

Steps to Implement Cookies in JSP

• Create and set cookies in a JSP page.


• Retrieve cookies in another JSP page.

Example: Setting a Cookie

jsp
CopyEdit
<%
Cookie userCookie = new Cookie("username", "JohnDoe");
userCookie.setMaxAge(60 * 60 * 24); // Cookie valid for 1 day
response.addCookie(userCookie);
%>
Cookie has been set!

Example: Retrieving a Cookie

jsp

Dr. Shilpi Singh,Associate Professor,JIMS,Greater Noida


JIMS Engineering Management Technical Campus
Unit 2 Notes
WebTechnologies(CIE-356T)

CopyEdit
<%
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals("username")) {
out.print("Welcome back, " + cookie.getValue());
}
}
} else {
out.print("No cookies found!");
}
%>

Notes:

• Cookies store small amounts of data and are sent with each HTTP request.
• Use setMaxAge(0) to delete a cookie.

2. Session Tracking Using HttpSession

HttpSession is a built-in JSP API that maintains user data across multiple requests on
the server.

Steps to Implement HttpSession in JSP

1. Create a session and store attributes.


2. Retrieve the session attributes in another JSP page.

Example: Storing Data in Session

jsp
CopyEdit
<%
HttpSession sessionObj = request.getSession();
sessionObj.setAttribute("user", "JohnDoe");
%>
User session is created!

Example: Retrieving Session Data

jsp
CopyEdit
<%
HttpSession sessionObj = request.getSession(false);
if (sessionObj != null && sessionObj.getAttribute("user") != null) {
out.print("Hello, " + sessionObj.getAttribute("user"));

Dr. Shilpi Singh,Associate Professor,JIMS,Greater Noida


JIMS Engineering Management Technical Campus
Unit 2 Notes
WebTechnologies(CIE-356T)

} else {
out.print("No active session found!");
}
%>

Example: Invalidating a Session

jsp
CopyEdit
<%
HttpSession sessionObj = request.getSession(false);
if (sessionObj != null) {
sessionObj.invalidate();
out.print("Session has been destroyed!");
}
%>

Notes:

• request.getSession(true) creates a new session if none exists.


• request.getSession(false) returns null if no session exists.
• session.invalidate() destroys the session.

Comparison: Cookies vs. HttpSession

Feature Cookies HttpSession


Storage
Stored on the client (browser) Stored on the server
Location
Data Limit Limited (few KBs) No strict limit
Security Less secure (visible to users) More secure (server-side)
Persistent (even after closing
Lifespan Expires when session ends
browser, if set)
Slightly slower, but better
Performance Faster, but sent with every request
security

Which one to use?

• Use cookies for lightweight data storage and persistent user preferences.
• Use HttpSession for secure, temporary storage of user data.

Dr. Shilpi Singh,Associate Professor,JIMS,Greater Noida

You might also like