Unit Iv
Unit Iv
Introduction to JSP:
The Anatomy of a JSP
Page, JSP Processing,
Declarations,
Directives,
Expressions,
Code Snippets,
implicit
objects,
Using Beans in JSP Pages,
Using Cookies and session for session
tracking, connecting to database in JSP.
Introduction to JSP
Java Server Pages (JSP) is a server-side programming technology
that enables the creation of dynamic, platform-independent method
for building Web-based applications. JSP have access to the entire
family of Java APls, including the JDBC APl to access enterprise
databases.
JavaServer Pages (JSP) is a technology for developing Webpages
that supports dynamic content. This helps developers insert java
code in HTML pages by making use of special JSP tags, most of
which start with <% and end with %>.
A JavaServer Pages component is a type of Java servlet that is
designed to fulfill the role of a user interface for a Java web
application. Web developers write JSPs as text files that combine
HTML or XHTML code, XML elements, and embedded JSP
actions and commands.
Using JSP, you can collect input from users through Webpage forms,
present records from a database or another source, and create
Webpages dynamically.
JSP tags can be used for a variety of purposes, such as retrieving
information from a database or registering user preferences,
accessing JavaBeans components, passing control between pages,
and sharing information between requests, pages etc.
Downloaded by Deepthi P
Why to Learn JSP?
Downloaded by Deepthi P
Performance is significantly better because JSP allows
embedding Dynamic Elements in HTML Pages itself instead of
having separate CGl files.
JSP are always compiled before they are processed by the server
unlike CGl/Perl which requires the server to load an interpreter
and the target script each time the page is requested.
JavaServer Pages are built on top of the Java Servlets APl, so
like Servlets, JSP also has access to all the powerful
Enterprise Java APls, including JDBC, JNDI, EJB, JAXP,
etc.
JSP pages can be used in combination with servlets that
handle the business logic, the model supported by Java servlet
template engines.
Finally, JSP is an integral part of Java EE, a complete platform for
enterprise class applications. This means that JSP can play a part in
the simplest applications to the most complex and demanding.
Applications of JSP
There are many advantages of JSP over the Servlet. They are as follows:
1) Extension to Servlet
JSP technology is the extension to Servlet technology. We can use
all the features of the Servlet in JSP. ln addition to, we can use
implicit objects, predefined tags, expression language and Custom
tags in JSP, that makes JSP development easy.
2) Easy to maintain
JSP can be easily managed because we can easily separate our
business logic with presentation logic. ln Servlet technology, we mix
our business logic with the presentation logic.
Downloaded by Deepthi P
Translation of JSP Page
Downloaded by Deepthi P
Downloaded by Deepthi P
When a browser asks for a JSP, the JSP engine first checks to see
whether it needs to compile the page. lf the page has never been
compiled, or if the JSP has been modified since it was last
compiled, the JSP engine compiles the page.
The compilation process involves three steps −
JSP Initialization
When a container loads a JSP it invokes the jspInit() method before
servicing any requests.
The JSP container calls the jspInit() method once (like init() in Servlets).
<%!
public void jspInit() {
System.out.println("JSP Initialized!");
}
%>
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); %>
Downloaded by Deepthi P
</body>
</html>
Downloaded by Deepthi P
Output:
lO
A JSP page is simply a regular web page with JSP elements for
generating the parts of the page that differ for each request.
Everything in the page that is not a JSP element is called template text .
Template text can really be any text: HTML, WML, XML, or even plain
text. Since HTML is by far the most common web page language in use
Downloaded by Deepthi P
today, most of the descriptions and examples in this book are HTML-
based, but keep in mind that JSP has no dependency on HTML; it can
be used with any markup language. Template text is always passed
straight through to the browser.
Downloaded by Deepthi P
When a JSP page request is processed, the template text and the
dynamic content generated by the JSP elements are merged, and the
result is sent as the response to the browser.
<%!
// Declaration
int k = 0;
%>
<%
// Scriptlet: Business logic inside JSP
String num1 = request.getParameter("num1");
String num2 = request.getParameter("num2");
Architecture
Downloaded by Deepthi P
JSP Processing
The following steps explain how the web server creates the Webpage using
JSP −
All the mentioned steps can be seen in the following diagram −
Step 1: The client navigates to a file ending with the .jsp extension and the browser
initiates an HTTP request to the webserver. For example, the user enters the login details
and submits the button. The browser requests a status.jsp page from 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.
Downloaded by Deepthi P
Typically, the JSP engine checks to see whether a servlet for a JSP
file already exists and whether the modification date on the JSP is
older than the servlet. lf the JSP is older than its generated servlet,
the JSP container assumes that the JSP hasn't changed and that the
generated servlet still matches the JSP's contents. This makes the
process more efficient than with the other scripting languages (such
as PHP) and therefore faster.
So in a way, a JSP page is really just another way to write a servlet
without having to be a Java programming wiz. Except for the
translation phase, a JSP page is handled exactly like a regular
servlet.
Downloaded by Deepthi P
Elements of JSP/ JSP Code Snippets
JSP supports different types of code snippets to embed Java inside HTML.
The key types include:
1. JSP Declarations (<%! ... %>) → Define class-level variables/methods.
2. JSP Scriptlets (<% ... %>) → Write Java logic inside JSP.
3. JSP Expressions (<%= ... %>) → Output values dynamically.
4. JSP Directives (<%@ ... %>) → Configure JSP behavior.
5. JSP Actions (<jsp:... />) → Use predefined JSP elements.
The Scriptlet
Downloaded by Deepthi P
A scriptlet can contain any number of JAVA language statements,
variable or method declarations, or expressions that are valid in the
page scripting language.
Following is the syntax of Scriptlet −
<% code fragment %>
You can write the XML equivalent of the above syntax as follows −
<jsp:scriptlet>
code
fragment
</jsp:scriptlet>
Any text, HTML tags, or JSP elements you write must be outside the
scriptlet. Following is the simple and first example for JSP −
Downloaded by Deepthi P
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>JSP Scriptlet Example</title>
</head>
<body>
<%
int a = 10, b = 20;
int sum = a + b;
%>
</body>
</html>
JSP Declarations
A declaration declares one or more variables or methods that you
can use in Java code later in the JSP file. You must declare the
variable or method before you use it in the JSP file.
Following is the syntax for JSP Declarations −
<%! declaration; [ declaration; ]+ ... %>
You can write the XML equivalent of the above syntax as follows −
<jsp:declaratio
n> code
fragment
</jsp:declaration>
Following is an example for JSP Declarations −
<%! int i = 0; %>
<%! int a, b, c; %>
<%! Circle a = new Circle(2.0); %>
Downloaded by Deepthi P
JSP Expression
A JSP expression element contains a scripting language expression
that is evaluated, converted to a String, and inserted where the
expression appears in the JSP file.
Because the value of an expression is converted to a String, you can
use an expression within a line of text, whether or not it is tagged
with HTML, in a JSP file.
The expression element can contain any expression that is valid
according to the Java Language Specification but you cannot use a
semicolon to end an expression.
Following is the syntax of JSP Expression −
<%= expression %>
You can write the XML equivalent of the above syntax as follows –
<jsp:expression>
expression
</jsp:expression>
</body>
</html>
JSP Comments
Downloaded by Deepthi P
JSP comment marks text or statements that the JSP container should
ignore. A JSP comment is useful when you want to hide or
"comment out", a part of your JSP page. Not visible in the client’s
browser (processed at the server-side).
Following is the syntax of the JSP comments −
<%-- This is JSP comment --%>
Following example shows the JSP Comments −
<%-- This is a JSP comment. It will not be visible in the page source. --%>
<!-- This is an HTML comment. It will be visible in the page source. -->
</body>
</html>
Downloaded by Deepthi P
S.No. Syntax Purpose
There are a small number of special constructs you can use in various
cases to insert comments or characters that would otherwise be treated
specially. Here's a summary −
JSP Directives
JSP Directives are instructions to the JSP container that control the processing of JSP
pages. Directives do not produce output but affect the entire JSP page.
Directives are basically wont to configure the code that’s generated by the container
during a Servlet. JSP directives are JSP components that are used to give the
instructions to the JSP compiler. JSP directives will simplify writing JSP files. These
tags are used to give directions to the JSP page compiler. In web applications, JSP
Directives can be used to define present JSP page characteristics, to include the target
resource content into the present JSP page, and to make available user-defined tag
library into this JSP page. All the JSPdirectives are going to be resolved at the time of
translating the JSP page to the servlet. The majority of JSP Directives will not give a
direct effect to response generation.
A JSP directive affects the overall structure of the servlet class. lt usually
has
Downloaded by Deepthi P
the following form −
<%@ directive attribute="value" %>
There are three types of directive tag −
Syntax
<%@ page attribute="value" %>
Example:
Key Attributes:
Downloaded by Deepthi P
JSP Include Directive
Syntax
<%@ include file="header.jsp" %>
Example
Output:
Welcome to My Website
---------------------
Home Page Content
Downloaded by Deepthi P
<%@ page language="java" contentType="text/html; charset=ISO-8859-
1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<center>
<table width="100%" height="20%" bgcolor="red">
<tr>
<td colspan="2"><center>
<b><font size="7" color="white"> Hello World </font></b>
</center></td>
</tr>
</table>
</center>
</body>
</html>
body.jsp W
<%@ page language="java" contentType="text/html; charset=ISO-8859-
1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
Downloaded by Deepthi P
</html>
footer.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-
1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<center>
<table width="100%" height="15%" bgcolor="blue">
<tr>
<td colspan="2"><center>
<b><font size="6" color="white"> This is footer</font></b>
</center></td>
</tr>
</table>
</center>
</body>
</html>
mainpage.jsp
Downloaded by Deepthi P
JSP Taglib Directive(JavaServer Pages Standard Tag Library)
Addition.jsp
Downloaded by Deepthi P
<h2>Addition of Two Numbers</h2>
<form method="post">
Enter First Number: <input type="text" name="num1"><br><br>
Enter Second Number: <input type="text" name="num2"><br><br>
<input type="submit" value="Add">
</form>
<%
String num1 = request.getParameter("num1");
String num2 = request.getParameter("num2");
Palindrome.jsp
Downloaded by Deepthi P
<form method="post">
Enter a Number or String: <input type="text"
name="inputText"><br><br>
<input type="submit" value="Check">
</form>
<%
// Retrieve input from the form
String inputText = request.getParameter("inputText");
if (inputText.equalsIgnoreCase(reversedText)) {
%>
<h3 style="color: green;">"<%= inputText %>" is a
Palindrome!</h3>
<%
} else {
%>
<h3 style="color: red;">"<%= inputText %>" is NOT a
Palindrome!</h3>
<%
}
}
%>
</body>
</html>
JSP Actions
JSP actions use constructs in XML syntax to control the
behavior of the servlet engine.
Actions are used during request Processing Phase but directives
are used during translation phase.
Actions are re-evaluated every timethe Jsp is accessed.
You can dynamically insert a file, reuse JavaBeans components,
forward the user to another page, or generate HTML for the Java
plugin.
Downloaded by Deepthi P
JavaBeans are reusable Java classes that follow a specific convention and are
used in JSP applications to separate business logic from the presentation
layer.
Features of JavaBeans
Encapsulation – Private fields with public getters/setters
Serializable – Implements java.io.Serializable (optional but recommended)
No-argumentConstructor – Required for instantiation
Getter & Setter Methods – To access private properties
There is only one syntax for the Action element, as it conforms to the XML
standard −
<jsp:action_name attribute="value" />
Action elements are basically predefined functions. Following table lists out
the available JSP Actions −
Downloaded by Deepthi P
jsp:text Used to write template text in JSP pages
10
and documents.
jsp:include
<html>
<head>
<title>The include Action Example</title>
</head>
<body>
<center>
<h2>The include action Example</h2>
<jsp:include page = "date.jsp" flush = "true" />
</center>
</body>
</html>
jsp:forward
index.jsp
Downloaded by Deepthi P
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<jsp:forward page="welcome.jsp"/>
welcome.jsp
<h2>Welcome to the site!</h2>
<jsp:param>
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<jsp:forward page="greeting.jsp">
<jsp:param name="username" value="Alice"/>
</jsp:forward>
greeting.jsp
<jsp:plugin>
Syntax: <jsp:plugin code=”-” width=”-” height=”-” type=”-“/>
Attributes:
1. Code: It will take the fully qualified name of the applet.
2. Width: It is used to specify the width of the applet.
3. Height: It is used to specify the height of the applet.
4. Type: It can be used to specify which one we are going to include whether it applet or bean.
Example:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class MouseDrag extends Applet implements MouseMotionListener{
public void init(){
addMouseMotionListener(this);
setBackground(Color.red);
Downloaded by Deepthi P
}
public void mouseDragged(MouseEvent me){
Graphics g=getGraphics();
g.setColor(Color.white);
g.fillOval(me.getX(),me.getY(),20,20);
}
public void mouseMoved(MouseEvent me){}
}
index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Mouse Drag</title>
</head>
<body bgcolor="khaki">
<jsp:plugin align="middle" height="500" width="500" type="applet"
code="MouseDrag.class" name="clock" codebase="." />
</body>
</html>
Downloaded by Deepthi P
Response This is the HttpServletResponse object
2
associated with the response to the client.
</form>
Downloaded by Deepthi P
<%
%>
<%
response.sendRedirect("home.jsp");
%>
<%
%>
<%
%>
<%
%>
Downloaded by Deepthi P
Retrieve Data in Any Page
<%
out.println("<h2>Hello, JSP!</h2>");
%>
<%
%>
Downloaded by Deepthi P
Control-Flow Statements
You can use all the APls and building blocks of Java in your JSP
programming including decision-making statements, loops, etc.
Downloaded by Deepthi P
Decision-Making Statements
The if...else block starts out like an ordinary Scriptlet, but the
Scriptlet is closed at each line with HTML text included between the
Scriptlet tags.
<%! int day = 3; %>
<html>
<head><title>lF...ELSE Example</title></head>
<body>
<% if (day == 1 || day == 7) { %>
<p> Today is weekend</p>
<% } else { %>
<p> Today is not weekend</p>
<% } %>
</body>
</html>
Loop Statements
You can also use three basic types of looping blocks in Java: for, while, and
do…while blocks in your JSP
programming. Let us look at the
<%! int fontSize; %>
<html>
<head><title>FOR LOOP Example</title></head>
<body>
<% for ( fontSize = 1; fontSize <= 3; fontSize++) { %>
<font color = "green" size = "<%= fontSize %>">
JSP Tutorial
</font><br />
<% } %>
</body>
</html>
following for loop example −
JSP Tutorial
JSP Tutorial
Above example can be written using the while loop as follows −
Downloaded by Deepthi P
<%! int fontSize; %>
Downloaded by Deepthi P
<html>
<head><title>WHlLE LOOP Example</title></head>
<body>
<% while ( fontSize <= 3) { %>
<font color = "green" size = "<%= fontSize %>"> JSP Tutorial
</font><br />
<% fontSize++; %>
<% } %>
</body>
</html>
JSP Tutorial
JSP Tutorial
JSP Operators
JSP supports all the logical and arithmetic operators supported by
Java. Following table lists out all the operators with the highest
precedence appear at the top of the table, those with the lowest
appear at the bottom.
Within an expression, higher precedence operators will be evaluated first.
Downloaded by Deepthi P
Bitwise XOR ^ Left to right
JSP Literals
The JSP expression language defines the following literals −
Boolean − true and false
Integer − as in Java
Floating point − as in Java
String − with single and double quotes; " is escaped as \", ' is
escaped as \', and \ is escaped as \\.
Null − null
Downloaded by Deepthi P
To be considered a JavaBean, a class should:
1. Have a public no-argument constructor
2. Have private properties/fields (also called variables)
3. Have public getter and setter methods to access those fields
4. Should not contain any business logic (it's just a data holder)
Note: setter method is useful to set data to bean property whereas the getter method is useful to
read data from bean property.
Java Bean is useful to combine multiple simple values to an object and to send that object
from one resource to another resource or one layer to another layer. For example, to keep
form data into a single object we can use java bean. Java Bean is a specially constructed Java
class written in Java and coded according to the Java Beans API specification.
First, the browser sends the request for the JSP page. Then the JSP page accesses Java Bean
and invokes the business logic. After invoking the business logic Java Bean connects to the
database and gets/saves the data. At last, the response is sent to the browser which is generated
by the JSP.
Downloaded by Deepthi P
Advantages of Java Beans
1. It is easy to reuse the software components.
2. The properties and methods of Java Bean can be exposed to another application.
Downloaded by Deepthi P
2. Class: This attribute will take the fully qualified name of the Bean class.
3. Type: It will take the fully qualified name of the Bean class to define the type of variable in
order to manage the Bean object reference.
4. Scope: It will take either of the JSP scopes to the Bean object.
EXAMPLE:
<jsp:useBean id="user" class="your_package.User" scope="session" />
<jsp:setProperty>
The jsp:setProperty tag is utilized to set a property in the JavaBean object. The principle
motivation
behind jsp:setProperty tag is to execute a specific setter technique to set an incentive to a
specific Bean
property.
Attributes:
1. Name: It will take a variable that is the same as the id attribute value in <jsp:useBean> tag.
2. Property: It will take a property name in order to access the respective setter method.
3. Value: It will take a value to pass as a parameter to the respective setter method.
Example:
<jsp:setProperty name="user" property="name" value="Alice" />
<jsp:setProperty name="user" property="age" value="25" />
Downloaded by Deepthi P
<jsp:getProperty>
The jsp:getProperty tag is utilized to get indicated property from the JavaBean object. The
principle
reason for <jsp:getProperty> tag is to execute a getter strategy to get an incentive from the Bean
object.
Attributes:
1. Name: It will take a variable that is the same as the id attribute value in <jsp:useBean> tag.
2. Property: It will take a particular property to execute the respective getter method.
Example:
Test.java
package Action;
public class Test {
Downloaded by Deepthi P
private String message = "No message specified";
public String getMessage() {
return (message);
}
public void setMessage(String message) {
this.message = message;
}
}
index.jsp
<html>
<head>
<title>Using JavaBeans in JSP</title>
</head>
<body>
<h2>Using JavaBeans in JSP</h2>
<jsp:useBean id="test" class="Action.Test" />
<jsp:setProperty name="test" property="message" value="Hello JSP..." />
<p>Got message....</p>
<jsp:getProperty name="test" property="message" />
</body>
</html>
Downloaded by Deepthi P
StudentsBean.java
package Beans;
public StudentsBean() {}
Downloaded by Deepthi P
this.lastName = lastName;
}
Index.jsp
</body>
</html>
Output:
Downloaded by Deepthi P
Student Bean Example
First Name: saritha
Age: 38
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.
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.
Cookies are usually set in an HTTP header (although JavaScript can also set a cookie directly on a browser). A
JSP that sets a cookie might send headers that look something like this −
HTTP/1.1 200 OK
Date: Fri, 11 April 2024 21:03:38 GMT
Downloaded by Deepthi P
Server: Apache/1.3.9 (UNIX) PHP/4.0b3
Set-Cookie: name = xyz; expires = Saturday, 12-april-07 22:03:38 GMT;
path = /; domain = tutorialspoint.com
Connection: close
Content-Type: text/html
As you can see, the Set-Cookie header contains a name value pair, a GMT date, a path and 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.
Downloaded by Deepthi P
Step 1: Creating a Cookie object
You call the Cookie constructor with a cookie name and a cookie value, both of which are strings.
You 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);
You use response.addCookie to add cookies in the HTTP response header as follows
response.addCookie(cookie);
Deleting a Cookie
<%
Cookie deleteCookie = new Cookie("username", "");
deleteCookie.setMaxAge(0); // Deletes it
response.addCookie(deleteCookie);
%>
Example
setCookie.jsp
Downloaded by Deepthi P
getCookie.jsp
deleteCookie.jsp
Downloaded by Deepthi P
<h2>Cookie has been deleted.</h2>
<a href="getCookie.jsp">Try Getting Cookie Again</a>
</body>
</html>
HTTP is a "stateless" protocol which means each time a client retrieves a Webpage, the client
opens a separate connection to the Web server and the server automatically does not keep any record of
previous client request.
a common way to maintain user data across multiple pages during a user's visit (session).
Downloaded by Deepthi P
Each user gets a unique session when they visit your site.
Data stored in the session is accessible across all pages for that user.
JSP gives access to session via the implicit session object.
Cookies
A webserver can assign a unique session ID as a cookie to each web client and for subsequent requests
from the client they can be recognized using the received cookie.
This may not be an effective way as the browser at times does not support a cookie. It is not
recommended to use this procedure to maintain the sessions.
A web server can send a hidden HTML form field along with a unique session ID as follows −
This entry means that, when the form is submitted, the specified name and value are automatically
included in the GET or the POST data. Each time the web browser sends the request back,
the session_id value can be used to keep the track of different web browsers.
This can be an effective way of keeping track of the session but clicking on a regular (<A HREF...>)
hypertext link does not result in a form submission, so hidden form fields also cannot support general
session tracking.
URL Rewriting
You can append some extra data at the end of each URL. This data identifies the session; the server can
associate that session identifier with the data it has stored about that session.
URL rewriting is a better way to maintain sessions and works for the browsers when they don't support
cookies. The drawback here is that you will have to generate every URL dynamically to assign a session
ID though page is a simple static HTML page.
Apart from the above mentioned options, JSP makes use of the servlet provided HttpSession Interface.
This interface provides a way to identify a user across.
a one page request or
visit to a website or
store information about that user
By default, JSPs have session tracking enabled and a new HttpSession object is instantiated for each
Downloaded by Deepthi P
new client automatically. Disabling session tracking requires explicitly turning it off by setting the page
directive session attribute to false as follows −
<%@ page session = "false" %>
The JSP engine exposes the HttpSession object to the JSP author through the implicit session object.
Since session object is already provided to the JSP programmer, the programmer can immediately begin
storing and retrieving data from the object without any initialization or getSession().
Method Description
setAttribute(String name, Object value) Stores an object in the session, accessible by name.
getAttribute(String name) Retrieves an object from the session. Returns null if not found.
removeAttribute(String name) Removes an object from the session.
invalidate() Destroys the session completely. All data is lost.
getId() Returns the unique session ID assigned to the user.
getCreationTime() Returns the time when the session was created.
getLastAccessedTime() Returns the last time the client accessed the session.
isNew() Returns true if the session is newly created.
getMaxInactiveInterval() Gets the time (in seconds) the session will remain active without access.
Sets the session timeout
setMaxInactiveInterval(int seconds)
interval (in seconds).
Example:
Downloaded by Deepthi P
</form>
</body>
</html>
Downloaded by Deepthi P
connecting to database in JSP
Class.forName("com.mysql.cj.jdbc.Driver");
Downloaded by Deepthi P
<%
String url = "jdbc:mysql://localhost:3306/yourDatabaseName";
String username = "yourUsername";
String password = "yourPassword";
<%
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM students");
%>
Or for insert/update:
int rows = stmt.executeUpdate("INSERT INTO students(name, age) VALUES('John', 20)");
<%
rs.close();
stmt.close();
conn.close();
%>
Javax.sql.* package
The javax.sql package is an extension of the java.sql package, and it provides advanced JDBC features
primarily for enterprise-level applications. It's commonly used in Java EE (Jakarta EE) applications and
provides support for connection pooling, distributed transactions, and row sets.
Downloaded by Deepthi P
Key Interfaces in javax.sql:
DataSource: An alternative to DriverManager for obtaining a connection. Supports connection pooling and is
more suitable for enterprise apps.
PooledConnection : Represents a physical DB connection that can be reused (used with connection pooling).
RowSet: A wrapper around ResultSet with more flexibility; can be used in disconnected mode.
JdbcRowSet, CachedRowSet: Implementations of RowSet for scrollable and updatable result sets.
Java.sql.*package
The java.sql package in Java is part of the JDBC API (Java Database Connectivity), which provides the
necessary classes and interfaces to interact with relational databases. It's commonly used for tasks like
connecting to a database, executing SQL queries, and retrieving results.
Downloaded by Deepthi P