Module-2
JSP(Jakarta Server
pages/Java Server pages)
• 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.
Advantages of JSP over Servlets
• JSP simplifies web development by combining the strengths of
Java with the flexibility of HTML.
• 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.
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 3-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.
Steps to Create a JSP
Application
• JSP allows us to embed Java code within HTML pages
and making it easy to create dynamic content.
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:
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.
JSP Elements
• 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.
2. Scriplets
Scriplets
This
This allows
allows inserting
inserting any
any amount
amount of
of valid
valid Java
Java code.
code. These
These codes
codes are
are placed
placed in
in the
the
_jspService() method by the JSP engine.
_jspService() method by the JSP engine.
Syntax:
<%
// Java codes
%>
Note: JSP Scriptlets begins with <% and ends %> . We can embed any amount of Java
Note:
code inJSP theScriptlets beginsJSP
JSP Scriptlets. with <% and
Engine ends
places %> codes
these . We can embed
in the any amount
_jspService() of Java
method.
code
Example:in the JSP Scriptlets. JSP Engine places these codes in the _jspService() method.
<%
Example:
String
<% name = “Geek”;
out.println(“Hello, ” + name);
String name = “Geek”;
%>
out.println(“Hello, ” + name);
Variables
%> available to the JSP Scriptlets are:
• Request
Variables
• Response available to the JSP Scriptlets are:
•• Request
Session
•• Response
Out
• 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.
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.
Why Use JSP?
JSP is powerful because it allows us to:
• Embed Java logic directly into HTML.
• To create dynamic pages that respond to user actions.
• To customize content for each user or session.
• JSP stands for Jakarta Server Pages (JavaServer Pages).
• It is a programming tool that is used on the Application Server Side
to create dynamic web pages.
• JSP basically used to support Platform–Independent and Dynamic
methods to build web-dependent applications based on HTML, XML,
SOAP, etc.
• JSP allows developers to embed Java code as well as pre-defined
tags.
• JSP pages are like ASP (Active Server Pages) in that they are
compiled on the server, instead of the user’s web browser.
• JSP was developed by Sun Microsystems Company in
1999.
• For the development of the JSP, languages are used all the
functions built into it have been created in the Java
programming language.
Characteristics of JSP
• JSP is an extended version of Servlet Technology.
• JSP technology is similar to the Servlet application program
interface(API).
• It provides some additional features such as expression
language and Custom tags etc.
• A JSP file is much easier to deploy because the JSP engine
performs the recompilation for the Java code automatically
Advantages of JSP
• Extension to Servlet:
• JSP is extension of Servlet.
• We can use all the features of Servlet in JSP.
• We can use Implicit objects, Predefined tags, Customized tags, and
expression language that JSP development easily.
• Easy To Maintain: It is easily managed because we can easily
separate our Business Logic in Servlet technology.
• Fast Development: No need to recompile and redeploy if the JSP
page is modified. The Servlet code needs to be recompiled and
updated if we want to change the look and feel of the Application.
• Less Code than Servlet: In JSP we can use a lot of tags such as
action tags, Custom tags, etc that reduce the code.
Disadvantages of JSP
• JSP is difficult to debug or trace errors because JSP pages are
first translated into servlets before the compilation process.
• Database connectivity is not easy.
• JSP pages require more disk space to hold the JSP page.
• JSP pages need more time when accessed for the first as they
are to compile on the server.
Uses of JSP
• JSP has many advantages.
• The dynamic part is written in Java, not Visual Basic or another MS-
specific language, so it is more powerful and easier to use.
• It is platform independent for Non-Microsoft web servers and other
OS.
• JSP helps developers for making use of Special JSP tags for Insert
Java Code in HTML pages.
• JSP may be also be used to access JavaBeans objects.
• JSP allow to share information across pages using request and
response objects.
The following JSP program calculates factorial values for an integer number, while the input is taken from an HTML form.
Factorial.jsp
<html>
input.html <body>
<html> <%!
long n, result;
<body> String str;
<form action="Factorial.jsp"> long fact(long n) {
if(n==0)
Enter a value for n: <input return 1;
type="text" name="val"> else
return n*fact(n-1);
<input type="submit" }
%>
value="Submit"> <%
</form> str
n
=
=
request.getParameter("val");
Long.parseLong(str);
</body> result = fact(n);
%>
</html> <b>Factorial value: </b> <%= result %>
</body>
</html>
Fibonacci.jsp
<html>
<body>
The following JSP program shows <%!
the Fibonacci series up to a int n;
particular term, while the input String str;
is taken from an HTML form. int fibo(int n) {
input.html if(n<2)
<html> return n;
<body> else
return fibo(n-1) + fibo(n-2);
<form action="Fibonacci.jsp">
}
Enter a value for n: <input %>
type="text" name="val"> <b>Fibonacci series: </b><br>
<input type="submit" <%
value="Submit"> str = request.getParameter("val");
</form> n = Integer.parseInt(str);
</body>
</html> for(int i=0; i<=n; i++) {
out.print(fibo(i) + " ");
}
%>
</body>
</html>
The following JSP program shows the System date and time.
Date.jsp
<html>
<body>
<%-- JSP comments --%>
<%@page import="java.util.Date"%>
<%!
Date date;
%>
<%
date = new Date();
%>
<b>System date and time: </b> <%= date %>
</body>
</html>
The following JSP program calculates Powers of 2 for integers in the range 0-10.
PowersOf2.jsp
<html>
<head>
<title>Powers of 2</title>
</head>
<body>
<center>
<table border="2" align="center">
<th>Exponent</th>
<th>2^Exponent</th>
<% for (int i=0; i<=10; i++) { //start for loop %>
<tr>
<td><%= i%></td>
<td><%= Math.pow(2, i) %></td>
</tr>
<% } //end for loop %>
</table>
</center>
</body>
</html>
• When a JSP file is processed,
• a web server first receives a request for the JSP
page from a client
• then the JSP engine within the server compiles
the JSP into a servlet
• which is then executed to generate dynamic
HTML content that is finally sent back to the
client as a response
• JSP pages are translated into servlets at
runtime and executed to produce dynamic
web content.
Key steps in JSP processing:
Client request:
• The user's web browser sends an HTTP request to the web server asking for a specific JSP
page.
JSP engine recognition:
• The web server identifies the file extension as ".jsp" and forwards the request to the JSP
engine.
Compilation to servlet:
• The JSP engine compiles the JSP page into a servlet class, translating any JSP tags and
expressions into Java code.
Servlet execution:
• The compiled servlet is then executed by the web server's servlet container, allowing it to
access Java functionalities like database interaction and logic processing.
Dynamic content generation:
• During execution, the servlet generates the dynamic HTML content based on the JSP code
and any data retrieved from the database or other sources.
Response to client:
• The generated HTML is sent back to the client's web browser as the response to the initial
Important points to remember about JSP processing:
Automatic compilation:
• JSP compilation happens at runtime, meaning the JSP page is
compiled into a servlet only when it is first requested by a client.
JSP tags and expressions:
• JSP pages can contain special tags and expressions that allow for
dynamic content generation within the HTML structure.
Java code integration:
• JSP allows developers to embed Java code within the JSP page to
perform server-side logic and data manipulation.
Web container role:
• The web server's servlet container is responsible for managing
the execution of the compiled JSP servlet.
JSP Architecture
• JSP architecture gives a high-level view of the
working of JSP.
• JSP architecture is a 3 tier architecture.
• It has a
• Client
• Web Server
• Database.
• The client is the web browser or application on the user side.
• Web Server uses a JSP Engine i.e a container that processes JSP.
• For example, Apache Tomcat has a built-in JSP Engine.
• JSP Engine intercepts the request for JSP and provides the
runtime environment for the understanding and processing of JSP
files.
• It reads, parses, build Java Servlet, Compiles and Executes Java
code, and returns the HTML page to the client.
• The webserver has access to the Database.
Architecture of JSP
• JSP is a server-side technology.
• It is used for creating web applications.
• It is used to create dynamic web content.
• In this JSP tags are used to insert JAVA code into HTML pages.
• It is an advanced version of Servlet Technology.
• It is a Web-based technology that helps to create dynamic and
platform-independent web pages.
• In this, Java code can be inserted in HTML/ XML pages or both.
• JSP is first converted into a servlet by JSP container before
processing the client’s request.
JSP Processing
• Step 1: The client navigates to a file ending with the .jsp extension and the
browser initiates an HTTP request to the webserver.
• Step 2: If the compiled version of JSP exists in the web server, it returns
the file. Otherwise, the request is forwarded to the JSP Engine. This is done
by recognizing the URL ending with .jsp extension.
• Step 3: The JSP Engine loads the JSP file and translates the JSP to
Servlet(Java code). This is done by converting all the template text into
println() statements and JSP elements to Java code. This process is
called translation.
• Step 4: The JSP engine compiles the Servlet to an executable .class file. It
is forwarded to the Servlet engine. This process is called
compilation or request processing phase.
• Step 5: The .class file is executed by the Servlet engine which is a part of
the Web Server. The output is an HTML file. The Servlet engine passes the
output as an HTTP response to the webserver.
• Step 6: The web server forwards the HTML file to the client’s browser.
JSP Scripting Constructs
• JSP scripting elements are snippets of Java code that can
be included in a JSP page.
• They allow developers to use Java programming
statements in their JSP pages.
Types of JSP scripting elements
• Declarations: Declare methods or member variables that will be
used in the JSP page.
• Expressions: Evaluate Java expressions and display them on the
page.
• Scriptlets: Intermix portions of Java code within the markup
language of the page.
• Comments: Developer comments embedded within the JSP
code.
How to use JSP scripting elements
• Use <%!...%> declaration tags to declare a member variable
or method.
• Use <%=...%> tags to contain a JSP expression.
• Use <% code %> to contain a scriptlet.
• Use <%! code %> to contain a declaration.
When to use JSP scripting elements?
• JSP scripting elements are used to
• create and access objects
• define methods
• manage the flow of control.
• Custom tag libraries can eliminate many tasks that
require scripts.
JSP | Scriptlet Tag
• JSP is a technology for controlling the content or appearance of Web pages
through the use of servlets.
• Small programs that are specified in the Web page and run on the Web
server to modify the Web page before it is sent to the user who requested
it.
• There are 3 Scripting Element in JSP
1.Scriptlet tag
2.Expression tag
3.Declaration tag
• Using these tags we can insert our java code in JSP.
Scriptlet tag
• This tag allow user to insert java code in JSP.
• The statement which is written will be moved to jspservice()
using JSP container while generating servlet from JSP.
• When client make a request, JSP service method is invoked
and after that the content which is written inside the scriptlet
tag executes.
<html>
<body>
<% out.print("GeeksforGeeks"); %> <!-- scriptlet tag -->
</body>
</html>
Explanation
• The Syntax of JSP Scriptlet tag is begin with <!
• We can write our java code inside this tag.
• In java we use System.out.println for printing anything on
console. In JSP, we use only out.print to write something on
console
• out is a different class entirely which writes to the output
stream for the generated response.
• Create a HTML file to take username from user. Save
this file as index.html
<!--index.html -->
<!-- Example of JSP code which prints the Username -->
<html>
<body>
<form action="Geeks.jsp">
<!-- move the control to Geeks.jsp when Submit button is clicked -->
Enter Username:
<input type="text" name="username">
<input type="submit" value="Submit"><br/>
</form>
</body>
</html>
Creating a jsp file names as Geeks.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8“ pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
String name=request.getParameter("username");
out.print("Hello "+name);
%>
</body>
</html>
JSP Predefined Variables
• To simplify code in JSP expressions and scriptlets, there are 8
automatically defined variables/implicit objects.
• The available variables are
1. request
2. response
3. out
4. session
5. application
6. config
7. pageContext
8. page
request
This is the HttpServletRequest associated with the request, and lets you look at the
request parameters (via getParameter), the request type (GET, POST, HEAD), and
the incoming HTTP headers (cookies, Referer).
response
This is the HttpServletResponse associated with the response to the client. Since
the output stream is buffered, it is legal to set HTTP status codes and response
headers
out
This is the PrintWriter used to send output to the client. In order to make
the response object useful, this is a buffered version
of PrintWriter called JspWriter.
session
This is the HttpSession object associated with the request. Sessions are created automatically,
so this variable is bound even if there was no incoming session reference.
application
This is the ServletContext as obtained via getServletConfig().getContext().
It represents the entire web application.
config
This is the ServletConfig object for this page.
pageContext
JSP introduced a new class called PageContext to encapsulate use of server-specific features
like higher performance JspWriters.
page
JSP page directive is used to define the properties applying the JSP page, such as the size of the
allocated buffer, imported packages, and classes/interfaces, defining what type of page it is.
JSP Directives
JSP directives are the elements of a JSP source code that guide
the web container on how to translate the JSP page into its
respective servlet.
Syntax :
<%@ directive attribute = "value"%>
Directives can have a number of attributes as key-value
pairs and are separated by commas.
The blanks between the @ symbol and the directive name, and
between the last attribute and the closing %>, are optional.
Different types of JSP directives :
There are 3 different JSP directives available.
1. include
2. page
3. taglib
•Page Directives : JSP page directive is used to define the
properties applying the JSP page, such as the size of the
allocated buffer, imported packages, and classes/interfaces,
defining what type of page it is, etc.
• syntax of JSP page directive is as follows:
<%@page attribute = "value"%>
•Different properties/attributes :
The following are the different properties that can be
defined using page directive :
•import: This tells the container what
packages/classes are needed to be imported into the
program.
Syntax:
<%@page import = "value"%>
<%-- JSP code to demonstrate how to use page directive to import a package --%>
<%@page import = "java.util.Date"%>
<%Date d = new Date();%>
<%=d%>
•contentType: This defines the format of data that is being exchanged
between the client and the server.
Syntax:
<%@page contentType="value"%>
<%-- JSP code to demonstrate how to use page directive to set the type of
content --%>
<%@page contentType = "text/html" %>
<% = "This is sparta" %>
In JSP, the syntax <%= %> is used to output or display the result of an expression
directly into the response stream (HTML output). It's a shorthand way to embed Java
expressions within the JSP page.
<%-- JSP code to demonstrate how to use page directive to set the page
information --%>
<%@page contentType = "text/html" %>
<% = getServletInfo()%>
getServletInfo() method is part of the Servlet interface, typically implemented in servlets,
not directly in JSP pages. This method is used to retrieve information about the servlet, such
as version, author, etc.
•buffer: Defines the size of the buffer that is allocated for
handling the JSP page. The size is defined in Kilo Bytes.
Syntax:
<%@page buffer = "size in kb"%>
•language: Defines the scripting language used in the page. By
default, this attribute contains the value ‘java’.
•isELIgnored: This attribute tells if the page supports expression
language. By default, it is set to false. If set to true, it will disable
expression language.
Syntax:
<%@page isElIgnored = "true/false"%>
<%-- JSP code to demonstrate how to use page directive to ignore expression
language --%>
<%@page contentType = "text/html" %>
<%@page isELIgnored = "true"%>
<body bgcolor = "blue">
<c:out value = "${'This is sparta}"/>
</body>
•errorPage: Defines which page to redirect to, in case
the current page encounters an exception.
Syntax:
<%@page errorPage = "true/false"%>
//JSP code to divide two numbers
<%@ page errorPage = "error.jsp" %>
<%
// dividing the numbers
int z = 1/0;
out.print("division of numbers is: " + z);
%>
•isErrorPage: It classifies whether the page is an error
page or not.
•By classifying a page as an error page, it can use the
implicit object ‘exception’ which can be used to display
exceptions that have occurred.
Syntax:
<%@page isErrorPage="true/false"%>
//JSP code for error page, which displays the exception
<%@ page isErrorPage = "true" %>
<h1>Exception caught</h1>
The exception is: <% = exception %>
• Include directive :
• JSP include directive is used to include other files into the
current jsp page.
• These files can be html files, other Jsp files etc.
• The advantage of using an include directive is that it allows
code re-usability.
• The syntax of an include
<%@include directive
file is as follows:
= "file
location"%>
In the following code, we’re including the contents of an
HTML file into a jsp page.
a.html
<h1>This is the content of a.html</h1>
index.jsp
<% = Local content%>
<%@include file = "a.html"%>
<% = local content%>
•Taglib Directive : The taglib directive is used to
mention the library whose custom-defined tags are
being used in the JSP page.
•It’s major application is JSTL(JSP standard tag library).
Syntax:
<%@taglib uri = "library url" prefix="the
prefix to identify the tags of this library
with"%>
<%-- JSP code to demonstrate taglib directive--%>
<%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %>
<c:out value = "${'This is Sparta'}"/>
• In the above code, we’ve used to taglib directive to point to the
JSTL library which is a set of some custom-defined tags in JSP
that can be used in place of the scriptlet tag (<%..%>).
• The prefix attribute is used to define the prefix that is used to
identify the tags of this library.
• The prefix c is used in the <c:out> tag to tell the container that
this tag belongs to the library mentioned above.
Simple JSP Program to fetch database records
Create Table
To create the Employees table in the EMP database, use the following steps
Step 1
Open a Command Prompt and change to the installation directory as follows
Step 2
Step 3
Create the Employee table in the TEST database as follows
Create Data Records
SELECT Operation
Following example shows how we can execute the SQL SELECT statement using
JTSL in JSP programming
INSERT Operation :Following example shows how we can execute the SQL INSERT statement
using JTSL in JSP programming
DELETE Operation: Following example shows how we can execute the SQL
DELETE statement using JTSL in JSP programming
UPDATE Operation: Following example shows how we can execute the SQL
UPDATE statement using JTSL in JSP programming
JSP - Cookies Handling
• Cookies are text files stored on the client computer and they
are kept for various information tracking purposes.
• JSP transparently supports HTTP cookies using underlying
servlet technology.
• There are 3 steps involved in identifying and returning users
• Server script sends a set of cookies to the browser. For
example, name, age, or identification number, etc.
• Browser stores this information on the local machine for future
use.
• When the next time the browser sends any request to the web
server then it sends those cookies information to the server
and server uses that information to identify the user or may
be for some other purpose as well.
A JSP that sets a cookie might send headers that look something like this
• The Set-Cookie header contains
• a name value pair
• a GMT date
• a path
• a domain
• The name and value will be URL encoded.
• The expires field is an instruction to the browser to "forget" the cookie after the
given time and date.
• If the browser is configured to store cookies, it will then keep this information until
the expiry date.
• If the user points the browser at any page that matches the path and domain of the
cookie, it will resend the cookie to the server.
The browser's headers might look something like this
A JSP script will then have access to the cookies through the request
method request.getCookies() which returns an array of Cookie objects.
Setting Cookies with JSP
Setting cookies with JSP involves 3 steps
Step 1: Creating a Cookie object
Call the Cookie constructor with a cookie name and a cookie value, both of which are strings.
Cookie cookie = new Cookie("key","value");
Neither the name nor the value should contain white space or any of the following characters −
[]()=,"/?@:;
Step 2: Setting the maximum age
Use setMaxAge to specify how long (in seconds) the cookie should be valid. The following code
will set up a cookie for 24 hours.
cookie.setMaxAge(60*60*24);
Step 3: Sending the Cookie into the HTTP response headers
Use response.addCookie to add cookies in the HTTP response header as follows
response.addCookie(cookie);
<% // Create cookies for first and last names.
Cookie firstName = new Cookie("first_name",request.getParameter("first_name"));
Cookie lastName = new Cookie("last_name", request.getParameter("last_name"));
// Set expiry date after 24 Hrs for both the cookies.
firstName.setMaxAge(60*60*24);
lastName.setMaxAge(60*60*24);
// Add both the cookies in the response header.
response.addCookie( firstName );
response.addCookie( lastName ); %>
<html>
<head>
<title>Setting Cookies</title>
</head>
<body>
<center>
<h1>Setting Cookies</h1>
</center>
<ul> <li><p><b>First Name:</b>
<%= request.getParameter("first_name")%> </p></li>
<li><p><b>Last Name:</b> <%= request.getParameter("last_name")%>
</p></li> </ul>
</body>
</html>
Let us put the above code in main.jsp file and use it in the
following HTML page
<html>
<body>
<form action = "main.jsp" method = "GET">
First Name: <input type = "text" name = "first_name">
<br />
Last Name: <input type = "text" name = "last_name" />
<input type = "submit" value = "Submit" />
</form>
</body>
</html>
• Keep the above HTML content in a file hello.jsp and
put hello.jsp and main.jsp in <Tomcat-installation-directory>/web
apps/ROOT directory.
• When you will access http://localhost:8080/hello.jsp, here is the
actual output of the above form.
Enter the First Name and the Last Name and then click the submit button. This will display
the first name and the last name on your screen and will also set two
cookies firstName and lastName. These cookies will be passed back to the server when the
next time you click the Submit button.
What are Cookies? How Cookies are handled in JSP? Develop a program to
create with name “Username” and cookie value “xyz”. Also display stored
cookie in webpage.
What are Cookies?
• Cookies are small pieces of data sent from a website and stored on the user's
browser while the user is browsing the website.
• They are used to store information that can be accessed by the server or
client-side scripts later.
• Cookies help in maintaining user sessions, personalizing web content, and
tracking user activity.
How Cookies are handled in JSP?
In JSP cookies are handled using the javax.servlet.http.Cookie class.
JSP allows you to create, read, and manipulate cookies with the following steps:
1.Creating Cookies: To create a cookie, instantiate the Cookie class and add it to
the response object.
2.Sending Cookies to Client: Cookies are sent to the client browser via the
HttpServletResponse object.
3.Retrieving Cookies: To retrieve cookies, use the getCookies() method of the
HttpServletRequest object.
4.Deleting Cookies: To delete a cookie, set its max age to zero and add it back to
the response.
JSP Program to Create a Cookie with Name “Username” and Value “xyz” and Display it
<%@ page import="javax.servlet.http.Cookie" %> // Retrieve all cookies from the request
<%@ page import="java.io.PrintWriter" %> Cookie[] cookies = request.getCookies();
<html>
<head> // Display the stored cookie
<title>Cookie Example in JSP</title> if (cookies != null) {
</head> out.println("<h2>Stored Cookies:</h2>");
<body> for (Cookie cookie : cookies) {
<% if (cookie.getName().equals("Username")) {
// Create a cookie with name "Username" and out.println("<p>Cookie Name: " + cookie.getName() +
value "xyz" "</p>");
Cookie userCookie = new Cookie("Username", out.println("<p>Cookie Value: " + cookie.getValue() +
"xyz"); "</p>");
}
// Set cookie expiry time (optional). This sets the }
cookie to expire in 24 hours (60 * 60 * 24 seconds). } else {
userCookie.setMaxAge(60 * 60 * 24); out.println("<h2>No Cookies found!</h2>");
}
// Add the cookie to the response %>
response.addCookie(userCookie); </body>
</html>
Develop a JSP to create and read session attribute named “product” and
stores the value “2025”
Working with Sessions in JSP
• Sessions in JSP are used to store information about a user across multiple pages.
• The session data is stored on the server side, and a unique session ID is sent to the client
via a cookie.
• In JSP, session management is handled using the HttpSession interface.
Steps to Create and Read a Session Attribute in JSP:
1.Creating Session Attribute: Session attribute can be created by
using the setAttribute() method of the HttpSession object.
2.Reading Session Attribute: Retrieve a session attribute using the
getAttribute() method of the HttpSession object.
JSP Program to Create and Read a Session Attribute
Named “product” with Value “2025”
<%@ page import="java.io.PrintWriter" %>
// Retrieve the session attribute "product"
<html> String productValue = (String)
<head> session.getAttribute("product");
<title>Session Example in JSP</title>
</head> // Display the session attribute value
<body> if (productValue != null) {
<% out.println("<h2>Session Attribute
// Obtain the current session or create a new 'product': " + productValue + "</h2>");
session if none exists } else {
out.println("<h2>No session attribute
HttpSession session = request.getSession();
named 'product' found!</h2>");
// Create a session attribute named }
"product" and store the value "2025" %>
session.setAttribute("product", "2025"); </body>
</html>
Case Study: Browsing Database Tables
1. Introduction
• In database management, efficient table browsing is crucial for understanding
data structure, relationships, and the content stored.
• This case study explores the techniques, tools, and practices used to navigate
and interact with database tables, with an emphasis on improving productivity
and ensuring data integrity.
2. Scenario Overview
• A retail company has an SQL-based relational database that stores
information about customers, orders, products, inventory, and payments.
• The database is queried regularly by analysts, managers, and data engineers
to make informed business decisions.
• To optimize these activities, the organization needs to establish best
practices for browsing database tables efficiently.
3. Problem Statement
• With the growing size and complexity of the database, employees face
challenges in:
• Locating specific data across multiple tables
• Understanding the relationships between tables
• Visualizing the data without making redundant queries
• Navigating large datasets without compromising query performance
• Ensuring that sensitive data is accessed securely and efficiently
4. Key Stakeholders
• Data Analysts: Need access to tables to perform data aggregation and analysis
for reporting.
• Business Managers: Require real-time insights from sales, inventory, and
customer behavior to make informed decisions.
• Database Administrators (DBAs): Manage database integrity, optimize
queries, and enforce security policies.
• Developers: Work with database interactions to enhance business software.
5. Current Approach
The team primarily uses SQL clients and command-line interfaces (CLI) to query tables.
Basic SQL commands (SELECT, JOIN, etc.) are used to fetch data, but challenges arise with
more complex queries or when multiple tables must be combined.
Some of the common tools used include:
•MySQL Workbench
•pgAdmin for PostgreSQL
•SQL Server Management Studio (SSMS)
•DBeaver (universal database client)
The following issues are observed:
•Time-Consuming Queries: Querying large tables or executing JOIN operations on multiple
tables results in slow performance.
•Complex Joins: Understanding how tables relate through foreign keys is not always
straightforward.
•Security and Permissions: Not all users should have access to sensitive information, but
determining permission levels for browsing tables is not well-defined.
6. Proposed Solutions
6.1 Indexing and Optimization
•Indexes: Ensuring that common query columns (e.g., foreign keys,
commonly searched fields) are indexed will speed up the search process.
•Query Optimization: Use techniques such as EXPLAIN and ANALYZE
to identify bottlenecks in the queries and optimize query performance.
6.2 Schema Visualization
•ER Diagrams: Employ tools like MySQL Workbench or ERD-specific tools to
visualize relationships between tables. This helps users see how tables are
linked, making it easier to understand the structure before querying.
•Table Relationships: Providing visualizations for FOREIGN KEY
relationships between tables aids in understanding how to join data from
different tables.
6.3 Partitioning Large Tables
• Table Partitioning: For large datasets, partitioning tables based on
specific criteria (e.g., date ranges for transactions) can enhance
query speed.
• For instance, separating sales data by year can improve the
performance of time-based queries.
6.4 Granular Permissions
• Row-Level Security (RLS): In PostgreSQL and other database systems,
row-level security can be implemented to control which rows users
can access based on their roles.
• View-Based Access: Instead of giving users access to entire tables,
creating views with pre-filtered content ensures that users only see
the data relevant to their tasks.
6.5 Tools for Enhanced Browsing
• DBeaver or DataGrip: These advanced SQL editors allow for better
organization of queries, visual exploration of tables, and the ability
to switch between multiple databases easily.
• Database Dashboards: Platforms like Metabase or Looker provide
user-friendly dashboards that allow browsing without complex SQL,
which is beneficial for non-technical users.
7. SQL Techniques for Table Browsing
7.1 Filtering Data
SELECT * FROM Orders
WHERE OrderDate > '2025-01-01'
LIMIT 100;
Use the LIMIT clause to restrict results when browsing large tables to improve
performance .
7.2 Understanding Relationships (JOINs)
SELECT Customers.CustomerName, Orders.OrderDate
FROM Customers
JOIN Orders ON Customers.CustomerID = Orders.CustomerID
WHERE OrderDate > '2025-01-01’;
Using JOIN operations to link tables based on their relationships.
7.3 Exploring Table Structure
DESCRIBE Orders;
The DESCRIBE or EXPLAIN command (depending on the SQL dialect)
provides insight into the structure of the table, including data types and keys.
7.4 Using Views for Simplicity
CREATE VIEW CustomerOrders AS
SELECT Customers.CustomerName, Orders.OrderID,
Orders.OrderDate
FROM Customers
JOIN Orders ON Customers.CustomerID = Orders.CustomerID;
Views can simplify complex queries and give users easy access to commonly
used joins and datasets.
8. Measuring Success
Key performance indicators (KPIs) for assessing improvements in database
browsing include:
• Query Execution Time: Average time taken to retrieve data should reduce.
• User Feedback: Analysts and other stakeholders should report ease of use and
reduced complexity in navigating the database.
• Security Compliance: Audits should show that permissions are enforced
properly, and sensitive data is protected.
9. Conclusion
• Browsing database tables is an essential function for both technical and non-
technical users.
• Implementing strategies such as query optimization, schema visualization, and
the use of appropriate tools can significantly improve the efficiency and
security of database interactions.
• Balancing ease of access with data protection is key to ensuring all users have
the information they need without compromising sensitive data.