0% found this document useful (0 votes)
2 views

Servlet & JSP Reference Notes

Notes

Uploaded by

ak8651070623
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)
2 views

Servlet & JSP Reference Notes

Notes

Uploaded by

ak8651070623
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/ 295

Reference

Notes
[Digital Copy]

Servlet &
Java Server Pages

Join us for Better Career and Job Guarantee

[ Live Online & Offline Classes Available ]

LEARN-2-EARN LABS TRAINING INSTITUTE, AGRA


Website : www.LearntoearnLabs.com | Contact:+91-9837705705
Guiding Careers with
Visionary Support

Institute Director(s)

Mr. Mohit Singh is a professional full-stack trainer, project


consultant and startup mentor. He is holding expertise in Java,
Application Design, MERN Stack, DevOps, Design Thinking and
User Experience Design.
He has trained thousands of students & hundreds of employed
professionals. He completed his trainings in Google, Gurugram
and short term projects in IIT Delhi, IIT BHU & IIT Jodhpur.
He is also recognized as Mentor with startup India, Punjab
Startup, startup Uttarakhand, Mumbai State Innovation Society,
Atal Innovation Mission, etc. in the area of education & utility
services.
Mr. Mohit Singh
M.Tech, B.Tech (C.S.E) https://www.linkedin.com/in/mohit9pages/

Dr. Shubhendra Gupta is an experienced digital marketer,


Business Consultant and startup mentor with a demonstrated
history of working in the education and services industry.
He use to train students & working professionals for getting
better job opportunities and train business owners in
generating profits or leads. His areas of interest are Digital
Marketing, Business Development, Data Analysis, Strategic
Planning, Market Research & Reality, User Testing, Website
design, etc.
He is also recognized as Mentor with Startup Hubs &
Innovation Labs in the area of education, brand building &
Dr. Shubhendra Gupta business consultation.
Phd, B.Ed, M.Sc (Physics)
https://www.linkedin.com/in/dmshubhendra/

Institute Vision

To be an institute that provides a transformative learning to produce


highly skilled & competent professionals and to create leaders and
innovators for society and industry.

LEARN-2-EARN LABS TRAINING INSTITUTE, AGRA


Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Servlet
• Servlets are the java programs which executes on web server.
• Servlet takes request from the user and generate dynamic responses in the form
of html/text.
• Servlets are used to reduce the load of webserver and improve the efficiency of
web server.
• Servlets are Java classes used to handle requests and responses in web
applications.
• A Servlet is a Java programming language class used to extend the capabilities of
servers hosting applications accessed via a request-response programming model.
• Although servlets can respond to any type of request, they are commonly used to
extend the applications hosted by web servers.
• Servlets play a crucial role in Java-based web applications by providing a robust
and efficient way to handle client-server interactions.

Servlet : Use Cases

• Dynamic Content Generation: Servlets can be used to generate dynamic web


content, such as HTML or XML. They can take user input from web forms and
generate appropriate responses based on that input.
• Data Processing: Servlets can process data submitted through web forms, such as
saving user information in a database.
• Middleware: Servlets can act as middleware components between a web server
and backend systems like databases or other applications, managing requests and
responses.
• Session Management: Servlets can manage user sessions by storing user-specific
data across multiple requests.
• Web Services: Servlets can be used to create RESTful web services, providing a
mechanism for communication between different software applications over the
web.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Servlet : Life Cycle

The life cycle of a servlet is managed by the servlet container (e.g., Apache Tomcat). It
consists of the following phases:
• Loading and Instantiation: When a servlet is first requested, the servlet container
loads the servlet class and creates an instance of the servlet. This is typically done
once per servlet class.
• Initialization (init method): After instantiation, the servlet container calls the init
method of the servlet. This method is called only once and is used for initialization
tasks such as setting up database connections or reading configuration
parameters.
public void init(ServletConfig config) throws ServletException {
// Initialization code
}
• Request Handling (service method): For each client request, the servlet container
calls the service method. This method is responsible for handling requests and
generating responses. The service method can dispatch requests to doGet, doPost,
doPut, doDelete, etc., based on the HTTP request type.
public void service(ServletRequest req, ServletResponse res) throws
ServletException, IOException {
// Request processing code
}
The common structure within service typically looks like:
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
// Handle GET request
}
protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
// Handle POST request
}
• Destruction (destroy method): When the servlet container decides to remove a
servlet (usually when the server is shutting down or the servlet is no longer
needed), it calls the destroy method. This method allows the servlet to release
resources and perform clean-up tasks.
public void destroy() {
// Cleanup code
}

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Points to Remember
To create a simple web application using Servlet, we must have
• servlet program (.java)
• web.xml file (deployment descriptor)
▪ which contains the servlet declaration and its mapping.

So intially, we will create a servlet project using Servlet interface which exist inside
javax.servlet package. The javax.servlet package is not available inside the jvm or jdk.

The package is available inside servlet-api of the server(apache tomcat in our case) library.
To verify the availability of the package inside the servlet-api, extract the servlet-api jar
file which exist inside apache tomcat > lib.

Eclipse IDE
• Eclipse is an integrated development environment (IDE) widely used for Java
development, including Java EE (Enterprise Edition) applications.
• It provides a robust platform with many plugins to extend its functionality, making
it suitable for various programming tasks beyond Java, such as web development,
mobile development, and more.

Download & Setup

To download and set up Eclipse for developing Java EE applications, follow these steps:
• Visit the Eclipse Downloads Page: Go to the official Eclipse Downloads page
(https://www.eclipse.org/downloads/).
• Choose the Eclipse IDE for Enterprise Java and Web Developers: Look for the
package named "Eclipse IDE for Enterprise Java and Web Developers."
This package includes the necessary tools for Java EE development, including
support for Java, JavaScript, and other web technologies.
• Download the Installer: Click on the download link for the "Eclipse IDE for
Enterprise Java and Web Developers."
Choose the appropriate installer for your operating system (Windows, macOS, or
Linux).
• Run the Installer: After the download completes, run the installer file.
On Windows, it will be an .exe file; on macOS, a .dmg file; and on Linux, a .tar.gz
file.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

• Install Eclipse: Follow the prompts in the installer.


▪ When asked to select the package to install, ensure "Eclipse IDE for
Enterprise Java and Web Developers" is selected.
▪ Choose an installation folder and proceed with the installation.
• Launch Eclipse: Once the installation is complete, launch Eclipse.
You may be asked to select a workspace, which is a folder where your projects will
be stored. Choose a suitable location and proceed.
▪ Configure Java EE Environment: Ensure you have the Java Development Kit (JDK)
installed on your system. If not, download and install the latest JDK from the Oracle
website or OpenJDK.
In Eclipse, go to Window -> Preferences -> Java -> Installed JREs to add the JDK if
it's not already listed.
▪ Set Up a Server Runtime Environment: For Java EE development, you will likely
need a server such as Apache Tomcat, WildFly, or another Java EE server.
▪ Go to Window -> Preferences -> Server -> Runtime Environments.
▪ Click Add, select your server type (e.g., Apache Tomcat), and follow
the instructions to download and configure it.
▪ Create a New Java EE Project: Go to File -> New -> Other -> Java EE to create
new Java EE projects like Dynamic Web Projects, Enterprise Application Projects,
etc.
By following the above steps, you should be able to set up Eclipse for Java EE
development and start working on your Java EE projects.

let’s create a servlet project in eclipse:


1. Go to project window -> new -> dynamic web project
2. Enter the project name & choose the runtime (installed server) & click on next.
3. Check the build path and click on next
4. Check the web.xml deployment descriptor and click on finish.
5. Now inside project window, right click on your project.
6. Select new > servlet
7. Enter the package name (com.java.student) under which you want to create
your servlet source file & enter servlet class name (First Servlet).
8. Choose either next or finish.
9. Delete all the code statement exist inside servlet class. and copy the project
code given in next page & don’t forget to check the class name and package
name.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

FirstServlet.java
package com.java.student;

import java.io.IOException;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class FirstServlet implements Servlet


{
@Override
public void destroy() {
System.out.println("Servlet Destroyed");
}
@Override
public ServletConfig getServletConfig() {
return null;
}
@Override
public String getServletInfo() {
return null;
}
@Override
public void init(ServletConfig arg0) throws ServletException {
System.out.println("Servlet initialized");
}
@Override
public void service(ServletRequest arg0, ServletResponse arg1) throws
ServletException, IOException {
System.out.println("start servicing...");
}

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Now come to web.xml file which exist inside -> src -> main -> webapp -> WEB-INF
and overwrite the below source code

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID"
version="4.0">
<display-name>firstservlet</display-name>

<!-- servlet declaration -->


<servlet>
<servlet-name>first</servlet-name>
<servlet-class>com.java.student.FirstServlet</servlet-class>
</servlet>

<!-- servlet mapping -->


<servlet-mapping>
<servlet-name>first</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
</web-app>

At last, save all the things and run your web project using server (‘apache tomcat’).
Initially you will get “page not found” error, so enter the below url in the brower to go
to servlet.

http://localhost:8080/firstservlet/test

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Servlet Important Interfaces & Classes

When creating a web application using servlets, several important interfaces & classes
provided by the Servlet API are commonly used.

1. Servlet
The Servlet interface defines methods that all servlets must implement. This is the
core interface for any servlet.

Key Methods:
• void init(ServletConfig config): Called by the servlet container to indicate to
a servlet that the servlet is being placed into service.
• void service(ServletRequest req, ServletResponse res): Called by the servlet
container to allow the servlet to respond to a request.
• void destroy(): Called by the servlet container to indicate to a servlet that
the servlet is being taken out of service.
• ServletConfig getServletConfig(): Returns a ServletConfig object, which
contains initialization and startup parameters for this servlet.
• String getServletInfo(): Returns information about the servlet, such as
author, version, and copyright.

2. HttpServlet
The HttpServlet class extends the GenericServlet class and implements the Servlet
interface. It provides methods for handling HTTP-specific services.

Key Methods:
• void doGet(HttpServletRequest req, HttpServletResponse res): Handles the
HTTP GET request.
• void doPost(HttpServletRequest req, HttpServletResponse res): Handles the
HTTP POST request.
• void doPut(HttpServletRequest req, HttpServletResponse res): Handles the
HTTP PUT request.
• void doDelete(HttpServletRequest req, HttpServletResponse res): Handles
the HTTP DELETE request.
• void doHead(HttpServletRequest req, HttpServletResponse res): Handles
the HTTP HEAD request.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

3. ServletRequest
The ServletRequest interface defines an object to provide client request
information to a servlet.
The servlet container creates a ServletRequest object and passes it as an argument
to the servlet's service method.

Key Methods:
• String getParameter(String name): Returns the value of a request parameter
as a String.
• Enumeration<String> getParameterNames(): Returns an enumeration of all
parameter names.
• String[] getParameterValues(String name): Returns an array of String objects
containing all of the parameter values associated with a parameter name.
• Object getAttribute(String name): Returns the value of the named attribute
as an Object.
• Enumeration<String> getAttributeNames(): Returns an enumeration of the
names of all the attributes available to this request.

4. HttpServletRequest
The HttpServletRequest interface extends the ServletRequest interface to provide
request information for HTTP servlets.

Key Methods:
• String getHeader(String name): Returns the value of the specified request
header as a String.
• Enumeration<String> getHeaderNames(): Returns an enumeration of all the
header names.
• HttpSession getSession(): Returns the current session associated with this
request.
• String getMethod(): Returns the name of the HTTP method with which this
request was made (GET, POST, etc.).
• String getRequestURI(): Returns the part of this request's URL from the
protocol name up to the query string.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

5. ServletResponse
The ServletResponse interface defines an object to assist a servlet in sending a
response to the client.

Key Methods
• PrintWriter getWriter(): Returns a PrintWriter object that can send character
text to the client.
• ServletOutputStream getOutputStream(): Returns a ServletOutputStream
object that can send binary data to the client.
• void setContentType(String type): Sets the content type of the response
being sent to the client.

6. HttpServletResponse
The HttpServletResponse interface extends the ServletResponse interface to
provide HTTP-specific functionality in sending a response.

Key Methods
• void addCookie(Cookie cookie): Adds the specified cookie to the response.
• void sendRedirect(String location): Sends a temporary redirect response to
the client using the specified redirect location URL.
• void setStatus(int sc): Sets the status code for this response.
• void setHeader(String name, String value): Sets a response header with the
given name and value.
• void setContentLength(int len): Sets the length of the response content.

7. ServletConfig
The ServletConfig interface provides servlet configuration information to a servlet.
The servlet container passes a ServletConfig object to the init method of a servlet.

Key Methods
• String getServletName(): Returns the name of the servlet instance.
• ServletContext getServletContext(): Returns a reference to the
ServletContext in which the servlet is executing.
• String getInitParameter(String name): Returns a String containing the value
of the named initialization parameter.
• Enumeration<String> getInitParameterNames(): Returns an enumeration of
the names of the servlet's initialization parameters.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

8. ServletContext
The ServletContext interface defines a set of methods that a servlet uses to
communicate with its servlet container, such as getting the MIME type of a file,
dispatching requests, or writing to a log file.

Key Methods
• String getRealPath(String path): Returns the real path corresponding to the
given virtual path.
• RequestDispatcher getRequestDispatcher(String path): Returns the
RequestDispatcher object that acts as a wrapper for the resource located at
the given path.
• void log(String msg): Writes the specified message to a servlet log file.
• String getInitParameter(String name): Returns the value of the named
context-wide initialization parameter.
• Enumeration<String> getInitParameterNames(): Returns an enumeration of
the context-wide initialization parameter names.

These interfaces provide the fundamental building blocks for creating and managing
servlets in a web application, enabling developers to handle client requests and responses
efficiently while maintaining a robust and scalable architecture.

java.io.PrintWriter
• If we talk about our previous web project, we were not getting anything over our
servlet web page so to write anything over servlet, PrintWriter class is used.
• The PrintWriter class in servlets is used to send character text to the client, which
is typically an HTML page displayed in a web browser.
• This class is part of the java.io package and is obtained from the
HttpServletResponse object in a servlet.

Key Points about PrintWriter in Servlets


▪ Obtaining a PrintWriter Object: To get a PrintWriter object, you use the
getWriter() method of the HttpServletResponse object.
▪ Usage:The PrintWriter object is used to write response data, such as HTML
content, to the client.
▪ Content Type: It's important to set the content type of the response before
writing any data to the PrintWriter.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Example : Creating Servlet using Servlet interface & PrintWriter

FirstServlet.java
package com.java.student;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class FirstServlet implements Servlet
{
@Override
public void destroy() {
System.out.println("Servlet Destroyed");
}
@Override
public ServletConfig getServletConfig() {
return null;
}
@Override
public String getServletInfo() {
return null;
}
@Override
public void init(ServletConfig arg0) throws ServletException {
System.out.println("Servlet initialized");
}
@Override
public void service(ServletRequest arg0, ServletResponse arg1) throws
ServletException, IOException {
System.out.println("start servicing...");
arg1.setContentType("text/html");
PrintWriter pw=arg1.getWriter();
pw.write("This is my servlet page");
}}

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID"
version="4.0">
<display-name>firstservlet</display-name>

<!-- servlet declaration -->


<servlet>
<servlet-name>first</servlet-name>
<servlet-class>com.java.student.FirstServlet</servlet-class>
</servlet>

<!-- servlet mapping -->


<servlet-mapping>
<servlet-name>first</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
</web-app>

Example : Navigate to servlet using html page

index.html
<!DOCTYPE html>
<html>
<head><meta charset="ISO-8859-1"><title>Insert title here</title></head>
<body>
<h1> Servlet project</h1>
<br>
<a href="test">go to servlet page</a>
</body>
</html>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

FirstServlet.java
package com.java.student;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class FirstServlet implements Servlet{


@Override
public void destroy() {
System.out.println("Servlet Destroyed");
}
@Override
public ServletConfig getServletConfig() {
return null;
}
@Override
public String getServletInfo() {
return null;
}
@Override
public void init(ServletConfig arg0) throws ServletException {
System.out.println("Servlet initialized");
}
@Override
public void service(ServletRequest arg0, ServletResponse arg1) throws
ServletException, IOException {
System.out.println("start servicing...");
arg1.setContentType("text/html");
PrintWriter pw=arg1.getWriter();
pw.write("This is my servlet page");
pw.write("<br>");
pw.write("<a href=\"index.html\">Go to Index.html page</a>");
} }

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID"
version="4.0">
<display-name>firstservlet</display-name>

<!-- servlet declaration -->


<servlet>
<servlet-name>first</servlet-name>
<servlet-class>com.java.student.FirstServlet</servlet-class>
</servlet>

<!-- servlet mapping -->


<servlet-mapping>
<servlet-name>first</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

If you want to execute or open your servlet as the home page or welcome page, then
mention the servlet url inside the <welcome-file> of the web.xml file

Example : open servlet as the home page or welcome page

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID"
version="4.0">
<display-name>firstservlet</display-name>

<!-- servlet declaration -->


<servlet>
<servlet-name>first</servlet-name>
<servlet-class>com.java.student.FirstServlet</servlet-class>
</servlet>

<!-- servlet mapping -->


<servlet-mapping>
<servlet-name>first</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>

<welcome-file-list>
<welcome-file>test</welcome-file>
</welcome-file-list>
</web-app>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Example : Creating servlet using GenericServlet

Note : In the servlet, you only need to implement the body of service() method.

Hello.java
package com.mps.student;

import java.io.IOException;
import javax.servlet.GenericServlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class Hello extends GenericServlet{


public void init(ServletConfig arg0) throws ServletException {
System.out.println("Servlet initialized");
}
@Override
public void service(ServletRequest arg0, ServletResponse arg1) throws
ServletException, IOException {
arg1.setContentType("text/html");
arg1.getWriter().write("<h1>this is my servlet page</h1>");
}
}

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID"
version="4.0">
<display-name>firstservlet</display-name>

<!-- servlet declaration -->


<servlet>
<servlet-name>first</servlet-name>
<servlet-class>com.mps.student.Hello</servlet-class>
</servlet>

<!-- servlet mapping -->


<servlet-mapping>
<servlet-name>first</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>

<welcome-file-list>
<welcome-file>test</welcome-file>
</welcome-file-list>
</web-app>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

If you want to transmit or process the http data, then you need to use the
javax.servlet.http.HttpServlet abstract class.

Let’s understand the flow, how it works


1. Client sends the request (http request) to the server.
2. The HttpServletRequest object is delivered to the web component.
3. The web components interact with the database to execute queries.
4. The web components interact with the java beans to generate dynamic queries or
to perform operations.
5. The web component generates the response in HttpServletResponse Object.
6. The web server converts the HttpServletResponse into Http response and sends it
to the client.

Example : Create servlet using javax.servlet.http.HttpServlet abstract class

MyServlet.java
package com.example.java;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

public class MyServlet extends HttpServlet {


@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/html");
PrintWriter out=resp.getWriter();
out.write("Hello students");
}
}

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID"
version="4.0">
<display-name>secondpro</display-name>
<servlet>
<servlet-name>servlet</servlet-name>
<servlet-class>com.example.java.MyServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>servlet</servlet-name>
<url-pattern>/first</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>

</welcome-file-list>
</web-app>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Example : Process form data using doGet method of HttpServlet

index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="first" method="get">
Username : <input type="text" name="username">
<br>
Password : <input type="password" name="password">
<br>
<input type="submit" value="submit">
</form>
</body>
</html>

MyServlet.java
package com.example.java;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyServlet extends HttpServlet {
String username, password;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

resp.setContentType("text/html");
username=req.getParameter("username");
password=req.getParameter("password");
PrintWriter out=resp.getWriter();
if(username.equalsIgnoreCase("kapil") &&
password.equalsIgnoreCase("123"))
out.write("Hello "+username);
else
out.write("unauthorised access");
}
}

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID"
version="4.0">
<display-name>secondpro</display-name>
<servlet>
<servlet-name>servlet</servlet-name>
<servlet-class>com.example.java.MyServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>servlet</servlet-name>
<url-pattern>/first</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>

</welcome-file-list>
</web-app>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Example : Process form data using doPost method of HttpServlet

index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="first" method="post">
Username : <input type="text" name="username"> <br>
Password : <input type="password" name="password"> <br>
<input type="submit" value="submit">
</form>
</body>
</html>

MyServlet.java
package com.example.java;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyServlet extends HttpServlet {
String username, password;
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/html");

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

username=req.getParameter("username");
password=req.getParameter("password");
PrintWriter out=resp.getWriter();
if(username.equalsIgnoreCase("kapil") &&
password.equalsIgnoreCase("123"))
out.write("Hello "+username);
else
out.write("unauthorised access");
}
}

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID"
version="4.0">
<display-name>secondpro</display-name>
<servlet>
<servlet-name>servlet</servlet-name>
<servlet-class>com.example.java.MyServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>servlet</servlet-name>
<url-pattern>/first</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>

</welcome-file-list>
</web-app>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Another Example : Process form data using doPost method of HttpServlet

web.xml
Remains Same

index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="first" method="post">
<table>
<tr>
<td>username</td>
<td><input type="text" name="username" placeholder="enter
username"></td>
</tr>
<tr>
<td>City Name</td>
<td><select name="city">
<option value="delhi">Delhi</option>
<option value="banglore">Banglore</option>
<option value="mumbai">Mumbai</option>
<option value="chennai">Chennai</option>
</select></td>
</tr>
<tr>
<td><input type="submit" value="enter"></td>
<td><input type="reset" value="clear"></td>
</tr>
</table>
</form>
</body>
</html>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

MyServlet.java

package com.example.java;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyServlet extends HttpServlet {


String username, city;

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {

resp.setContentType("text/html");
username=req.getParameter("username");
city=req.getParameter("city");
PrintWriter out=resp.getWriter();

out.write("Hello "+username);
out.write("<br>");
out.write("Your city name is "+city);

}
}

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Best Training Institute
for Graduates
with
Live Online & Offline Classes Available

Join us for Better Career and Job Guarantee

Full Stack Web Development


Top Edge (MERN Stack) HTML, CSS, JavaScript, ES,
Git, ReactJS, Node, Express, MySQL & MongoDB

Training Full Stack Engineer


Java, JavaScript, ReactJS, Spring, SpringBoot
Hibernate, Linux, AWS, Git, DevOps & Jira

Programs Digital Marketing


Social Media, Website Design, SEO,
Google Ads, Freelancing & Many More

Guaranteed Package (In Writing)


▪ 3-5 Lakhs (With 6 Months Training Programs)
▪ 6-8 Lakhs (With 12 Months Training Programs)
▪ 10 Lakhs+ (With 2 Years Training Programs)

Amenities
▪ Digital Notes ▪ Working Experience
▪ Live Training Sessions ▪ Job Recommendations
▪ Project Assistance ▪ Professional Development
▪ Interview Preparation ▪ Digital Resume & Portfolio

LEARN-2-EARN LABS TRAINING INSTITUTE


Anna Icon Complex, near Kargil Petrol Pump, Sikandra-Bodla Road, Sikandra, Agra
Website : www.LearntoearnLabs.com
Call : 91-9548868337 / +91-9837705705
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Java Database Connectivity (JDBC) using Servlet


• Java Servlets are Java classes that extend the capabilities of servers hosting
applications accessed via a request-response programming model. They are
commonly used to create dynamic web content.
• While JDBC is a Java API that provides a standard way to connect to and interact
with relational databases. It allows developers to execute SQL queries, retrieve
results, and perform database updates.
• Java Database Connectivity (JDBC) and Java Servlets are essential components of
Java Enterprise Edition (Java EE) for building web-based applications that interact
with databases.
• JDBC allows servlets to interact with databases to store and retrieve data
dynamically. Understanding the lifecycle of both JDBC connections and servlets is
crucial for building robust, efficient, and scalable web applications.

Combining JDBC with Servlets

• Database Connection in Servlets


• Servlets often interact with databases to fetch or store data based on user
input.
• The database connection code can be placed in the doGet or doPost
methods, but for better design, it's advisable to use a connection pool and
a DAO (Data Access Object) pattern.

• Example Workflow
• A user submits a form (HTTP POST request) to the servlet.
• The servlet retrieves form data from the request object.
• The servlet establishes a database connection using JDBC.
• The servlet executes SQL queries based on the form data.
• The servlet processes the results and generates an HTML response.

Note: Make sure to handle exceptions and resources properly in a real-world application
to avoid resource leaks and other issues.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Prerequisites of Combining JDBC with Servlets

• Java Development Kit (JDK) installed.


• Apache Tomcat or any other servlet container.
• MySQL Database with a table and some data.
• JDBC Driver for MySQL (e.g., mysql-connector-java.jar).

Installing MySQL Server and MySQL Workbench (For Windows)

To install MySQL Server and MySQL Workbench on your system, follow the below steps.

Installing MySQL Server

1. Download the MySQL Installer


• Go to the MySQL Downloads page.
• Download the MySQL Installer for Windows (either the web or the full
version).
2. Run the Installer
• Open the downloaded .msi file to start the installation.
3. Choose Setup Type
• Choose the setup type. Typically, "Developer Default" is recommended
as it includes MySQL Server, MySQL Workbench, and other necessary
tools.
4. Check Requirements
• The installer will check for required software. Install any missing
requirements if prompted.
5. Installation Process
• Click "Execute" to download and install MySQL Server and other selected
components.
6. Configuration
• Configure MySQL Server by following the setup wizard:
• Choose the server configuration type (e.g., "Development Machine").
• Set the MySQL Root Password (remember this for later use).
• Optionally create additional MySQL user accounts.
7. Start MySQL Server
• The installer will start the MySQL Server. Ensure it starts without errors.
8. Complete Installation
• Finish the installation process.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Installing MySQL Workbench

1. Download the MySQL Workbench Installer


• Go to the MySQL Workbench Downloads page.
• Download the installer for Windows.
2. Run the Installer
• Open the downloaded .msi file to start the installation.
• Follow the installation instructions and complete the setup.

JConnector for MySQL

MySQL Connector/J, often referred to as JConnector, is the official JDBC (Java Database
Connectivity) driver for MySQL. It allows Java applications to interact with a MySQL
database using the standard JDBC API. The driver translates JDBC calls into the network
protocol used by MySQL.

Why, JConnector is Required for Creating Servlet Projects Using JDBC?

When creating Java Servlet projects that interact with a MySQL database, MySQL
Connector/J is essential for following several reasons:
1. Database Connectivity
JDBC provides a standard interface for Java applications to connect to databases.
MySQL Connector/J implements this interface for MySQL databases, allowing Java
applications, including servlets, to communicate with MySQL.
2. SQL Execution
MySQL Connector/J enables Java applications to execute SQL queries and updates
against a MySQL database. It handles the communication details and converts
JDBC method calls into SQL statements understood by the MySQL database.
3. Database Independence
By using JDBC with MySQL Connector/J, the application code remains database-
independent to a large extent. This means you can switch to another database (like
PostgreSQL, Oracle, etc.) with minimal changes to the code, assuming you use the
appropriate JDBC driver for the target database.
4. Security and Configuration
MySQL Connector/J supports secure connections, connection pooling, and various
configuration options that help optimize database access and performance in Java
Servlet projects.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Integrating MySQL Connector/J in a Java Servlet Project

Follow the below points to integrate MySQL Connector/J in a Java Servlet project:
1. Download MySQL Connector/J
Obtain the latest version of MySQL Connector/J from the MySQL Downloads page.
https://dev.mysql.com/downloads/connector/j/
2. Add Connector/J to Your Project
Extract the downloaded ZIP file and locate the mysql-connector-java-x.x.x.jar file.
Add this JAR file to your project's build path (webapp -> WEB-INF -> lib) in your
IDE (e.g., Eclipse).

Example : Establishing Java Database Connectivity using Servlet with MySQL database

1. First create a project (dynamic web project) with name ‘servletdb’.


2. Then create your servlet class to define the drivers & connections
ServletDB.java
package com.example.java;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ServletDB extends HttpServlet {


Connection connection;
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
connection=DriverManager.getConnection("jdbc:mysql://localhost:3
306/studentdb","root","android");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace(); }

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

if(connection!=null)
System.out.print("connected to database");
else
System.out.print("connection failed");
}
}

3. Configure Deployment Descriptor (web.xml file)


web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID"
version="4.0">
<display-name>servletdb</display-name>
<servlet>
<servlet-name>data</servlet-name>
<servlet-class>com.example.java.ServletDB</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>data</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
<welcome-file-list> <welcome-file>test</welcome-file> </welcome-file-list>
</web-app>

Note : To execute the above code, you need to take care about the following points.
1. You must have a database named ‘studentdb’ available at MySQL Database server.
2. The login credentials (username & password) of MySQL Database server must be
“root” & “android”.
3. To check the functionality, you need to go through the following url:
http://192.168.29.113:8080/servletdb/

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Example : Insert record in MySQL database using Servlet

1. First create a MySQL database for your project


MySQL Command
CREATE DATABASE IF NOT EXISTS studentdb;
USE studentdb;
CREATE TABLE IF NOT EXISTS record (
name VARCHAR(100),
city VARCHAR(100)
);

2. Then create an HTML page (index.html) to get the details from the user
index.html
<!DOCTYPE html>
<html>
<head><meta charset="ISO-8859-1"><title>Insert title here</title></head>
<body>
<form action="test" method="get">
<table> <tr>
<td>username</td>
<td><input type="text" name="username" placeholder="enter
username"></td>
</tr> <tr>
<td>City Name</td>
<td><select name="city">
<option value="delhi">Delhi</option>
<option value="banglore">Banglore</option>
<option value="mumbai">Mumbai</option>
<option value="chennai">Chennai</option>
</select></td>
</tr> <tr>
<td><input type="submit" value="enter"></td>
<td><input type="reset" value="clear"></td>
</tr>
</table>
</form>
</body></html>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

3. Then create a servlet class in your project to perform insert operations.


ServletDB.java
package com.example.java;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ServletDB extends HttpServlet {


Connection connection;
String name,city;
int status;
private void createConnection() {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
connection=DriverManager.getConnection("jdbc:mysql://localhost:3
306/studentdb","root","android");
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
catch (SQLException e) {
e.printStackTrace();
}
if(connection!=null)
System.out.print("connected to database");
else
System.out.print("connection failed");
}

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

private void insertValue(String name, String city)


{
try {
PreparedStatement
statement=connection.prepareStatement("insert into record value(?,?)");

statement.setString(1, name);
statement.setString(2, city);
status=statement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}

protected void doGet(HttpServletRequest request,


HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out=response.getWriter();
createConnection();
name=request.getParameter("username");
city=request.getParameter("city");
insertValue(name, city);
if(status>0)
{
out.print("data inserted successfully");
}
else {
out.print("data insertion error");
}
}
}

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

4. Configure Deployment Descriptor (web.xml file)


web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID"
version="4.0">
<display-name>servletdb</display-name>

<servlet>
<servlet-name>data</servlet-name>
<servlet-class>com.example.java.ServletDB</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>data</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

RequestDispatcher in Servlet
• RequestDispatcher is an interface provided by the Java Servlet API that allows a
request to be forwarded to another resource (such as another servlet, JSP, or HTML
file) or to include content from another resource.
• RequestDispatcher is a powerful tool in servlets that enables server-side request
forwarding and content inclusion.
• It is commonly used to achieve server-side redirection and to combine resources
within a web application.
• It helps in modularizing the web application by allowing different parts of the
request processing and response generation to be handled by different resources.
This enhances code reuse and separation of concerns in web application
development.

RequestDispather Methods

• forward(HttpServletRequest request, HttpServletResponse response)


Forwards a request from a servlet to another resource (servlet, JSP, or HTML file)
on the server. The control is transferred to the new resource, and the client is
unaware of the internal server forwarding.
RequestDispatcher dispatcher = request.getRequestDispatcher("/anotherServlet");
dispatcher.forward(request, response);

• include(HttpServletRequest request, HttpServletResponse response)


Includes the content of another resource in the response. The original request and
response are passed to the included resource, allowing it to contribute content to
the response.
RequestDispatcher dispatcher = request.getRequestDispatcher("/index.html");
dispatcher.include(request, response);

How to Obtain a RequestDispatcher

• Using ServletContext: Useful for accessing resources with absolute paths.


RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher("/absolutePathToResource");

• Using an HttpServletRequest: Useful for accessing resources with relative paths.


RequestDispatcher dispatcher =
request.getRequestDispatcher("relativePathToResource");

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

RequestDispatcher : Use-Cases

• Forwarding Requests
• Forwarding is typically used when you want to transfer control to another
servlet or JSP to handle part of the request processing.
• This is common in MVC (Model-View-Controller) architecture, where a
controller servlet forwards the request to a view (JSP) to render the output.
• Including Content
• Including is used when you want to include the content of another resource
in the response.
• This can be useful for reusable components like headers, footers, or
navigation bars in web pages.

Example : Create a simple example to demonstrate how RequestDispatcher can be used


to forward a request from one servlet to another and to include content from a HTML
page.

index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Project</title>
</head>
<body>
<h1>Institute Login Page</h1>
<form action="validate" method="get">
Username : <input type="text" name="username">
<br>
Password: <input type="password" name="password">
<br>
<input type="submit" value="submit">
<input type="reset" value="reset">
</form>
</body>
</html>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Validate.java
package com.example.java;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Validate extends HttpServlet {


String username, password;
RequestDispatcher rd;

protected void doGet(HttpServletRequest request, HttpServletResponse


response) throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out=response.getWriter();
username=request.getParameter("username");
password=request.getParameter("password");

if(username.equalsIgnoreCase("learn2earnlabs") &&
password.equalsIgnoreCase("training institute")) {
rd=request.getRequestDispatcher("homepage");
rd.forward(request, response);
}
else {
out.write("enter valid credentails");
rd=request.getRequestDispatcher("index.html");
rd.include(request, response);
}
}
}

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Homepage.java
package com.example.java;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Homepage extends HttpServlet {


protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
String username=request.getParameter("username");
out.write("Hello "+username);
}
}

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID"
version="4.0">
<display-name>rdservletdemo</display-name>
<servlet>
<servlet-name>validate</servlet-name>
<servlet-class>com.example.java.Validate</servlet-class>
</servlet>
<servlet>
<servlet-name>homepage</servlet-name>
<servlet-class>com.example.java.Homepage</servlet-class>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

</servlet>
<servlet-mapping>
<servlet-name>validate</servlet-name>
<url-pattern>/validate</url-pattern>
</servlet-mapping>

<servlet-mapping>
<servlet-name>homepage</servlet-name>
<url-pattern>/homepage</url-pattern>
</servlet-mapping>

<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Deployment Descriptor
• The Deployment Descriptor is a configuration file for a Java EE web application. It
is an XML file named web.xml located in the WEB-INF directory of a web
application.
• The deployment descriptor defines the structure and configuration of the web
application, including servlets, filters, listeners, context parameters, and other
settings.
• The deployment descriptor (web.xml) is an integral part of Java EE web
applications, serving as a configuration file that defines servlets, filters, listeners,
context parameters, security settings, and other configurations.
• It provides a standardized way to manage the various components and settings of
a web application, ensuring consistency and portability across different
environments.

Deployment Descriptor : Key Concepts

• Servlet Configuration: To declare and configure servlets, including their class


names and URL patterns.
<servlet>
<servlet-name>ExampleServlet</servlet-name>
<servlet-class>com.example.ExampleServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ExampleServlet</servlet-name>
<url-pattern>/example</url-pattern>
</servlet-mapping>

• Servlet Initialization Parameters: To define initialization parameters for servlets.


<servlet>
<servlet-name>ExampleServlet</servlet-name>
<servlet-class>com.example.ExampleServlet</servlet-class>
<init-param>
<param-name>param1</param-name>
<param-value>value1</param-value>
</init-param>
</servlet>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

• Filter Configuration: To declare filters and map them to specific servlets or URL
patterns.
<filter>
<filter-name>ExampleFilter</filter-name>
<filter-class>com.example.ExampleFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>ExampleFilter</filter-name>
<url-pattern>/example/*</url-pattern>
</filter-mapping>

• Listener Configuration: To configure listeners that respond to lifecycle events of


the servlet context, session, and request.
<listener>
<listener-class>com.example.ExampleListener</listener-class>
</listener>

• Context Parameters: To define global parameters accessible to all servlets and


JSPs in the web application.
<context-param>
<param-name>contextParam1</param-name>
<param-value>value1</param-value>
</context-param>

• Welcome Files: To specify the list of welcome files that the server should use as
the default page of a directory.
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>

• Error Pages: To define custom error pages for specific HTTP error codes or
exceptions.
<error-page>
<error-code>404</error-code> <location>/error404.jsp</location>
</error-page>
<error-page>
<exception-type>java.lang.Exception</exception-type>
<location>/error.jsp</location> </error-page>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

• Session Configuration: To configure session timeout settings.


<session-config>
<session-timeout>30</session-timeout>
</session-config>

Role of Deployment Descriptor


• Centralized Configuration:
web.xml provides a centralized location to configure web application components,
making it easier to manage.
• Portability:
Using web.xml ensures that your web application can be deployed on any Java EE-
compliant server without changing the configuration code.
• Separation of Concerns:
Configuration details are separated from the code, following the principle of
separation of concerns.
• Declarative Security:
Define security constraints, authentication methods, and authorization rules.
<security-constraint>
<web-resource-collection>
<web-resource-name>Protected Area</web-resource-name>
<url-pattern>/protected/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>admin</role-name>
</auth-constraint>
</security-constraint>
<login-config>
<auth-method>FORM</auth-method>
<form-login-config>
<form-login-page>/login.jsp</form-login-page>
<form-error-page>/loginError.jsp</form-error-page>
</form-login-config>
</login-config>
<security-role>
<role-name>admin</role-name>
</security-role>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Servlet Filter
• Servlet Filters are Java objects that can be used to perform filtering tasks on either
the request to a resource (like a servlet or JSP) or on the response from a resource,
or both. T
• Servlet Filter provide a powerful mechanism for transforming the content of HTTP
requests and responses. Filters are typically used for tasks such as logging,
authentication, input validation, and data compression.
• Servlet filters are powerful tools that allow you to intercept and manipulate
requests and responses in a web application.
• They can be used for various purposes, including logging, authentication, input
validation, and response transformation. F
• Filters are reusable, can be chained together, and can be configured either
programmatically or declaratively.
• This modular approach to request and response handling enhances the
maintainability and scalability of web applications.
• To associate filter with servlet, the url-pattern for filter must be same as the url
pattern for the respective servlet.
• filters are used to reduce the load of the servlet.

Servlet Filter : Characteristics

• Intercept Requests and Responses


• Filters can intercept HTTP requests before they reach a servlet or JSP and
modify the request or perform specific actions.
• They can also intercept HTTP responses after the servlet has processed them
but before they are sent back to the client.
• Reusable Components
Filters are reusable components. The same filter can be applied to multiple
servlets or JSPs.
• Chaining
Filters can be configured in a chain. The output of one filter can be passed
to another filter before reaching the final destination.
• Declarative and Programmatic Configuration
Filters can be configured declaratively in the web.xml file or
programmatically using annotations.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

ServletFilter Methods

Filters must implement the javax.servlet.Filter interface, which includes three methods:

• init(FilterConfig filterConfig)
Called by the servlet container to initialize the filter. This method is invoked only
once when the filter is instantiated.

public void init(FilterConfig filterConfig) throws ServletException {


// Initialization code, e.g., reading configuration parameters
}

• doFilter(ServletRequest request, ServletResponse response, FilterChain


chain)
This method is called each time a request/response pair is passed through the filter
chain due to a client request for a resource at the end of the chain.
The FilterChain object is used to invoke the next filter in the chain or the resource
at the end of the chain.

public void doFilter(ServletRequest request, ServletResponse response,


FilterChain chain)
throws IOException, ServletException {
// Pre-processing (before passing the request to the next filter or servlet)
chain.doFilter(request, response);
// Post-processing (after the request has been processed by the next filter
or servlet)
}

• destroy()
Called by the servlet container to indicate to the filter that it is being taken out of
service. This method is invoked only once when the filter is being destroyed.

public void destroy() {


// Cleanup code, e.g., releasing resources
}

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Required Interfaces

In Java Servlets, filtering is accomplished using the following interfaces:

javax.servlet.Filter
• This is the main interface for creating servlet filters.
• It contains three methods: init(), doFilter(), and destroy().
• Filters must implement this interface to intercept requests and responses.

public interface Filter {


public void init(FilterConfig filterConfig) throws ServletException;
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)
throws IOException, ServletException;
public void destroy();
}
where,
• init(FilterConfig filterConfig): Called by the servlet container to initialize the filter.
This method is invoked only once when the filter is instantiated.
• doFilter(ServletRequest request, ServletResponse response, FilterChain
chain): This method is called each time a request/response pair is passed through
the filter chain. It allows the filter to perform its filtering tasks.
• destroy(): Called by the servlet container to indicate to the filter that it is being
taken out of service. This method is invoked only once when the filter is being
destroyed.

javax.servlet.FilterConfig
• This interface provides configuration information to a filter during initialization.
• It allows filters to access initialization parameters specified in the deployment
descriptor (web.xml).

public interface FilterConfig {


public String getFilterName();
public ServletContext getServletContext();
public String getInitParameter(String name);
public Enumeration<String> getInitParameterNames();
}

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

where,
• getFilterName(): Returns the name of the filter.
• getServletContext(): Returns a reference to the ServletContext of the web
application.
• getInitParameter(String name): Returns the value of the initialization parameter
with the given name.
• getInitParameterNames(): Returns an enumeration of all the initialization
parameter names.

javax.servlet.FilterChain
• This interface represents a chain of filters.
• It provides a mechanism for invoking the next filter in the chain, or if the calling
filter is the last filter in the chain, invoking the resource at the end of the chain
(such as a servlet or JSP).

public interface FilterChain {


public void doFilter(ServletRequest request, ServletResponse response)
throws IOException, ServletException;
}
where,
• doFilter(ServletRequest request, ServletResponse response): Invokes the next
filter in the chain or, if the calling filter is the last filter in the chain, invokes the
resource at the end of the chain (such as a servlet or JSP).

All these interfaces work together to provide a mechanism for creating, configuring, and
chaining filters in Java Servlets.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Example: Create a simple project to demonstrate the usage of a servlet filter

index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="first" method="get">
<input type="submit" value="press me">
</form>
</body>
</html>

MyFilter.java
package com.example.java;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpFilter;

public class MyFilter extends HttpFilter implements Filter {

public void doFilter(ServletRequest request, ServletResponse response,


FilterChain chain) throws IOException, ServletException {

System.out.println("preprocessing");

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

chain.doFilter(request, response);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.print("postprocessing");
}

MyServlet.java
package com.example.java;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyServlet extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse


response) throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.write("Hello students");
}
}

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID"
version="4.0">
<display-name>filterex</display-name>

<servlet>
<servlet-name>first</servlet-name>
<servlet-class>com.example.java.MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>first</servlet-name>
<url-pattern>/first</url-pattern>
</servlet-mapping>

<filter>
<filter-name>test</filter-name>
<filter-class>com.example.java.MyFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>test</filter-name>
<url-pattern>/first</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Best Training Institute
for Graduates
with
Live Online & Offline Classes Available

Join us for Better Career and Job Guarantee

Full Stack Web Development


Top Edge (MERN Stack) HTML, CSS, JavaScript, ES,
Git, ReactJS, Node, Express, MySQL & MongoDB

Training Full Stack Engineer


Java, JavaScript, ReactJS, Spring, SpringBoot
Hibernate, Linux, AWS, Git, DevOps & Jira

Programs Digital Marketing


Social Media, Website Design, SEO,
Google Ads, Freelancing & Many More

Guaranteed Package (In Writing)


▪ 3-5 Lakhs (With 6 Months Training Programs)
▪ 6-8 Lakhs (With 12 Months Training Programs)
▪ 10 Lakhs+ (With 2 Years Training Programs)

Amenities
▪ Digital Notes ▪ Working Experience
▪ Live Training Sessions ▪ Job Recommendations
▪ Project Assistance ▪ Professional Development
▪ Interview Preparation ▪ Digital Resume & Portfolio

LEARN-2-EARN LABS TRAINING INSTITUTE


Anna Icon Complex, near Kargil Petrol Pump, Sikandra-Bodla Road, Sikandra, Agra
Website : www.LearntoearnLabs.com
Call : 91-9548868337 / +91-9837705705
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Session Management and Tracking in Servlets


• Session management and tracking in servlets refer to the mechanisms used to
maintain state information between multiple requests from the same client.
• This is crucial for maintaining user sessions, storing user-specific data, and
providing a personalized experience in web applications.
• Servlets provide built-in support for session management through the HttpSession
interface.
• Session is a time duration, it will start from the staring point of client
communication with server and will terminate at the ending point of client
communication with server.
• The data which we transfer from client to server through multiple number of
requests during a particular session then the data is called "state of the session".
• In general for a web application, container will prepare a request object similarly
to represent a particular used we have to prepare a separate session.
• Session management and tracking in servlets are essential for maintaining user
state and providing a personalized experience in web applications.
• By leveraging the HttpSession interface and session tracking mechanisms, servlets
can effectively manage user sessions and store session-specific data. However,
developers should be mindful of the challenges associated with session
management, such as scalability, resource consumption, and security
considerations.

Session Management and Tracking : Key Concepts

• HttpSession Interface
• The HttpSession interface provides a way to track user sessions.
• It allows servlets to store and retrieve session-specific data.
• Sessions are identified using a session ID, which is typically stored as a
cookie in the client's browser.

• Session Tracking Mechanisms


• Cookies: The session ID can be stored as a cookie in the client's browser.
This is the default mechanism used by servlet containers.
• URL Rewriting: The session ID can be appended to URLs as a query
parameter. This is useful when cookies are disabled.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

• Hidden Form Fields: The session ID can be included as a hidden form field
in HTML forms. This is less common but can be useful in certain scenarios.

• Creating and Accessing Sessions


• Sessions can be created and accessed using the getSession() method of the
HttpServletRequest object.
• If a session does not already exist, getSession() will create a new session.

• Storing and Retrieving Data


• Data can be stored in a session using the setAttribute() method and
retrieved using the getAttribute() method of the HttpSession object.

• Session Timeout
• Sessions have a configurable timeout period, after which they are
invalidated and removed.
• The timeout period can be set in the deployment descriptor (web.xml) or
programmatically using the setMaxInactiveInterval() method of the
HttpSession object.

Code Example :

@WebServlet("/example")
public class ExampleServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
// Get the session object
HttpSession session = request.getSession();

// Store data in the session


session.setAttribute("username", "learn2EarnLabs");

// Retrieve data from the session


String username = (String) session.getAttribute("username");

// Invalidate the session


session.invalidate();
}
}

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Session Management and Tracking : Benefits:

• User Identification: Sessions allow the server to identify users across multiple
requests, even if they do not provide authentication credentials with each request.
• State Management: Sessions enable the storage of user-specific data, such as
shopping cart items, user preferences, and login information.
• Personalization: Sessions facilitate the customization of web content based on
user interactions and preferences.
• Security: Session data is stored on the server, making it more secure than storing
sensitive information on the client side.

Session Management and Tracking : Challenges

• Scalability: Storing session data on the server can impact scalability, especially in
distributed environments with multiple servers.
• Resource Consumption: Sessions consume server resources, such as memory and
CPU, especially if session data is large or if sessions are not properly managed.
• Session Fixation: Improper session management can lead to security
vulnerabilities, such as session fixation attacks.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

HttpSession
• HttpSession is an interface provided by the Java Servlet API that enables the
management and tracking of user sessions.
• A session allows a server to maintain state information for a particular user across
multiple HTTP requests.
• This is crucial for applications that require user-specific data to be stored and
retrieved, such as shopping carts, user preferences, and login states.
• HttpSession is a powerful tool for managing user sessions in Java web applications.
By understanding its features, methods, and best practices, developers can
effectively maintain state and provide a seamless user experience.

HttpSession : Key Features

• Session Creation and Access


• A session is created when the server receives a request from a client that
does not have an associated session.
• Sessions can be accessed using the getSession() method of the
HttpServletRequest object.

• Session ID
• Each session is identified by a unique session ID.
• The session ID is typically stored as a cookie in the client's browser.

• Session Data Storage


• Data can be stored in a session using key-value pairs.
• The setAttribute() method is used to store data, and the getAttribute()
method is used to retrieve data.

• Session Invalidation
• Sessions can be explicitly invalidated using the invalidate() method.
• This is useful for logging out users or clearing session data.

• Session Timeout
• Sessions have a timeout period after which they are automatically
invalidated.
• The timeout period can be configured in the deployment descriptor
(web.xml) or programmatically.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

HttpSession Methods

• getId(): Returns the unique session ID.


String sessionId = session.getId();

• getCreationTime(): Returns the time when the session was created.


long creationTime = session.getCreationTime();

• getLastAccessedTime(): Returns the last time the session was accessed.


long lastAccessedTime = session.getLastAccessedTime();

• setAttribute(String name, Object value): Stores an attribute in the session.


session.setAttribute("username", "Learn2EarnLabs");

• getAttribute(String name): Retrieves an attribute from the session.


String username = (String) session.getAttribute("username");

• removeAttribute(String name): Removes an attribute from the session.


session.removeAttribute("username");

• invalidate(): Invalidates the session, removing all attributes.


session.invalidate();

• setMaxInactiveInterval(int interval): Sets the maximum interval, in seconds, that the


session will be kept open between client accesses.
session.setMaxInactiveInterval(30 * 60); // 30 minutes

• getMaxInactiveInterval(): Returns the maximum time interval, in seconds, that the


session will be kept open between client accesses.
int interval = session.getMaxInactiveInterval();

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Example : Creating and Accessing HttpSession

index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="first" method="get">
<input type="text" name="user">
<br>
<input type="text" name="rollno">
<br>
<input type="submit" value="press me"></form>
</body>
</html>

MyServlet.java
package com.example.java;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class MyServlet extends HttpServlet {


String user, rollno;

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

protected void doGet(HttpServletRequest request, HttpServletResponse


response) throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out=response.getWriter();

user=request.getParameter("user");
rollno=request.getParameter("rollno");

HttpSession session=request.getSession();
session.setAttribute("user",user);
session.setAttribute("rollno", rollno);

RequestDispatcher
rd=request.getRequestDispatcher("second.html");
rd.forward(request, response);
}
}

second.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="second" method="get">
<input type="text" name="gender">
<br>
<input type="text" name="city">
<br>
<input type="submit" value="press me"></form>
</body>
</html>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

SecondServlet.java
package com.example.java;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class SecondServlet extends HttpServlet {

String gender, city;

protected void doGet(HttpServletRequest request, HttpServletResponse


response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();

gender=request.getParameter("gender");
city=request.getParameter("city");

HttpSession session=request.getSession();

out.write("The username is "+session.getAttribute("user"));


out.write("Roll no is "+session.getAttribute("rollno"));
out.write("the gender is "+gender);
out.write("the city is "+city);
}
}

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID"
version="4.0">
<display-name>filterex</display-name>

<servlet>
<servlet-name>first</servlet-name>
<servlet-class>com.example.java.MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>first</servlet-name>
<url-pattern>/first</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>second</servlet-name>
<servlet-class>com.example.java.SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>second</servlet-name>
<url-pattern>/second</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Benefits of HttpSession

• State Management: HttpSession allows the server to maintain state information


between multiple requests from the same client.
• Data Storage: It provides a convenient way to store and retrieve user-specific data.
• Security: Session data is stored on the server, reducing the risk of client-side data
manipulation.
• Ease of Use: HttpSession is easy to use and integrates seamlessly with the Java
Servlet API.

Challenges of HttpSession

• Scalability: Maintaining sessions for a large number of users can consume


significant server resources.
• Session Clustering: In a distributed environment, managing sessions across
multiple servers can be complex.
• Timeout Management: Improper session timeout settings can lead to sessions
being invalidated too soon or lingering too long, affecting user experience and
resource utilization.
• Security: Sessions can be vulnerable to attacks such as session fixation and session
hijacking if not properly managed.

HttpSession : Best Practices

• Minimize Session Data: Store only necessary data in the session to minimize
memory usage.
• Secure Session IDs: Use secure methods to generate session IDs and transmit
them over HTTPS.
• Proper Timeout Settings: Configure appropriate session timeout settings based
on the application's requirements.
• Invalidate Sessions: Explicitly invalidate sessions when they are no longer needed
(e.g., after user logout).

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Cookies
• Cookies are small pieces of data that a server sends to the client's browser, which
are then stored and sent back to the server with subsequent requests.
• Cookies are used to remember information about the user between requests, such
as login credentials, user preferences, and tracking information.
• Cookies are a simple and effective way to manage state and user information in
web applications. By using the Cookie class in servlets, developers can create,
retrieve, and delete cookies as needed.
• Cookies can be configured with various attributes to control their behavior,
ensuring security and proper management of user data.
• In terms of programming, Cookies are usually the objects, which are used to
process or hold the data from the user at client machine or web browser so when
any user uses the application with the same client machine (web browser) then the
data would be sended to the server.
• Cookies only works until they are allowed at client machine. If cookies are disabled
then we can't process the data using cookies, in-between client and server.
• All the cookies object should be added to the responses of each servlet for which
we want to manage cookies then with the help of request, we will get the cookies
to the next servlet or page.

Cookies : Key Characteristics

• Name-Value Pair: Each cookie consists of a name-value pair, where both the name
and value are strings.
• Storage: Cookies are stored on the client's browser and can have attributes like
expiration time, domain, and path.
• Session and Persistent Cookies:
• Session Cookies: These cookies are temporary and are deleted when the
browser is closed.
• Persistent Cookies: These cookies have an expiration date and are stored on
the client's disk until they expire or are deleted by the user.
• Security: Cookies can be secured by setting the HttpOnly and Secure flags.
• The HttpOnly flag prevents access to cookies via JavaScript, mitigating the
risk of XSS attacks.
• The Secure flag ensures cookies are sent over HTTPS only.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Creating and Managing Cookies in Servlet

• Creating a Cookie

To create a cookie in a servlet, you can use the javax.servlet.http.Cookie class and
then add it to the response.

Code Example:

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/createCookie")
public class CreateCookieServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws IOException {

// Create a cookie with a name and a value


Cookie cookie = new Cookie("username", "Learn2EarnLabs");

// Set the maximum age of the cookie in seconds (optional)


cookie.setMaxAge(60 * 60 * 24); // 1 day

// Add the cookie to the response


response.addCookie(cookie);

// Respond to the client


response.getWriter().println("Cookie created successfully");
}
}

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

• Retrieving Cookies

To retrieve cookies sent by the client, you can use the getCookies() method of the
HttpServletRequest object.

Code Example

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/getCookies")
public class GetCookiesServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws IOException {
// Get an array of Cookies from the request
Cookie[] cookies = request.getCookies();

// Check if any cookies are present


if (cookies != null) {
for (Cookie cookie : cookies) {
// Retrieve cookie name and value
String name = cookie.getName();
String value = cookie.getValue();

// Write cookie details to the response


response.getWriter().println("Cookie Name: " + name + ", Cookie
Value: " + value);
}
} else {
response.getWriter().println("No cookies found");
}
}
}

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

• Deleting Cookies
To delete a cookie, you need to set its maximum age to zero and add it to the
response.

Code Example:

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/deleteCookie")
public class DeleteCookieServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws IOException {
// Create a cookie with the same name as the cookie you want to delete
Cookie cookie = new Cookie("username", "");

// Set the maximum age to 0 to delete the cookie


cookie.setMaxAge(0);

// Add the cookie to the response


response.addCookie(cookie);

// Respond to the client


response.getWriter().println("Cookie deleted successfully");
}
}

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Cookie Attributes

• Max Age
cookie.setMaxAge(int expiry): Sets the maximum age in seconds. If set to
zero, the cookie is deleted. If negative, the cookie is not stored persistently
and will be deleted when the browser exits.
• Path
cookie.setPath(String uri): Specifies the path within the site to which the
cookie applies.
• Domain
cookie.setDomain(String domain): Specifies the domain to which the cookie
applies.
• Secure
cookie.setSecure(boolean flag): Indicates that the cookie should only be
sent over secure protocols like HTTPS.
• HttpOnly
cookie.setHttpOnly(boolean isHttpOnly): If set to true, the cookie is not
accessible through client-side scripts.

Example: Create a simple project demonstrating the use of cookies in servlets.

index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="first" method="get">
<input type="text" name="user">
<br>
<input type="text" name="rollno">
<br>
<input type="submit" value="press me"></form>
</body>
</html>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

MyServlet.java
package com.example.java;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class MyServlet extends HttpServlet {


String user, rollno;
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out=response.getWriter();

user=request.getParameter("user");
rollno=request.getParameter("rollno");

Cookie cookie1=new Cookie("user", user);


Cookie cookie2=new Cookie("rollno", rollno);

response.addCookie(cookie1);
response.addCookie(cookie2);

RequestDispatcher rd=request.getRequestDispatcher("second.html");
rd.forward(request, response);
}
}

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

second.html
<!DOCTYPE html>
<html>
<head><meta charset="ISO-8859-1"><title>Insert title here</title></head>
<body>
<form action="second" method="get">
<input type="text" name="gender">
<br>
<input type="text" name="city">
<br>
<input type="submit" value="press me"></form>
</body>
</html>

SecondServlet.java
package com.example.java;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class SecondServlet extends HttpServlet {


String user, rollno, gender, city;
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();

gender=request.getParameter("gender");
city=request.getParameter("city");
Cookie cookie[]=request.getCookies();

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

user=cookie[0].getValue();
rollno=cookie[1].getValue();
out.write("The username is "+user);
out.write("Roll no is "+rollno);
out.write("the gender is "+gender);
out.write("the city is "+city);
}
}

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID"
version="4.0">
<display-name>filterex</display-name>
<servlet>
<servlet-name>first</servlet-name>
<servlet-class>com.example.java.MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>first</servlet-name>
<url-pattern>/first</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>second</servlet-name>
<servlet-class>com.example.java.SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>second</servlet-name>
<url-pattern>/second</url-pattern>
</servlet-mapping>
<welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-
file-list>
</web-app>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

URL Rewriting
• When using HttpSession (a session tracking mechanism), the session ID is
automatically created in the form of a cookie when the HttpSession object is
created. This session ID is transferred from the server to the client and from the
client to the server along with the response and request, respectively.
• In session tracking, we can identify user-specific HttpSession objects based on the
session ID. Therefore, if cookies are disabled in the client's browser, the HttpSession
tracking mechanism will not function properly.
• As we already discussed, using cookies cannot secure user data on the client
machine or web browser. To overcome this issue, URL rewriting is used.
• With URL rewriting, we do not maintain the client conversation on the client
machine. Instead, we maintain the client conversation in the form of an HttpSession
object on the server side, thereby providing security.
• URL rewriting does not depend on cookies.
• With URL rewriting, the URL must be rewritten with the session ID value in every
subsequent page/form (HTML/servlet/JSP).
• URL Rewriting is a technique used for session tracking in web applications. When
cookies are disabled or not supported by the client, URL rewriting can be used to
maintain the session by appending the session ID to the URL of each request. This
ensures that the session information is passed back to the server with each
subsequent request.
• URL Rewriting is a useful technique for maintaining sessions in environments where
cookies are not available or reliable.
• While it has its use cases, developers need to be aware of its drawbacks, particularly
regarding security and user experience. Combining URL rewriting with other
session management techniques can help mitigate some of these issues.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

How URL Rewriting Works

• Session Management
• When a client sends a request to the server, and a session is created, the
server generates a unique session ID.
• This session ID can be appended to the URL of each response sent back to
the client.
• For each subsequent request from the client, the session ID included in the
URL allows the server to recognize the session.
• Appending Session ID
• The session ID is appended to the URL as a query parameter.
• The servlet container provides methods to handle URL rewriting, such as
HttpServletResponse.encodeURL(String url) and
HttpServletResponse.encodeRedirectURL(String url).

Drawbacks of URL Rewriting

• URL Complexity
• URLs become longer and more complex with the appended session ID,
which can make them harder to read and manage.
• Security Risks
• Session IDs in URLs can be exposed through browser history, bookmarks, or
logs.
• If a URL containing a session ID is shared or intercepted, it can lead to
session hijacking.
• Search Engine Issues
• URLs with session IDs can create duplicate content issues for search engines,
potentially impacting SEO.
• User Experience
• Users may find rewritten URLs less user-friendly.
• Users might inadvertently share URLs containing session IDs, leading to
unintended session sharing.
• Performance Overhead
• Appending and processing session IDs in URLs adds a slight performance
overhead compared to using cookies.
URL Rewriting requires dynamically generated forms, it will not execute its functionality
with static forms.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

URL Rewriting : Use Cases

• Session Tracking Without Cookies


• Useful when cookies are disabled or not supported by the client's browser.
• Ensures session continuity by passing session ID through URLs.
• Secure Environments
• In some security-sensitive applications, URL rewriting can be used in
combination with other session management techniques for added security.
• State Management
• Can be used in applications where maintaining state across multiple pages
is necessary without relying on cookies.

Example: Create a simple project demonstrating the use of URL Rewriting in servlets.

index.html
<!DOCTYPE html>
<html>
<head><meta charset="ISO-8859-1"><title>Insert title here</title></head>
<body>
<form action="first" method="get">
<input type="text" name="user"><br>
<input type="text" name="rollno"><br>
<input type="submit" value="press me"></form>
</body>
</html>

MyServlet.java
package com.example.java;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class MyServlet extends HttpServlet {


String user, rollno;
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
user=request.getParameter("user");
rollno=request.getParameter("rollno");
out.write("the user name is "+user+" & roll no is "+rollno);
out.write("<br>");
out.println("<a
href='second?user="+user+"&rollno="+rollno+"'>go to next servlet</a>");
}
}

SecondServlet.java
package com.example.java;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class SecondServlet extends HttpServlet {


String user, rollno;
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

user=request.getParameter("user");
rollno=request.getParameter("rollno");
out.write("Now, The username is "+user);
out.write("<br>Roll no is "+rollno);
}
}

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID"
version="4.0">
<display-name>filterex</display-name>
<servlet>
<servlet-name>first</servlet-name>
<servlet-class>com.example.java.MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>first</servlet-name>
<url-pattern>/first</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>second</servlet-name>
<servlet-class>com.example.java.SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>second</servlet-name>
<url-pattern>/second</url-pattern>
</servlet-mapping>
<welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-
file-list>
</web-app>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Hidden Form Fields in Servlets


• Hidden form fields are a method used to maintain state information between client
requests in web applications & are generally used for state management.
• They are a part of an HTML form and are not visible to the user.
• Hidden form fields are used to store data that needs to be sent back to the server
with subsequent requests without displaying it on the webpage.
• The hidden form field session tracking mechanism is not an official session tracking
mechanism from servlets. Its creation and usage depend entirely on the developer.
• In the hidden form field session tracking mechanism, for each request, we will pick
up all the request parameters and generate dynamic forms.
• In these generated dynamic forms, we must maintain the current request
parameters' data in the form of hidden fields.

How Hidden Form Fields Work

• HTML Form Integration


• Hidden form fields are included in an HTML form using the <input
type="hidden"> tag.
• These fields have a name attribute to identify the data and a value attribute
to store the data.
• Data Storage
• When the form is submitted, the data in hidden fields is sent to the server
along with other form data.
• The server can retrieve this data using standard methods to process the
request.

Use Cases of Hidden Form Fields

• Session Tracking
• Maintain session state in applications where cookies are not used or
supported.
• Store session IDs or user-specific data to be sent back with subsequent
requests.
• Passing Data Between Pages
• Transfer data between multiple pages/forms in a multi-step process.
• Useful in shopping cart applications to pass item details, quantities, and
other related information.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

• Storing Metadata
• Store metadata or additional information required for form processing
without displaying it to the user.
• Security Tokens
• Embed security tokens in forms to prevent CSRF (Cross-Site Request
Forgery) attacks.

Drawbacks of Hidden Form Fields

• Visibility in Source Code


• Although not visible on the rendered webpage, hidden fields are visible in
the page source code.
• Users can view and modify hidden field values using browser developer
tools.
• Security Risks
• Sensitive information should not be stored in hidden fields, as it can be
easily tampered with by users.
• Hidden fields should not be relied upon for storing critical or secure data.
• Data Integrity
• Since users can manipulate hidden field values, the server must validate and
sanitize all received data to ensure integrity.
• Limited Data Handling
• Hidden fields are limited to simple text data and cannot handle complex
data structures effectively.
• Increased Complexity
• Managing multiple hidden fields across different forms and pages can
increase the complexity of the application.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Example: Create a simple project demonstrating the use of Hidden Form Fields in servlets.

index.html
<!DOCTYPE html>
<html>
<head><meta charset="ISO-8859-1"><title>Insert title here</title></head>
<body>
<form action="first" method="get">
<input type="text" name="user"><br>
<input type="text" name="rollno"><br>
<input type="submit" value="press me"></form>
</body>
</html>

MyServlet.java
package com.example.java;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class MyServlet extends HttpServlet {
String user, rollno;
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out=response.getWriter();
user=request.getParameter("user");
rollno=request.getParameter("rollno");

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

String status="blocked";
out.write("the user name is "+user+" & roll no is "+rollno);
out.write("<br>");
out.write("<!DOCTYPE html>\r\n"
+ "<html>\r\n"
+ "<head>\r\n"
+ "<meta charset=\"ISO-8859-1\">\r\n"
+ "<title>Insert title here</title>\r\n"
+ "</head>\r\n"
+ "<body>\r\n"
+ "<form action='second'>\r\n"
+ "<input type='hidden' name='username'
value='"+user+"'>"
+ "<input type='hidden' name='rollnumber'
value='"+rollno+"'>"
+ "<input type='hidden' name='status'
value='"+status+"'>"
+ "<input type='submit' value='pressme'>"
+ "</form>"
+ "</body>\r\n"
+ "</html>");
}
}

SecondServlet.java
package com.example.java;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

public class SecondServlet extends HttpServlet {

String user, rollno, status;


protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
user=request.getParameter("username");
rollno=request.getParameter("rollnumber");
status=request.getParameter("status");
out.write("Now, The username is "+user);
out.write("<br>Roll no is "+rollno);
out.write("you are now : "+status);
}
}

web.xml
Remains Same as previous

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Best Training Institute
for Graduates
with
Live Online & Offline Classes Available

Join us for Better Career and Job Guarantee

Full Stack Web Development


Top Edge (MERN Stack) HTML, CSS, JavaScript, ES,
Git, ReactJS, Node, Express, MySQL & MongoDB

Training Full Stack Engineer


Java, JavaScript, ReactJS, Spring, SpringBoot
Hibernate, Linux, AWS, Git, DevOps & Jira

Programs Digital Marketing


Social Media, Website Design, SEO,
Google Ads, Freelancing & Many More

Guaranteed Package (In Writing)


▪ 3-5 Lakhs (With 6 Months Training Programs)
▪ 6-8 Lakhs (With 12 Months Training Programs)
▪ 10 Lakhs+ (With 2 Years Training Programs)

Amenities
▪ Digital Notes ▪ Working Experience
▪ Live Training Sessions ▪ Job Recommendations
▪ Project Assistance ▪ Professional Development
▪ Interview Preparation ▪ Digital Resume & Portfolio

LEARN-2-EARN LABS TRAINING INSTITUTE


Anna Icon Complex, near Kargil Petrol Pump, Sikandra-Bodla Road, Sikandra, Agra
Website : www.LearntoearnLabs.com
Call : 91-9548868337 / +91-9837705705
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Annotations in Servlet
• Annotations in servlets provide a way to configure and deploy servlets without the
need for a web.xml configuration file.
• They simplify the development process by allowing metadata to be directly
included in the Java source code.
• Annotations in servlets were introduced in Servlet 3.0, which is part of the Java EE
6 specification.

Types of Servlet Annotations


• @WebServlet: Used to declare a servlet.
• @WebInitParam: Used to specify initialization parameters for a servlet.
• @WebFilter: Used to define a filter.
• @WebListener: Used to declare a listener.
• @MultipartConfig: Used to specify configuration settings for file upload in a
servlet.

Examples of Servlet Annotations

@WebServlet
The @WebServlet annotation is used to declare a servlet and map it to a URL pattern.

Code Example:

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "ExampleServlet", urlPatterns = {"/example"})


public class ExampleServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
response.getWriter().println("Hello, World!");
}
}

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

@WebInitParam
The @WebInitParam annotation is used to specify initialization parameters for a servlet.

Code Example:

import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(
name = "InitParamServlet",
urlPatterns = {"/initParam"},
initParams = {
@WebInitParam(name = "param1", value = "value1"),
@WebInitParam(name = "param2", value = "value2")
}
)
public class InitParamServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
String param1 = getServletConfig().getInitParameter("param1");
String param2 = getServletConfig().getInitParameter("param2");
response.getWriter().println("Param1: " + param1);
response.getWriter().println("Param2: " + param2);
}
}

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

@WebFilter
The @WebFilter annotation is used to define a filter.

Code Example:

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

@WebFilter(filterName = "ExampleFilter", urlPatterns = {"/example"})


public class ExampleFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {}

@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
// Pre-processing
response.getWriter().println("Filter is invoked before");

chain.doFilter(request, response);

// Post-processing
response.getWriter().println("Filter is invoked after");
}

@Override
public void destroy() {}
}

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

@WebListener
The @WebListener annotation is used to declare a listener.

Code Example:

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

@WebListener
public class ExampleListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
System.out.println("Context initialized");
}

@Override
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("Context destroyed");
}
}

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

@MultipartConfig
The @MultipartConfig annotation is used to specify configuration settings for file upload
in a servlet.

Code Example:

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;

@WebServlet(name = "UploadServlet", urlPatterns = {"/upload"})


@MultipartConfig
public class UploadServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
Part filePart = request.getPart("file");
String fileName = filePart.getSubmittedFileName();
filePart.write("/uploads/" + fileName);
response.getWriter().println("File uploaded successfully");
}
}

All these annotations significantly reduce the need for boilerplate code and make servlet
configuration more straightforward and less error-prone.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Servlet Annotations : Additional Factors

1. Flexibility and Ease of Use


• Servlet annotations allow for more flexible and easier configuration
compared to the traditional web.xml file.
• Developers can quickly add or modify configurations directly in the code,
leading to a more intuitive development process.

2. Deployment Descriptor Overrides


• Even when using annotations, it is possible to override the annotation
configurations using the web.xml deployment descriptor.
• This provides a way to maintain backward compatibility and allows for more
complex configurations that might be easier to manage in web.xml.

3. Annotation Processing Order


• Annotations are processed during the deployment phase of the application.
• The order of processing annotations can be significant, especially when
multiple filters and listeners are involved.

4. Meta-Annotations
• Servlet annotations can use meta-annotations to provide additional context
or configuration.
• For example, annotations like @WebServlet, @WebFilter, and
@WebListener can include meta-annotations to specify initialization
parameters, description, display name, and more.

5. Combining Multiple Annotations


• It is possible to combine multiple servlet annotations on a single servlet
class.
• For example, you can use @WebServlet and @MultipartConfig together on
a file upload servlet to handle both servlet mappings and multipart
configuration.

6. Automatic Scanning
• Servlet annotations allow the servlet container to automatically scan and
register components without requiring manual listing in the web.xml file.
• This reduces the risk of configuration errors and makes it easier to manage
large applications.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

7. Integration with Dependency Injection


• Annotations can integrate seamlessly with dependency injection
frameworks (like CDI - Contexts and Dependency Injection).
• This enables the use of annotations for injecting resources, services, and
other dependencies directly into servlets, filters, and listeners.

Code Example : Combining Annotations

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;

@WebServlet(
name = "AdvancedServlet",
urlPatterns = {"/advanced"},
initParams = {
@WebInitParam(name = "param1", value = "value1") })

@MultipartConfig
public class AdvancedServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
String param1 = getServletConfig().getInitParameter("param1");
Part filePart = request.getPart("file");
String fileName = filePart.getSubmittedFileName();
filePart.write("/uploads/" + fileName);
response.getWriter().println("Param1: " + param1);
response.getWriter().println("File uploaded successfully");
}
}

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Code Example : Using Meta-Annotations

import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@WebServlet(
name = "CustomServlet",
urlPatterns = {"/custom"},
initParams = {
@WebInitParam(name = "customParam", value = "customValue")
}
)
public @interface CustomServlet {
String description() default "Custom Servlet Description";
}

@CustomServlet
public class MyCustomServlet extends HttpServlet {
// Servlet implementation
}

Servlet Annotations : Additional Considerations

• Security: Annotations can help manage security configurations, such as defining


security roles and constraints directly in the code.
• Portability: Annotations enhance portability across different servlet containers by
reducing reliance on container-specific deployment descriptors.
• Version Compatibility: Always ensure that the servlet container being used
supports the version of the servlet specification that includes annotations (Servlet
3.0 and above).

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Servlet Listener
• Servlet Listeners are special interfaces in Java Servlet API that allow developers to
receive notifications about changes and events in a web application.
• Servlet Listeners enable actions to be taken in response to these events, enhancing
the application's responsiveness and interactivity.
• Servlet listeners provide a way to execute specific code in response to various
significant events in the lifecycle of a web application, aiding in tasks such as
resource management, logging, and application monitoring.
• Servlet Listeners provide a powerful mechanism to react to various events in a web
application, enabling developers to build robust, efficient, and maintainable
applications.
• Servlet API provides listener interfaces that we can implement & configure to listen
to an event and do certain operations.
• Event is an occurrence of something, in web application world like initialization of
an application, destroying an application, client request, session management
(creation/destroy), attribute processing during session, etc.

Servlet Listeners : Types

There are several types of listeners, each designed to listen for different kinds of events:
• ServletContextListener: Monitors lifecycle events of the ServletContext, such as
when the context is initialized or destroyed.
Methods:
contextInitialized(ServletContextEvent sce): Called when the web
application is starting up.
contextDestroyed(ServletContextEvent sce): Called when the web
application is shutting down.
• ServletContextAttributeListener: Monitors changes to attributes in the
ServletContext.
Methods:
attributeAdded(ServletContextAttributeEvent scae): Called when an
attribute is added.
attributeRemoved(ServletContextAttributeEvent scae): Called when
an attribute is removed.
attributeReplaced(ServletContextAttributeEvent scae): Called when
an attribute is replaced.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

• HttpSessionListener: Monitors lifecycle events of HttpSession objects, such as


when sessions are created or destroyed.
Methods:
sessionCreated(HttpSessionEvent se): Called when a session is
created.
sessionDestroyed(HttpSessionEvent se): Called when a session is
invalidated or timed out.

• HttpSessionAttributeListener: Monitors changes to attributes in HttpSession


objects.
Methods:
attributeAdded(HttpSessionBindingEvent se): Called when an
attribute is added.
attributeRemoved(HttpSessionBindingEvent se): Called when an
attribute is removed.
attributeReplaced(HttpSessionBindingEvent se): Called when an
attribute is replaced.

• HttpSessionBindingListener: Monitors the binding and unbinding of objects to


and from a session.
Methods:
valueBound(HttpSessionBindingEvent event): Called when an object
is added to a session.
valueUnbound(HttpSessionBindingEvent event): Called when an
object is removed from a session.

• HttpSessionActivationListener: Monitors the passivation and activation of


session objects, which occur when a session is moved from one JVM to another.
Methods:
sessionWillPassivate(HttpSessionEvent se): Called before the session
is passivated.
sessionDidActivate(HttpSessionEvent se): Called after the session is
activated.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

• ServletRequestListener: Monitors lifecycle events of ServletRequest objects.


Methods:
requestInitialized(ServletRequestEvent sre): Called when a request is
initialized.
requestDestroyed(ServletRequestEvent sre): Called when a request is
destroyed.

• ServletRequestAttributeListener: Monitors changes to attributes in


ServletRequest objects.
Methods:
attributeAdded(ServletRequestAttributeEvent srae): Called when an
attribute is added.
attributeRemoved(ServletRequestAttributeEvent srae): Called when
an attribute is removed.
attributeReplaced(ServletRequestAttributeEvent srae): Called when
an attribute is replaced.

Servlet Listeners : Use Case & Benefits

Servlet Listeners offer several use cases and benefits that can significantly enhance the
functionality, performance, and maintainability of a web application.

Here are some of the key use cases and benefits:

Use Cases

• Resource Management
Initialization and Cleanup: Using ServletContextListener to set up resources
such as database connections, thread pools, or configuration settings when
the application starts, and to clean them up when the application shuts
down.
• Session Management
Monitoring User Sessions: Using HttpSessionListener to track the creation
and destruction of user sessions, which is useful for maintaining session-
related data, implementing custom session expiration policies, or managing
session statistics.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Attribute Changes in Sessions: Using HttpSessionAttributeListener to


respond to changes in session attributes, which can be useful for keeping
track of user activity or preferences.
• Request Tracking and Logging
Request Lifecycle Monitoring: Using ServletRequestListener to track the
start and end of requests, which is useful for logging, auditing, and
monitoring request processing times.
Request Attribute Changes: Using ServletRequestAttributeListener to
handle changes in request attributes, which can be useful for tracking state
changes within a request.
• Security
Session Binding: Using HttpSessionBindingListener to monitor objects
bound to sessions, which can help in implementing custom security policies
or logging session activities.
• Distributed Applications
Session Activation/Passivation: Using HttpSessionActivationListener in
distributed environments to handle the passivation (serialization) and
activation (deserialization) of session objects, ensuring that session data is
properly managed across different nodes.

Benefits

• Separation of Concerns: Listeners allow you to separate the logic for handling
specific events from the core business logic of your application. This modular
approach makes the code more maintainable and easier to manage.
• Resource Efficiency: Efficient resource management by initializing resources when
the application starts and cleaning them up when it shuts down helps in optimizing
resource usage and avoiding memory leaks.
• Improved Monitoring and Logging: Listeners provide hooks for monitoring
various events in the application lifecycle, aiding in better logging, debugging, and
auditing of application behavior.
• Enhanced User Experience: By monitoring and managing session and request
attributes, listeners can help in delivering a more responsive and personalized user
experience.
• Scalability and Reliability: In distributed applications, listeners can help in
managing session data across multiple nodes, ensuring that the application
remains scalable and reliable.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

• Security Enhancements: Listeners can help implement and enforce security


policies, such as tracking user sessions and handling session invalidation, thereby
enhancing the overall security of the application.
• Custom Event Handling: Developers can create custom logic to handle specific
events, such as attribute changes or session passivation, allowing for greater
flexibility and control over application behaviour.

Maven
• Maven is a powerful build automation and project management tool primarily used
for Java projects.
• It uses a Project Object Model (POM) file to manage project dependencies, build
processes, and other project-related tasks.

What is Maven?

• Build Automation Tool: Maven automates the process of building and managing
Java projects, ensuring consistent and reproducible builds.
• Dependency Management: Maven manages project dependencies and libraries
efficiently through a central repository, allowing easy addition and updating of
libraries.
• Project Management: It provides a structured way to organize project information
and configurations using a POM file.
• Plugin System: Maven supports a wide range of plugins that enhance its
capabilities, such as compiling code, running tests, packaging applications, and
deploying them.

Significance of using Maven in creating a Servlet Project

• Dependency Management
Simplified Dependencies: Managing dependencies in servlet projects can be
complex due to the various libraries needed (e.g., servlet API, JSP API). Maven
simplifies this by allowing you to specify dependencies in the POM file, and it
automatically downloads and manages them.
Version Control: Maven handles different versions of dependencies, ensuring
compatibility and reducing conflicts.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

• Standard Directory Layout


Consistency: Maven enforces a standard directory structure for projects, making it
easier to navigate and maintain the project. For example, source code is placed in
src/main/java, web resources in src/main/webapp, and configuration files in
src/main/resources.
Best Practices: This structure aligns with industry best practices, enhancing
collaboration and understanding among developers.

• Build Lifecycle Management


Automated Builds: Maven automates the build process, including compiling source
code, packaging the application (e.g., WAR files for web applications), running
tests, and deploying the application.
Phases and Goals: Maven's build lifecycle consists of phases (e.g., compile, test,
package, install, deploy). Each phase performs specific tasks, ensuring a systematic
build process.

• Plugin Integration
Extensibility: Maven’s plugin system allows integration with various tools and
frameworks, such as JUnit for testing, Tomcat for deploying servlets, and other
build tools.
Customization: Plugins can be customized to suit specific project requirements,
enhancing the build process.

• Reproducibility and Continuous Integration


Consistent Builds: Maven ensures that builds are consistent across different
environments by using the same set of dependencies and configurations.
Integration with CI Tools: Maven easily integrates with Continuous Integration (CI)
tools like Jenkins, enabling automated builds, tests, and deployments.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Steps to Create a Maven Project in Eclipse

1. Open Eclipse
Start Eclipse and select your workspace.

2. Install Maven Integration for Eclipse (M2Eclipse)


Most Eclipse IDE packages come with M2Eclipse pre-installed. If it’s not
installed, you can add it via the Eclipse Marketplace:
▪ Go to Help > Eclipse Marketplace.
▪ Search for "Maven Integration for Eclipse" and install it.

3. Create a New Maven Project


▪ Go to File > New > Other.
▪ In the Select a wizard dialog, type Maven to filter the options.
▪ Select Maven Project and click Next.

4. Configure the Maven Project


In the New Maven Project dialog
▪ You can choose to create a simple project (skip archetype selection)
or use an archetype. For a typical servlet project, it’s better to use the
webapp archetype.
▪ Check Create a simple project (skip archetype selection) if you want
a simple setup, or leave it unchecked to choose an archetype.
▪ Click Next.

5. Select an Archetype (if not skipping archetype selection)


▪ In the Select an Archetype dialog:
▪ Filter by webapp to find the maven-archetype-webapp.
▪ Select maven-archetype-webapp and click Next.

6. Enter Group Id, Artifact Id, and Version


▪ Group Id: A unique identifier for your project’s group (e.g.,
com.example).
▪ Artifact Id: The name of the project (e.g., servlet-project).
▪ Version: The version of the project (default is 1.0-SNAPSHOT).
▪ Click Finish.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

7. Project Structure
▪ Eclipse will generate the project structure based on the selected
archetype.
▪ For a webapp archetype, the structure will look like

servlet-project
├── src
│ ├── main
│ │ ├── java
│ │ ├── resources
│ │ └── webapp
│ │ ├── WEB-INF
│ │ │ └── web.xml
│ │ └── index.jsp
├── pom.xml
└── target

8. Add Dependencies
▪ Open the pom.xml file located in the root of your project.
▪ Add the necessary dependencies for your servlet project, for
example:
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<!-- Add other dependencies as needed -->
</dependencies>

9. Create Servlet Class


▪ Right-click on the src/main/java directory and select New > Class.
▪ Enter the package name (e.g., com.example) and class name (e.g.,
HelloServlet).
▪ Implement the servlet by extending HttpServlet and overriding the
doGet() or doPost() methods.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

10. Configure web.xml


The web.xml file located in src/main/webapp/WEB-INF should define the
servlet and its mapping:
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>com.example.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>

11. Build and Run


▪ To build the project, right-click on the project in the Project Explorer
and select Run As > Maven build.
▪ Enter package as the goal to generate the WAR file.
▪ To run the project, you can use a server like Apache Tomcat:
▪ Right-click on the project, select Run As > Run on Server.
▪ Select the server and complete the configuration to deploy your
project.

Configuring Apache Tomcat for a Maven project in Eclipse

Configuring Apache Tomcat for a Maven project in Eclipse involves a few steps, including
installing Tomcat, adding it to Eclipse, and deploying your Maven project to the server.

Prerequisites
▪ Eclipse IDE: Ensure you have Eclipse IDE installed.
▪ Apache Tomcat: Download and install Apache Tomcat from the Tomcat
download page.
▪ Maven: Ensure your Maven project is set up in Eclipse.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Steps to Configure Apache Tomcat for a Maven Project in Eclipse

• Download and Install Apache Tomcat


▪ Download the appropriate version of Tomcat from the Tomcat
download page.
▪ Extract the downloaded archive to a directory on your computer (e.g.,
C:\apache-tomcat-9.0.65).
• Add Tomcat to Eclipse
▪ Open Eclipse & Go to Window > Preferences.
▪ In the Preferences window, expand Server and select Runtime
Environments.
▪ Click Add & Select the version of Apache Tomcat that you
downloaded (e.g., Apache Tomcat v9.0) and click Next.
▪ Click Browse to navigate to the directory where you extracted
Tomcat, then click Finish.
• Create a New Server
▪ In the Servers view (usually located at the bottom of the Eclipse
window), right-click and select New > Server.
▪ Select Apache > Tomcat v9.0 Server (or the version you added) and
click Next.
▪ Select the Tomcat installation directory and click Next.
▪ Click Finish.
• Add Your Maven Project to the Server
▪ In the Servers view, right-click on the Tomcat server you just created
and select Add and Remove.
▪ Select your Maven project from the Available list and click Add to
move it to the Configured list & Click Finish.
• Configure the Maven Project
▪ Open your pom.xml file.
▪ Ensure you have the maven-war-plugin configured to generate a
WAR file:
<build> <plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.3.1</version>
</plugin> </plugins>
</build>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

• Run the Maven Project on Tomcat


▪ Right-click on the Tomcat server in the Servers view and select Start.
▪ Once the server is started, right-click on your Maven project in the
Project Explorer, select Run As > Run on Server.
▪ Choose the Tomcat server and click Finish.

Additional Tips
• Debugging: To debug your application, you can start the server in debug mode
by right-clicking the Tomcat server in the Servers view and selecting Debug.
• Hot Deploy: Eclipse supports hot deployment, which means changes to your Java
classes and JSP files can be automatically deployed to Tomcat without restarting
the server.
• Web.xml Configuration: Ensure your web.xml file is correctly configured for your
servlets and other web components.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

ServletContextListener
• A ServletContextListener is an interface in the Java Servlet API that allows you to
perform actions when a web application's servlet context is initialized or destroyed.
• It is part of the javax.servlet package and is used to handle events related to the
lifecycle of the ServletContext.
• It is used to execute code during the startup and shutdown of a web application.
• It is commonly used for initializing resources like database connections, starting
background threads, or setting up application-wide configurations.
• To use a ServletContextListener, you need to implement the interface and override
its methods.
• The listener must be registered in the web.xml deployment descriptor or annotated
with @WebListener for automatic discovery.

Common Use Cases

• Initializing Resources: Setting up resources like database connections, caches, or


configuration settings at application startup.
• Cleanup Activities: Releasing resources or saving state before the application
shuts down.
• Logging: Logging the start and stop events of a web application.
• Background Services: Starting and stopping background services or threads
needed by the application.

By using a ServletContextListener, you can ensure that certain tasks are performed at the
appropriate stages of your web application's lifecycle, providing better control and
management of your application's resources and behavior.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Example : Create a simple Java web application that demonstrates the use of a
ServletContextListener

Project Structure
ServletContextListenerExample/
├── src/
│ ├── main/
│ │ ├── java/
│ │ │ └── com/
│ │ │ └── example/
│ │ │ ├── listener/
│ │ │ │ └── AppContextListener.java
│ │ │ └── servlet/
│ │ │ └── HelloServlet.java
│ │ └── webapp/
│ │ ├── WEB-INF/
│ │ │ └── web.xml
│ │ └── index.jsp
├── pom.xml
└── README.md

Step-by-Step Implementation

• Setup Maven Project: Ensure you have Maven installed. Create a new Maven
project with the directory structure as shown above.

• pom.xml: Include the necessary dependencies for the servlet.

<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>ServletListenerExample</artifactId>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>

<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.3.1</version>
</plugin>
</plugins>
</build>
</project>

• AppContextListener.java: Create the ServletContextListener that will initialize and


clean up resources.

package com.example.listener;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

@WebListener
public class AppContextListener implements ServletContextListener {

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

@Override
public void contextInitialized(ServletContextEvent sce) {
// Initialize resources here (e.g., database connection)
System.out.println("Application started. Initializing resources.");
// sce.getServletContext().setAttribute("dbConnection",
dbConnection);
}

@Override
public void contextDestroyed(ServletContextEvent sce) {
// Clean up resources here (e.g., close database connection)
System.out.println("Application stopped. Cleaning up resources.");
// dbConnection.close();
}
}

• HelloServlet.java: Create a simple servlet to handle requests.

package com.example.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
response.setContentType("text/html");
response.getWriter().println("<h1>Learn2Earn Labs Training
Institute!</h1>");
}
}

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

• web.xml: Define the listener and servlet in the deployment descriptor.

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">

<listener>
<listener-class>com.example.listener.AppContextListener</listener-
class>
</listener>

<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>com.example.servlet.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>

• index.html: Create a simple JSP file to test the servlet.

<!DOCTYPE html>
<html>
<head>
<title>Servlet Listener Example</title>
</head>
<body>
<h2>Welcome to Servlet Listener Example</h2>
<a href="hello">Say Hello</a>
</body>
</html>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Running the Project

• Package the application using Maven:


mvn clean package

• Deploy the WAR file (ServletListenerExample.war) to a servlet container like Apache


Tomcat.

• Access the application in a web browser:


▪ Navigate to http://localhost:8080/ServletListenerExample to see the
index page.
▪ Click the "Say Hello" link to trigger the HelloServlet.

The AppContextListener will log messages to the console when the application starts and
stops, demonstrating how resources can be managed during these lifecycle events.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Another Example : Create a simple Java web application that demonstrates the use of a
ServletContextListener

index.html
<!DOCTYPE html>
<html>
<head><meta charset="ISO-8859-1">
<title>Servlet Context Listener example</title>
</head>
<body>
<form action="first" method="get">
enter table name<input type="text" name="tablename">
<input type="submit" value="enter">
</form>
</body>
</html>

MyServlet.java
package com.example.java;

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

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

public class MyServlet extends HttpServlet {


String tablename;
Connection connection;
PreparedStatement statement;
ResultSet rs;
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();

tablename=request.getParameter("tablename");

ServletContext context=getServletContext();
connection=(Connection)context.getAttribute("con");

try
{
statement=connection.prepareStatement("select * from
"+tablename);
rs=statement.executeQuery();
while(rs.next())
{
int id=rs.getInt(1);
String name=rs.getString(2);

out.write(id+" with name "+name);


out.write("<br>");
}
out.write("<a href=index.html>go to homepage</a>");
}
catch(SQLException e)
{
e.printStackTrace();
}
}
}

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

MyListener.java
package com.example.java;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

public class MyListener implements ServletContextListener {


Connection connection;
ServletContext context;
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("context destroyed");
context=sce.getServletContext();
connection=(Connection)context.getAttribute("con");
try {
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} }
public void contextInitialized(ServletContextEvent sce) {
System.out.print("context initialized");
try {
Class.forName("com.mysql.cj.jdbc.Driver");
connection=DriverManager.getConnection("jdbc:mysql://localhost/servletdb","ro
ot","android");
context=sce.getServletContext();
context.setAttribute("con", connection);
}
catch(ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
} }

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID"
version="4.0">
<display-name>listenerex</display-name>

<servlet>
<servlet-name>first</servlet-name>
<servlet-class>com.example.java.MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>first</servlet-name>
<url-pattern>/first</url-pattern>
</servlet-mapping>

<listener>
<listener-class>com.example.java.MyListener</listener-class>
</listener>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

ServletContextAttributeListener
• A ServletContextAttributeListener is an interface in the Java Servlet API that allows
you to receive notifications about changes to the attributes of the ServletContext
of a web application.
• This listener is part of the javax.servlet package and is used to handle events related
to the addition, removal, and replacement of attributes in the ServletContext.
• It is used to track and respond to changes in the attributes of the ServletContext.
• It is useful for monitoring and managing application-wide data stored as context
attributes.
• To use a ServletContextAttributeListener, you need to implement the interface and
override its methods.
• The listener must be registered in the web.xml deployment descriptor or annotated
with @WebListener for automatic discovery.

Common Use Cases

• Monitoring Context Attributes: Keeping track of changes to application-wide


attributes for logging or auditing purposes.
• Resource Management: Managing resources that are tied to specific context
attributes, ensuring they are properly initialized and cleaned up.
• Dynamic Configuration: Responding to changes in configuration settings that are
stored as context attributes, allowing the application to adapt to new
configurations on the fly.
• Inter-component Communication: Facilitating communication between different
parts of the application by monitoring shared context attributes.

By using a ServletContextAttributeListener, you can effectively monitor and respond to


changes in the attributes of your ServletContext, ensuring better control over application-
wide data and resources. This can enhance the manageability, scalability, and
maintainability of your web application.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Example : Create a simple Java web application that demonstrates the use of a
ServletContextAttributeListener

AppContextAttributeListener.java
package com.example.listener;

import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;
import javax.servlet.annotation.WebListener;

@WebListener
public class AppContextAttributeListener implements
ServletContextAttributeListener {

@Override
public void attributeAdded(ServletContextAttributeEvent event) {
System.out.println("Attribute added successfully: " + event.getName() + " = "
+ event.getValue());
}

@Override
public void attributeRemoved(ServletContextAttributeEvent event) {
System.out.println("Attribute removed successfully: " + event.getName());
}

@Override
public void attributeReplaced(ServletContextAttributeEvent event) {
System.out.println("Attribute replaced successfully: " + event.getName() + "
= " + event.getValue());
}
}

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

AttributeServlet.java
package com.example.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/attributes")
public class AttributeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse


response) throws ServletException, IOException {
getServletContext().setAttribute("exampleAttribute", "Hello World!");
response.getWriter().println("Attribute has been set. Check console for
listener output.");
}

protected void doPost(HttpServletRequest request, HttpServletResponse


response) throws ServletException, IOException {
getServletContext().setAttribute("exampleAttribute",
request.getParameter("value"));
response.getWriter().println("Attribute has been updated. Check console for
listener output.");
}

protected void doDelete(HttpServletRequest request, HttpServletResponse


response) throws ServletException, IOException {
getServletContext().removeAttribute("exampleAttribute");
response.getWriter().println("Attribute has been removed. Check console for
listener output.");
}
}

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID"
version="4.0">
<display-name>checkpro</display-name>
<servlet>
<servlet-name>AttributeServlet</servlet-name>
<servlet-class>com.example.servlet.AttributeServlet</servlet-class>
</servlet>
<listener>
<listener-class>com.example.listener.AppContextAttributeListener</listener-
class>
</listener> <welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>

Run the Project

• Right-click the project and select Run As > Run on Server.


• Choose your server (e.g., Tomcat) and click Finish.
• Access the servlet in your browser at
http://localhost:8080/ServletContextAttributeListenerExample/attributes.

Testing the Listener


• Adding an Attribute: Access the below URL to add an attribute. Check the console
for the "Attribute added" message.
http://localhost:8080/ServletContextAttributeListenerExample/attributes
• Updating an Attribute: Use a tool like Postman to send a POST request to the
same URL with a parameter value to update the attribute. Check the console for
the "Attribute replaced" message.
• Removing an Attribute: Use Postman to send a DELETE request to the same URL
to remove the attribute. Check the console for the "Attribute removed" message.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

HttpSessionListener
• A HttpSessionListener is an interface in the Java Servlet API that allows you to
receive notifications about the lifecycle events of HttpSession objects in a web
application.
• This listener is part of the javax.servlet.http package and is used to handle events
related to the creation and destruction of sessions.
• It is used to perform actions when an HttpSession is created or destroyed.
• It is commonly used for session management tasks such as resource allocation,
cleanup, session counting, and logging.
• To use an HttpSessionListener, you need to implement the interface and override
its methods.
• The listener must be registered in the web.xml deployment descriptor or annotated
with @WebListener for automatic discovery.

Common Use Cases

• Session Counting: Keeping track of the number of active sessions for monitoring
or reporting purposes.
• Resource Management: Allocating resources (e.g., database connections) when
a session is created and releasing them when the session is destroyed.
• Logging: Logging session creation and destruction events for audit and analysis.
• Session Initialization: Setting up initial session attributes or configurations when
a session is created.
• Cleanup Activities: Performing necessary cleanup operations when a session is
invalidated, such as logging out users or saving session data.

By using an HttpSessionListener, you can effectively manage the lifecycle of user sessions,
ensuring proper resource management, session tracking, and initialization/cleanup tasks.
This enhances the reliability and maintainability of your web application, especially in
handling user interactions and session-based data.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Example : Create a simple Java web application that demonstrates the use of a
HttpSessionListener

index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>login dashboarde</title>
</head>
<body>
<form action="first" method="get">
<input type="text" name="username" placeholder="enter
username">
<input type="password" name="password" placeholder="enter
password">
<input type="submit" value="login">
</form>
</body>
</html>

MyListener.java
package com.example.java;
import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class MyListener implements HttpSessionListener {


ServletContext context=null;
static int totalUsers=0, currentUsers=0;

public void sessionCreated(HttpSessionEvent se) {


System.out.println("session object created with id :
"+se.getSession().getId());
totalUsers++;

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

currentUsers++;

context=se.getSession().getServletContext();
context.setAttribute("totalUsers",totalUsers);
context.setAttribute("currentUsers", currentUsers);
}
public void sessionDestroyed(HttpSessionEvent se) {
System.out.println("session object destroyed with id :
"+se.getSession().getId());
currentUsers--;
context.setAttribute("currentUsers", currentUsers);
}
}

MyServlet.java
package com.example.java;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class MyServlet extends HttpServlet {


String username, password;
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
username=request.getParameter("username");
password=request.getParameter("password");
out.print("welcome : "+username);

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

HttpSession session=request.getSession();
ServletContext context=getServletContext();
int totalUsers=(Integer)context.getAttribute("totalUsers");
int currentUsers=(Integer)context.getAttribute("currentUsers");

out.write("number of total users : "+totalUsers);


out.write("<br>");
out.write("number of current users : "+currentUsers);
out.write("<br><a href='logout'>logout</a>");
}
}

LogoutServlet.java
package com.example.java;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LogoutServlet extends HttpServlet {


protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
HttpSession session =request.getSession();
session.invalidate();
out.write("successfully logged out");
}

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID"
version="4.0">
<display-name>listenerex</display-name>

<servlet>
<servlet-name>first</servlet-name>
<servlet-class>com.example.java.MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>first</servlet-name>
<url-pattern>/first</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>logout</servlet-name>
<servlet-class>com.example.java.LogoutServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>logout</servlet-name>
<url-pattern>/logout</url-pattern>
</servlet-mapping>

<listener>
<listener-class>com.example.java.MyListener</listener-class>
</listener>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Another Example : Create a simple Java web application that demonstrates the use of a
HttpSessionListener

SessionListener.java
package com.example.listener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import javax.servlet.annotation.WebListener;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Logger;

@WebListener
public class SessionListener implements HttpSessionListener {
private static final Logger logger =
Logger.getLogger(SessionListener.class.getName());
private static final AtomicInteger activeSessions = new AtomicInteger();
@Override
public void sessionCreated(HttpSessionEvent se) {
activeSessions.incrementAndGet();
logger.info("Session created: " + se.getSession().getId() +
" | Active sessions: " + activeSessions.get());
// Perform session initialization
se.getSession().setAttribute("initialized", true);
}
@Override
public void sessionDestroyed(HttpSessionEvent se) {
activeSessions.decrementAndGet();
logger.info("Session destroyed: " + se.getSession().getId() +
" | Active sessions: " + activeSessions.get());
// Perform session cleanup
se.getSession().removeAttribute("initialized");
}
public static int getActiveSessions() {
return activeSessions.get();
}
}

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

SessionServlet.java
package com.example.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet("/session")
public class SessionServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse


response)
throws ServletException, IOException {
HttpSession session = request.getSession();
response.getWriter().println("Session ID: " + session.getId());
response.getWriter().println("Session initialized: " +
session.getAttribute("initialized"));
}

protected void doPost(HttpServletRequest request, HttpServletResponse


response)
throws ServletException, IOException {
HttpSession session = request.getSession(false);
if (session != null) {
session.invalidate();
response.getWriter().println("Session invalidated.");
} else {
response.getWriter().println("No session to invalidate.");
}
}
}

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

index.jsp
<!DOCTYPE html>
<html>
<head> <title>Session Example</title> </head>
<body>
<h2>Session Example</h2>
<a href="session">Create/Check Session</a>
<form action="session" method="post">
<button type="submit">Invalidate Session</button>
</form>
<p>Active Sessions: <%=
com.example.listener.SessionListener.getActiveSessions() %></p>
</body>
</html>

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID"
version="4.0">
<display-name>checkpro</display-name>
<servlet>
<servlet-name>SessionServlet</servlet-name>
<servlet-class>com.example.servlet.SessionServlet</servlet-class>
</servlet>

<listener>
<listener-class>com.example.listener.SessionListener</listener-class>
</listener>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Run the Project

• Right-click the project and select Run As > Run on Server.


• Choose your server (e.g., Tomcat) and click Finish.
• Access the application in your browser at
http://localhost:8080/HttpSessionListenerExample/.

Testing the Application


• Creating a Session: Access the below URL to create a session. The session ID and
initialization status should be displayed.
http://localhost:8080/HttpSessionListenerExample/session
• Invalidating a Session: Use the form in index.jsp to invalidate the session. The
session should be invalidated, and a message should be displayed.
• Active Sessions: The active session count is displayed on index.jsp.

This setup provides a comprehensive example of using HttpSessionListener for session


counting, resource management, logging, session initialization, and cleanup activities in
a Java web application.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Best Training Institute
for Graduates
with
Live Online & Offline Classes Available

Join us for Better Career and Job Guarantee

Full Stack Web Development


Top Edge (MERN Stack) HTML, CSS, JavaScript, ES,
Git, ReactJS, Node, Express, MySQL & MongoDB

Training Full Stack Engineer


Java, JavaScript, ReactJS, Spring, SpringBoot
Hibernate, Linux, AWS, Git, DevOps & Jira

Programs Digital Marketing


Social Media, Website Design, SEO,
Google Ads, Freelancing & Many More

Guaranteed Package (In Writing)


▪ 3-5 Lakhs (With 6 Months Training Programs)
▪ 6-8 Lakhs (With 12 Months Training Programs)
▪ 10 Lakhs+ (With 2 Years Training Programs)

Amenities
▪ Digital Notes ▪ Working Experience
▪ Live Training Sessions ▪ Job Recommendations
▪ Project Assistance ▪ Professional Development
▪ Interview Preparation ▪ Digital Resume & Portfolio

LEARN-2-EARN LABS TRAINING INSTITUTE


Anna Icon Complex, near Kargil Petrol Pump, Sikandra-Bodla Road, Sikandra, Agra
Website : www.LearntoearnLabs.com
Call : 91-9548868337 / +91-9837705705
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

HttpSessionAttributeListener
• A HttpSessionAttributeListener is an interface in the Java Servlet API that allows
you to receive notifications about changes to the attributes of HttpSession objects
in a web application.
• This listener is part of the javax.servlet.http package and is used to handle events
related to the addition, removal, and replacement of session attributes.
• It is used to track and respond to changes in the attributes of HttpSession objects.
• It is useful for monitoring and managing session-specific data.
• To use an HttpSessionAttributeListener, you need to implement the interface and
override its methods.
• The listener must be registered in the web.xml deployment descriptor or annotated
with @WebListener for automatic discovery.

Common Use Cases

• Monitoring Session Attributes: Keeping track of changes to session attributes for


logging or auditing purposes.
• State Management: Managing user-specific state information stored in session
attributes.
• Debugging: Tracking changes to session attributes can be useful for debugging
issues related to session state.
• Security: Monitoring sensitive session attributes for unexpected changes as part
of a security strategy.
• Inter-component Communication: Facilitating communication between different
parts of the application by tracking shared session attributes.

By using an HttpSessionAttributeListener, you can effectively monitor and respond to


changes in the attributes of your HttpSession objects, ensuring better control over
session-specific data and resources. This enhances the functionality and security of your
web application by providing hooks into the session attribute lifecycle.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Example : Create a simple Java web application that demonstrates the use of a
HttpSessionAttributeListener

SessionAttributeListener.java
package com.example.listener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import java.util.logging.Logger;

@WebListener
public class SessionAttributeListener implements HttpSessionAttributeListener {

private static final Logger logger =


Logger.getLogger(SessionAttributeListener.class.getName());

@Override
public void attributeAdded(HttpSessionBindingEvent event) {
logger.info("Attribute added: " + event.getName() + " = " +
event.getValue());
// Perform security check
if ("userRole".equals(event.getName()) && "admin".equals(event.getValue()))
{
logger.info("Admin user logged in.");
}
}
@Override
public void attributeRemoved(HttpSessionBindingEvent event) {
logger.info("Attribute removed: " + event.getName());
}
@Override
public void attributeReplaced(HttpSessionBindingEvent event) {
logger.info("Attribute replaced: " + event.getName() + " = " +
event.getValue());
}
}

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

AttributeServlet.java
package com.example.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet("/attributes")
public class AttributeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse


response) throws ServletException, IOException {
HttpSession session = request.getSession();
session.setAttribute("userRole", "admin");
response.getWriter().println("Attribute added successfully. Check the logs for
listener output.");
}
protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
HttpSession session = request.getSession();
session.setAttribute("userRole", request.getParameter("role"));
response.getWriter().println("Attribute updated successfully. Check the logs
for listener output.");
}
protected void doDelete(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
HttpSession session = request.getSession();
session.removeAttribute("userRole");
response.getWriter().println("Attribute removed successfully. Check the logs
for listener output.");
}
}

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

index.html
<!DOCTYPE html>
<html>
<head> <title>Session Attribute Example</title> </head>
<body>
<h2>Session Attribute Example</h2>
<a href="attributes">Add Attribute</a>
<form action="attributes" method="post">
<label for="role">Set Role:</label>
<input type="text" id="role" name="role">
<button type="submit">Update Attribute</button>
</form>
<form action="attributes" method="delete">
<button type="submit">Remove Attribute</button>
</form>
</body></html>

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID"
version="4.0">
<display-name>checkpro</display-name>
<servlet>
<servlet-name>AttributeServlet</servlet-name>
<servlet-class>com.example.servlet.AttributeServlet</servlet-class>
</servlet>
<listener>
<listener-class>com.example.listener.SessionAttributeListener</listener-class>
</listener>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Run the Project

• Right-click the project and select Run As > Run on Server.


• Choose your server (e.g., Tomcat) and click Finish.
• Access the application in your browser at
http://localhost:8080/HttpSessionAttributeListenerExample/

Testing the Application


• Adding an Attribute: Access the below URL to add an attribute. The attribute
addition should be logged.
http://localhost:8080/HttpSessionAttributeListenerExample/attributes
• Updating an Attribute: Use the form in index.html to update the attribute. The
attribute update should be logged.
• Removing an Attribute: Use the form in index.html to remove the attribute. The
attribute removal should be logged.

This setup provides a comprehensive example of using HttpSessionAttributeListener for


monitoring session attributes and performing state management, debugging, security
checks, and inter-component communication in a Java web application.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

HttpSessionBindingListener
• A HttpSessionBindingListener is an interface in the Java Servlet API that allows an
object to receive notifications when it is added to or removed from an HttpSession.
• This listener is part of the javax.servlet.http package and is used for tracking objects
that are bound to or unbound from a session.
• It is used to perform actions when an object is added to or removed from an
HttpSession.
• It is useful for managing resources or performing cleanup tasks when session
attributes change.
• To use an HttpSessionBindingListener, an object must implement this interface.
• The methods are automatically called when the object is added to or removed from
the session as an attribute.

Common Use Cases

• Resource Management: Allocating resources (e.g., database connections, file


handles) when the object is added to the session and releasing them when the
object is removed.
• Session Cleanup: Ensuring that any necessary cleanup operations are performed
when the session attribute is removed.
• State Tracking: Keeping track of when an object becomes associated with or
dissociated from a session.
• Logging: Logging the addition and removal of objects from sessions for audit and
debugging purposes.
• Security: Managing security-sensitive objects by performing actions when they are
bound to or unbound from sessions.

By using an HttpSessionBindingListener, you can manage the lifecycle of session


attributes more effectively, ensuring that resources are properly allocated and cleaned up
as objects are added to and removed from sessions. This enhances the robustness and
maintainability of your web application.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Example : Create a simple Java web application that demonstrates the use of a
HttpSessionBindingListener

User.java (Listener)
package com.example.model;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;
import java.util.logging.Logger;

public class User implements HttpSessionBindingListener {

private static final Logger logger = Logger.getLogger(User.class.getName());


private String username;

public User(String username) {


this.username = username;
}
@Override
public void valueBound(HttpSessionBindingEvent event) {
logger.info("User " + username + " bound to session " +
event.getSession().getId());
// Perform resource allocation or initialization
}
@Override
public void valueUnbound(HttpSessionBindingEvent event) {
logger.info("User " + username + " unbound from session " +
event.getSession().getId());
// Perform resource cleanup
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

UserServlet.java
package com.example.servlet;
import com.example.model.User;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/user")
public class UserServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse


response)
throws ServletException, IOException {
HttpSession session = request.getSession();
User user = new User("Learn2EarnLabs");
session.setAttribute("user", user);
response.getWriter().println("User added to session. Check the logs for
listener output.");
}

protected void doDelete(HttpServletRequest request, HttpServletResponse


response)
throws ServletException, IOException {
HttpSession session = request.getSession();
session.removeAttribute("user");
response.getWriter().println("User removed from session. Check the logs for
listener output.");
}
}

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

index.html
<!DOCTYPE html>
<html>
<head> <title>User Session Example</title></head>
<body>
<h2>User Session Example</h2>
<a href="user">Add User to Session</a>
<form action="user" method="delete">
<button type="submit">Remove User from Session</button>
</form>
</body>
</html>

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID"
version="4.0">
<display-name>checkpro</display-name>
<servlet>
<servlet-name>UserServlet</servlet-name>
<servlet-class>com.example.servlet.UserServlet</servlet-class>
</servlet>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Run the Project

• Right-click the project and select Run As > Run on Server.


• Choose your server (e.g., Tomcat) and click Finish.
• Access the application in your browser at
http://localhost:8080/HttpSessionBindingListenerExample/

Testing the Application

• Adding a User: Access the below URL to add a user object to the session. The
user addition should be logged.
http://localhost:8080/HttpSessionBindingListenerExample/user
• Removing a User: Use the form in index.html to remove the user object from the
session. The user removal should be logged.

This setup provides a comprehensive example of using HttpSessionBindingListener for


resource management, session cleanup, state tracking, logging, and managing security in
a Java web application.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

HttpSessionActivationListener
• The HttpSessionActivationListener interface in the Java Servlet API allows you to
receive notifications when an HttpSession is activated or passivated.
• This listener is part of the javax.servlet.http package and is used for managing and
monitoring session activation and passivation events.
• It is used to perform actions when an HttpSession is activated (i.e., when it is bound
to a session) or passivated (i.e., when it is moved out of memory to a persistent
storage).
• It is useful for managing resources, initializing or cleaning up session data, or
logging events related to session activation and passivation.
• To use an HttpSessionActivationListener, you need to implement the interface and
override its methods.
• The listener must be registered in the web.xml deployment descriptor or annotated
with @WebListener for automatic discovery.

Common Use Cases

• Resource Management: Performing cleanup or initialization tasks for session-


specific resources when the session is passivated or activated.
• Session State Management: Keeping track of when session data is moved out of
memory (passivated) or brought back into memory (activated).
• Cache Management: Storing or retrieving session data from a cache or database
when the session is passivated or activated.
• Security: Ensuring that sensitive session data is properly handled before
passivation and reinitialized after activation.
• Logging: Logging events related to session activation and passivation for audit
and debugging purposes.

By using an HttpSessionActivationListener, you can effectively manage the activation and


passivation of session data in your web application, ensuring that resources are properly
managed and initialized when needed. This enhances the scalability, performance, and
reliability of your application, especially in scenarios where session data needs to be
persisted or managed across server restarts.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Example: Create a simple Java web application that demonstrates the use of a
HttpSessionActivationListener

SessionActivationListener.java
package com.example.listener;
import javax.servlet.http.HttpSessionActivationListener;
import javax.servlet.http.HttpSessionEvent;
import java.util.logging.Logger;

public class SessionActivationListener implements HttpSessionActivationListener {


private static final Logger logger =
Logger.getLogger(SessionActivationListener.class.getName());
@Override
public void sessionWillPassivate(HttpSessionEvent se) {
logger.info("Session will be passivated: " + se.getSession().getId());
// Perform resource management before passivation
}
@Override
public void sessionDidActivate(HttpSessionEvent se) {
logger.info("Session activated: " + se.getSession().getId());
// Perform resource initialization after activation
}
}

SessionServlet.java
package com.example.servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebServlet("/session")
public class SessionServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

protected void doGet(HttpServletRequest request, HttpServletResponse


response) throws ServletException, IOException {
HttpSession session = request.getSession();
response.getWriter().println("Session ID: " + session.getId());
}
}

index.html
<!DOCTYPE html>
<html>
<head> <title>Session Example</title></head>
<body>
<h2>Session Example</h2>
<a href="session">Check Session ID</a>
</body>
</html>

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID"
version="4.0">
<display-name>checkpro</display-name>
<listener>
<listener-class>com.example.listener.SessionActivationListener</listener-class>
</listener>
<servlet>
<servlet-name>SessionServlet</servlet-name>
<servlet-class>com.example.servlet.SessionServlet</servlet-class>
</servlet>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Run the Project

• Right-click the project and select Run As > Run on Server.


• Choose your server (e.g., Tomcat) and click Finish.
• Access the application in your browser at
http://localhost:8080/HttpSessionActivationListenerExample/

Testing the Application


Checking Session ID: Access the below URL to check the session ID. Check the logs for
activation and passivation events.
http://localhost:8080/HttpSessionActivationListenerExample/session

This setup provides a comprehensive example of using HttpSessionActivationListener for


resource management, session state management, cache management, ensuring security,
and logging in a Java web application.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

ServletRequestListener
• The ServletRequestListener interface in the Java Servlet API allows you to receive
notifications about the lifecycle events of ServletRequest objects in a web
application.
• This listener is part of the javax.servlet package and is used for handling events
related to the creation and destruction of servlet requests.
• It is used to perform actions when a ServletRequest is created or destroyed.
• It is useful for logging request lifecycle events, initializing resources per request,
and performing cleanup tasks.
• To use a ServletRequestListener, you need to implement the interface and override
its methods.
• The listener must be registered in the web.xml deployment descriptor or annotated
with @WebListener for automatic discovery.

Common Use Cases

• Logging: Logging the start and end of each request for audit and debugging
purposes.
• Resource Management: Initializing resources (e.g., database connections) at the
start of a request and releasing them at the end.
• Performance Monitoring: Measuring the duration of requests to monitor
performance and identify bottlenecks.
• Security: Tracking request data for security purposes, such as monitoring request
origins and parameters.
• Request Initialization: Setting up request-specific attributes or context data
needed for request processing.
• Cleanup Activities: Ensuring that any resources allocated during the request are
properly cleaned up when the request is completed.

By using a ServletRequestListener, you can effectively manage the lifecycle of servlet


requests in your web application, ensuring that resources are properly initialized and
cleaned up, and that important events are logged and monitored. This enhances the
performance, security, and reliability of your web application.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Example: Create a simple Java web application that demonstrates the use of a
ServletRequestListener

RequestListener.java
package com.example.listener;

import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
import java.util.logging.Logger;

@WebListener
public class RequestListener implements ServletRequestListener {

private static final Logger logger =


Logger.getLogger(RequestListener.class.getName());

@Override
public void requestInitialized(ServletRequestEvent sre) {
logger.info("Request initialized. Remote IP: " +
sre.getServletRequest().getRemoteAddr());
// Perform resource management or logging
}

@Override
public void requestDestroyed(ServletRequestEvent sre) {
logger.info("Request destroyed. Remote IP: " +
sre.getServletRequest().getRemoteAddr());
// Clean up resources
}
}

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

RequestServlet.java
package com.example.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/request")
public class RequestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse


response)
throws ServletException, IOException {
response.getWriter().println("Request processed. Check the logs for listener
output.");
}
}

index.html
<!DOCTYPE html>
<html>
<head>
<title>Servlet Request Listener Example</title>
</head>
<body>
<h2>Servlet Request Listener Example</h2>
<a href="request">Process Request</a>
</body>
</html>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID"
version="4.0">
<display-name>checkpro</display-name>
<servlet>
<servlet-name>RequestServlet</servlet-name>
<servlet-class>com.example.servlet.RequestServlet</servlet-class>
</servlet>
<listener>
<listener-class>com.example.listener.RequestListener</listener-class>
</listener>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>

Run the Project

• Right-click the project and select Run As > Run on Server.


• Choose your server (e.g., Tomcat) and click Finish.
• Access the application in your browser at
http://localhost:8080/ServletRequestListenerExample/

Testing the Application

• Processing Request: Access the below URL to process a request. Check the logs to
see the output from the listener indicating that a request has been initialized and
destroyed.
http://localhost:8080/ServletRequestListenerExample/request

This setup provides a comprehensive example of using ServletRequestListener for


resource management, request logging, and session state management in a Java web
application.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

ServletRequestAttributeListener
• The ServletRequestAttributeListener interface in the Java Servlet API allows you to
receive notifications about changes to the attributes of ServletRequest objects in a
web application.
• This listener is part of the javax.servlet package and is used for handling events
related to the addition, removal, and replacement of request attributes.
• It is used to track and respond to changes in the attributes of ServletRequest
objects.
• It is useful for monitoring and managing request-specific data.
• To use a ServletRequestAttributeListener, you need to implement the interface and
override its methods.
• The listener must be registered in the web.xml deployment descriptor or annotated
with @WebListener for automatic discovery.

Common Use Cases

• Logging: Logging changes to request attributes for debugging and auditing


purposes.
• Security: Monitoring changes to request attributes that may contain sensitive
information.
• Inter-component Communication: Tracking and responding to changes in
attributes used for communication between different components of a web
application.
• Data Validation: Ensuring that request attributes meet certain criteria when they
are added, removed, or replaced.
• Performance Monitoring: Tracking attributes related to performance metrics or
other request-specific data.

By using a ServletRequestAttributeListener, you can effectively monitor and respond to


changes in the attributes of your ServletRequest objects, ensuring better control over
request-specific data and enhancing the overall functionality, security, and maintainability
of your web application.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Example: Create a simple Java web application that demonstrates the use of a
ServletRequestAttributeListener

RequestAttributeListener.java
package com.example.listener;

import javax.servlet.ServletRequestAttributeEvent;
import javax.servlet.ServletRequestAttributeListener;
import javax.servlet.annotation.WebListener;
import java.util.logging.Logger;

@WebListener
public class RequestAttributeListener implements ServletRequestAttributeListener
{

private static final Logger logger =


Logger.getLogger(RequestAttributeListener.class.getName());

@Override
public void attributeAdded(ServletRequestAttributeEvent srae) {
logger.info("Attribute added: " + srae.getName() + " = " + srae.getValue());
// Perform security check or data validation
}

@Override
public void attributeRemoved(ServletRequestAttributeEvent srae) {
logger.info("Attribute removed: " + srae.getName());
// Handle attribute removal
}

@Override
public void attributeReplaced(ServletRequestAttributeEvent srae) {
logger.info("Attribute replaced: " + srae.getName() + " = " + srae.getValue());
// Perform inter-component communication or performance monitoring
}
}

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

RequestAttributeServlet.java
package com.example.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/request")
public class RequestAttributeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse


response) throws ServletException, IOException {
request.setAttribute("username", "JohnDoe");
response.getWriter().println("Attribute added. Check the logs for listener
output.");
}

protected void doPost(HttpServletRequest request, HttpServletResponse


response) throws ServletException, IOException {
request.setAttribute("username", request.getParameter("username"));
response.getWriter().println("Attribute updated. Check the logs for listener
output.");
}

protected void doDelete(HttpServletRequest request, HttpServletResponse


response) throws ServletException, IOException {
request.removeAttribute("username");
response.getWriter().println("Attribute removed. Check the logs for listener
output.");
}
}

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

index.html
<!DOCTYPE html>
<html>
<head> <title>Servlet Request Attribute Listener Example</title></head>
<body>
<h2>Servlet Request Attribute Listener Example</h2>
<a href="example">Add Attribute</a>
<form action="request" method="post">
<label for="username">Set Username:</label>
<input type="text" id="username" name="username">
<button type="submit">Update Attribute</button>
</form>
<form action="request" method="delete">
<button type="submit">Remove Attribute</button>
</form>
</body>
</html>

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID"
version="4.0">
<display-name>checkpro</display-name>
<servlet>
<servlet-name> RequestAttributeServlet</servlet-name>
<servlet-class>com.example.servlet.RequestAttributeServlet</servlet-class>
</servlet>
<listener>
<listener-class>com.example.listener.RequestAttributeListener</listener-
class> </listener><welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Run the Project

• Right-click the project and select Run As > Run on Server.


• Choose your server (e.g., Tomcat) and click Finish.
• Access the application in your browser at
http://localhost:8080/ServletRequestAttributeListenerExample/

Testing the Application

• Adding an Attribute: Access the below URL to add an attribute. The attribute
addition should be logged.
http://localhost:8080/ServletRequestAttributeListenerExample/request
• Updating an Attribute: Use the form in index.html to update the attribute. The
attribute update should be logged.
• Removing an Attribute: Use the form in index.html to remove the attribute. The
attribute removal should be logged.

This setup provides a comprehensive example of using ServletRequestAttributeListener


for logging, security, inter-component communication, data validation, and performance
monitoring in a Java web application.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

MIME implementation in Servlet


• MIME (Multipurpose Internet Mail Extensions) implementation in servlets primarily
involves handling different types of data within HTTP requests and responses.
• Servlets, being part of Java EE (Enterprise Edition), have built-in support for MIME
types.
• MIME (Multipurpose Internet Mail Extensions) plays a critical role in web
development and HTTP communication.
• Understanding its implementation in servlets is essential for effectively handling
various types of data exchanged between clients and servers.
• MIME type handling is an integral part of servlet development, enabling robust
and secure web applications.
• By understanding and correctly implementing MIME handling, developers ensure
that data is correctly interpreted and processed by both clients and servers.
• This involves setting appropriate headers, handling file uploads, performing
content negotiation, and addressing security concerns related to MIME types.

Let’s discuss about MIME implementation in detail:

MIME Basics

• Definition: MIME is a standard for specifying the nature and format of a document,
file, or assortment of bytes. Initially developed for email, MIME types have become
a cornerstone of web communication.
• Structure: MIME types are composed of a type and a subtype, separated by a slash
(e.g., text/html, image/jpeg). This structure allows for a broad classification of data
types.

MIME in HTTP

• Content-Type Header: This HTTP header is used to indicate the media type of the
resource. Servers set this header in HTTP responses, and clients (browsers) use it
to interpret the content correctly.
• Accept Header: Clients send this header to inform the server of the MIME types
they can process. The server can then choose an appropriate representation of the
resource.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

MIME Handling in Servlets

• Setting Content-Type: The HttpServletResponse.setContentType(String type)


method is used to set the MIME type of the response.
Example:
response.setContentType("application/json");
This is critical for ensuring the client correctly interprets the response data.
• File Uploads: The @MultipartConfig annotation allows servlets to handle file
uploads. Uploaded files can be accessed via the HttpServletRequest.getPart(String
name) method.
Example:
@WebServlet("/upload")
@MultipartConfig
public class FileUploadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
Part filePart = request.getPart("file");
String contentType = filePart.getContentType();
// Handle file based on MIME type
} }
• Dynamic Content Generation: Servlets can dynamically generate content of
various MIME types based on the request context or application logic.
Example: Serving JSON data
response.setContentType("application/json");
PrintWriter out = response.getWriter();
out.println("{\"message\": \"Hello, World!\"}");
• Content Negotiation: Content negotiation involves the server selecting an
appropriate content representation based on the client's Accept header.
Example:
String accept = request.getHeader("Accept");
if (accept.contains("application/json")) {
response.setContentType("application/json");
response.getWriter().println("{\"message\": \"Hello, JSON!\"}");
} else {
response.setContentType("text/html");
response.getWriter().println("<h1>Hello, HTML!</h1>");
}

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

MIME Types and Security

• Preventing MIME Sniffing: Browsers sometimes try to determine the MIME type
by inspecting the content (MIME sniffing). This can lead to security vulnerabilities
if the content type is misinterpreted.
Example: Serving user-uploaded files
response.setHeader("X-Content-Type-Options", "nosniff");
• Cross-Site Scripting (XSS): Setting the correct MIME type is crucial to prevent XSS
attacks. For example, serving user-uploaded HTML files as plain text to prevent
execution.
Example:
response.setContentType("text/plain");
response.getWriter().println(userUploadedHtmlContent);

Practical Considerations

• File Downloads: Setting the correct MIME type when serving file downloads
ensures that browsers handle the files appropriately.
Example:
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment;
filename=\"download.pdf\"");
// Write file content to response output stream
• Handling Multiple MIME Types: Applications often need to handle multiple
MIME types, such as uploading images, serving JSON data, or dynamically
generating HTML.
Example:
if (contentType.equals("image/png")) {
// Handle PNG file
} else if (contentType.equals("application/json")) {
// Handle JSON data
} else {
// Default handling
}

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Example: Create an Eclipse project for MIME implementation in a servlet

FileUploadServlet.java
package com.example;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

@WebServlet("/upload")
@MultipartConfig
public class FileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doPost(HttpServletRequest request, HttpServletResponse


response) throws ServletException, IOException {
response.setContentType("text/html"); // Setting the content type of the
response
// Handling file upload
Part filePart = request.getPart("file"); // Retrieves <input type="file"
name="file">
String contentType = filePart.getContentType(); // Getting the MIME type of
the uploaded file
// Processing file based on its MIME type
if (contentType.equals("image/jpeg")) {
response.setContentType("image/jpeg"); // Setting content type to
image/jpeg
InputStream fileContent = filePart.getInputStream();
// Process the image fileContent and return it as a response
// For simplicity, let's just echo the image back

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

OutputStream out = response.getOutputStream();


byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = fileContent.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
out.close();
} else {
// For other MIME types, just return a simple text response
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<body>");
out.println("<h1>File uploaded successfully!</h1>");
out.println("<p>MIME type: " + contentType + "</p>");
out.println("</body>");
out.println("</html>");
}
}
}

index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>File Upload</title>
</head>
<body>
<h2>File Upload Form</h2>
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" /><br><br>
<input type="submit" value="Upload" />
</form>
</body>
</html>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID"
version="4.0">
<display-name>checkpro</display-name>
<servlet>
<servlet-name>FileUploadServlet</servlet-name>
<servlet-class>com.example.FileUploadServlet</servlet-class>
</servlet>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>

Run the Project

• Right-click on the project > Run As > Run on Server.


• Choose the appropriate server (e.g., Apache Tomcat).

Test the Application:

Open a web browser and navigate through the below url to use the form to upload a file
and observe the response based on the file's MIME.
http://localhost:8080/MIMEExampleProject/upload.html

The above project demonstrates MIME type handling in a servlet, with the ability to
upload files and respond differently based on the file's MIME type.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Best Training Institute
for Graduates
with
Live Online & Offline Classes Available

Join us for Better Career and Job Guarantee

Full Stack Web Development


Top Edge (MERN Stack) HTML, CSS, JavaScript, ES,
Git, ReactJS, Node, Express, MySQL & MongoDB

Training Full Stack Engineer


Java, JavaScript, ReactJS, Spring, SpringBoot
Hibernate, Linux, AWS, Git, DevOps & Jira

Programs Digital Marketing


Social Media, Website Design, SEO,
Google Ads, Freelancing & Many More

Guaranteed Package (In Writing)


▪ 3-5 Lakhs (With 6 Months Training Programs)
▪ 6-8 Lakhs (With 12 Months Training Programs)
▪ 10 Lakhs+ (With 2 Years Training Programs)

Amenities
▪ Digital Notes ▪ Working Experience
▪ Live Training Sessions ▪ Job Recommendations
▪ Project Assistance ▪ Professional Development
▪ Interview Preparation ▪ Digital Resume & Portfolio

LEARN-2-EARN LABS TRAINING INSTITUTE


Anna Icon Complex, near Kargil Petrol Pump, Sikandra-Bodla Road, Sikandra, Agra
Website : www.LearntoearnLabs.com
Call : 91-9548868337 / +91-9837705705
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Java Server Pages (JSP)


• Java Server Pages (JSP) is a technology used for creating dynamic web content.
• It is part of the Java EE (Enterprise Edition) platform and is used primarily for
developing web-based applications.
• JSP allows developers to embed Java code directly into HTML pages using special
JSP tags.
• This makes it easier to create dynamic content compared to using Java Servlets
alone, as it allows for a clear separation of business logic from presentation. Servlet
is best suited for executing processing logics, while JSP is used for creating dynamic
web pages and executing presentation logics rather than processing logics.
• It is an extension of servlet in which we can use implicit objects, custom tags and
predefined tags.
• JSP is slower than servlet, because the JSP page is first translated into servlet and
then get executed. While JSPs are converted into Servlets and thus can ultimately
perform similarly to Servlets after the initial compilation, the initial overhead
associated with this conversion, the complexity of mixed content, and the
additional processing steps involved in rendering JSP pages can make Servlets
faster in practice.
• In JSP, we write java code inside html.
• For performance-critical applications, Servlets are often preferred for their direct
execution path and straightforward lifecycle management. While, JSPs offer a
significant advantage in terms of ease of development and maintainability for
dynamic web content, making them a valuable tool despite the initial performance
trade-offs.

Java Server Pages (JSP): Key Features

• Ease of Use: Embeds Java code directly within HTML using JSP tags, which
simplifies the development process for creating dynamic web pages.
• Separation of Concerns: Separates the presentation layer from the business logic
layer, making the code more modular and maintainable.
• Reusability: Provides mechanisms like custom tags and tag libraries to
encapsulate and reuse common functionality.
• Integration: Can easily integrate with JavaBeans and Enterprise JavaBeans (EJB) for
business logic and data manipulation.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

• Session Management: Built-in support for session management to track user


interactions across multiple requests.
• Expression Language (EL): Simplifies access to data stored in JavaBeans and other
objects, without the need for explicit Java code.

Servlet Vs JSP – Key Differences

• Servlets and JSPs are both essential components of Java web applications but serve
different purposes.
• Servlets are more suited for handling complex request processing and business
logic, whereas JSPs are ideal for creating dynamic, user-friendly web pages.
• Together, they can be used to build robust and scalable web applications,
leveraging the strengths of each technology to address different aspects of web
development.
• In MVC architecture, JSP acts as a view part & servlets acts as a controller part.
• In servlets we are mixing both presentation logics and business logics but in JSP
we can separate our business logics with presentation logics.
• We must place the servlets in private area of directory structure so to access the
private area elements, web.xml is mandatory but we can place the JSP pages in
both public & private areas, so for accessing the JSP page, web.xml is optional.
• The servlets predefined support servlet-api.jar & JSP predefined support jsp-api.jar.

Let’s discuss the key difference between Servlet & JSP in detail:

1. Purpose and Use Case


Servlets
• Primarily used to handle and process HTTP requests and generate
responses.
• More suited for request handling, business logic processing, and interacting
with databases.
• Typically involves writing Java code for generating HTML content
dynamically.
JSP
• Primarily used for creating the presentation layer (i.e., the user interface).
• More suited for generating dynamic web content and combining static
HTML with dynamic Java code.
• Allows embedding Java code within HTML pages using JSP tags.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

2. Development Complexity
Servlets
• Require a deeper understanding of Java and HTTP protocols.
• Involves writing a lot of Java code to generate HTML, making it cumbersome
for complex UI development.
JSP
• Simplifies the creation of dynamic web pages by embedding Java code
directly into HTML.
• Easier to develop and maintain due to the separation of HTML
(presentation) from Java code (logic).
3. Compilation and Lifecycle
Servlets
• Compiled into bytecode and loaded into the server memory as a part of the
web application.
• Follow a strict lifecycle: init(), service(), and destroy() methods.
JSP
• Initially compiled into Servlets by the JSP engine, and then the Servlet
lifecycle applies.
• JSP pages are translated into Java Servlets once, and subsequent requests
are handled by the compiled Servlet.
4. Code Structure
Servlets
• Entirely written in Java, with HTML content being generated via print
statements or similar mechanisms.
JSP
• Mixes HTML with special JSP tags (<% %>, <%= %>, etc.) to insert Java code
directly.
• Supports JSP directives, scriptlets, and expressions to include Java logic
within HTML.
5. Maintainability
Servlets
• Harder to maintain for complex UIs because of the intermingling of Java
code with HTML content.
JSP
• Easier to maintain and modify as the HTML content is more directly readable
and separable from the Java code.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

6. Expression Language (EL) and JSTL


Servlets
• Do not natively support EL or JSTL (JavaServer Pages Standard Tag Library).
JSP
• Supports EL and JSTL, which simplify access to application data and reduce
the amount of Java code needed within JSP pages.

How Servlet is faster than JSP?

Servlets are generally faster than JSPs due to several reasons related to their nature and
execution process:

1. Compilation Overhead
Servlets: When you write and deploy a Servlet, it is compiled into Java bytecode
directly by the developer and deployed on the server.
JSP: When a JSP page is accessed for the first time, it goes through an initial
translation phase where the JSP engine converts the JSP page into a Servlet. This
Servlet is then compiled into Java bytecode. This initial translation and compilation
phase introduces additional overhead, which makes JSP slower on the first request.

2. Execution Path
Servlets: Directly execute the compiled Java code when handling HTTP requests.
This direct execution is very efficient.
JSP: After the initial translation and compilation to a Servlet, JSP pages execute the
compiled Servlet code. However, this involves an extra step compared to a pre-
compiled Servlet, making the initial execution slower.

3. Separation of Concerns
Servlets: Since Servlets are pure Java classes, they have a single responsibility of
handling HTTP requests and responses. They don't mix HTML with Java code, which
simplifies the execution path.
JSP: JSPs mix Java code with HTML, which necessitates additional parsing and
processing steps during the initial translation to Servlets.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

4. Optimizations and Caching


Servlets: Because Servlets are pre-compiled and often loaded into memory upon
server startup, they benefit from optimizations and caching mechanisms provided
by the servlet container. This can lead to faster response times for subsequent
requests.
JSP: Although JSPs are eventually compiled into Servlets and can be cached, they
do not benefit from these optimizations until after the initial compilation.
Additionally, changes to JSP files require re-compilation, which can introduce
additional overhead during development.

5. Lifecycle Management
Servlets: Have a well-defined lifecycle managed by the servlet container (init(),
service(), destroy()). This lifecycle management ensures efficient resource allocation
and cleanup, contributing to better performance.
JSP: Inherits the Servlet lifecycle but with the added complexity of JSP-specific
initializations, which can introduce slight performance overhead.

6. Error Handling and Debugging


Servlets: Easier to debug and optimize because they are pure Java code. Developers
have full control over the code, making it easier to identify and fix performance
bottlenecks.
JSP: Debugging can be more challenging due to the mixed nature of Java and
HTML, and errors during the translation phase can complicate the debugging
process.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Java Server Pages (JSP): Life Cycle

The life cycle of a JavaServer Page (JSP) describes the process a JSP undergoes from
creation to destruction within a JSP container. The JSP life cycle is similar to that of a
Servlet because a JSP is ultimately compiled into a Servlet.

Let’s discuss the key phases of JSP life cycle

1. Translation Phase : The JSP engine translates the JSP file into a Servlet source file.
• Parsing: The JSP file is parsed, and the static HTML and JSP elements (like
scriptlets, expressions, and directives) are identified.
• Translation: The JSP elements are converted into equivalent Java code to
form a Servlet class.
2. Compilation Phase : The generated Servlet source file (from the translation phase)
is compiled into a Java bytecode class file.
• Compilation: The JSP engine invokes the Java compiler to compile the
generated Servlet source file into bytecode.

3. Loading and Initialization Phase : The compiled Servlet class is loaded into
memory and initialized.
• Class Loading: The JSP container loads the compiled Servlet class using the
class loader.
• Instance Creation: An instance of the Servlet class is created.
• Initialization (jspInit Method): The jspInit() method is called once for the JSP
instance to perform any initialization tasks. This method is similar to the init()
method in a Servlet.

4. Request Processing Phase : The JSP handles client requests and generates
responses.
• Request Handling (_jspService Method): For each client request, the JSP
container invokes the _jspService() method of the JSP. This method is auto-
generated and contains the logic for handling requests, including
processing JSP elements and generating the HTML response.
• Response Generation: The JSP constructs the HTTP response based on the
processed JSP elements and any embedded Java code.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

5. Destruction Phase : The JSP is taken out of service, and any resources are released.
• Cleanup (jspDestroy Method): The jspDestroy() method is called before the
JSP instance is destroyed. This method allows the JSP to release any
resources it holds, such as closing database connections.

Understanding the JSP life cycle is crucial for developers to manage resources efficiently
and ensure optimal performance of JSP-based web applications.

Java Server Pages (JSP): Life Cycle Methods

1. jspInit() Method
• Invoked once when the JSP is first initialized.
• Used to perform any setup tasks, such as resource allocation or initialization
of instance variables.

2. _jspService(HttpServletRequest request, HttpServletResponse response) Method


• Called for each client request to the JSP.
• Handles the main logic for processing requests and generating responses.
• Cannot be overridden by developers; it is generated automatically by the
JSP engine.

3. jspDestroy() Method
• Called once when the JSP is about to be destroyed.
• Used to perform any cleanup tasks, such as releasing resources or saving
state.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Creating a JSP Project in Eclipse


Prerequisites
• Eclipse IDE for Java EE Developers: Ensure you have the version of Eclipse that
includes tools for Java EE development.
• Apache Tomcat: Install and configure Apache Tomcat or another servlet container.

By following the below steps, you will have a simple JSP project set up in Eclipse with a
single JSP file and a web.xml configuration file.

1. Open Eclipse.
• Go to File > New > Other....
• In the wizard, expand the Web folder and select Dynamic Web Project. Click
Next.
• Enter the project name (e.g., MyJSPProject).
• Click Next through the subsequent pages, accepting the default settings, until
you reach the final page. Ensure you have selected a target runtime (e.g.,
Apache Tomcat). Click Finish.

2. Set Up the Project Structure


The project will be created with a typical web project structure. You should see a
folder structure similar to this:
MyJSPProject/
├── WebContent/
│ ├── META-INF/
│ ├── WEB-INF/
│ │ ├── web.xml
└── src/

3. Create a JSP File


• Right-click on the WebContent folder.
• Go to New > JSP File.
• Enter the file name (e.g., index.jsp). Click Next and then Finish.
• Open index.jsp and add some basic content:

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

myjsp.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>JSP Page</title></head>
<body>
<h1>Learn2Earn Labs – Best Training Institute for graduates</h1>
</body>
</html>

4. Edit the web.xml File


• The web.xml file is located in the WebContent/WEB-INF folder.
• Open web.xml and configure it as follows:
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID"
version="4.0">
<display-name>jspex</display-name>
<welcome-file-list>
<welcome-file>myjsp.jsp</welcome-file>

</welcome-file-list>
</web-app>

5. Configure the Server


• Go to the Servers view in Eclipse. If it is not open, go to Window > Show View
> Servers.
• Right-click in the Servers view and select New > Server.
• Choose Apache Tomcat (or your servlet container) and configure it if necessary.
• Add your project to the server. Right-click on the server and select Add and
Remove..., then add your project to the Configured side. Click Finish.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

6. Run the Project


• Right-click on your project in the Project Explorer.
• Select Run As > Run on Server.
• Choose your configured server and click Finish.

7. Access Your JSP Page


• Once the server is running, open a web browser and navigate to
http://localhost:8080/MyJSPProject/.
• You should see your index.jsp file displaying " Learn2Earn Labs – Best Training
Institute for graduates".

Sample Example : Servlet Issue

Login.html
<html>
<body>
<form action="LoginServlet" method="POST">
User Name: <input type="text" name="username" /><br>
Password: <input type="text" name="password" /><br>
<input type="submit" value="Sign In" />
</form>
</body>
</html>

Web.xml
<web-app>
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class> com.java.example.LoginServlet</servlet-class>
</servlet>
<welcome-file-list>
<welcome-file>login.html</welcome-file>
</welcome-file-list>
</web-app>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

LoginServlet.java
package com.java.example;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public LoginServlet() { }

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
doPost(request, response);
}

protected void doPost(HttpServletRequest request, HttpServletResponse


response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String username = request.getParameter("username");
String password = request.getParameter("password");
System.out.println("User Name:"+username);
System.out.println("Password:"+password);

if(username.equals("nitin") && password.equals("123")){


//Rendering success response on browser.
out.println("<html><body>");
out.println("<h1><font color=\"green\"/>Successfully logged in
at:"+ new Date()+"</h1>");
out.println("</body></html>");
}

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

else{
//Rendering failure response to browser.
out.println("<html><body>");
out.println("<h1><font color='red'/>Invalid Username or
Password.</h1>");
out.println("</body></html>");
}
}
}

Conclusion
In the above example, Servlet class is used for:
1. Handling User Inputs.
2. Performing (or Invoking) Business Logic.
3. Presentation layer (Rendering response on browser).

Disadvantages
1. Writing html code inside the servlets is not recommended.
2. The page author must have knowledge in Java programming who write the html
code.
3. For every change servlet gets recompiled.
4. Servlets can't get accessed directly, so we need to have web.xml file configuration.

Developing same application by using JSP


It is always to recommended to separate both business logics & presentation logics,
hence JSP were introduced.

LoginServlet.java
package com.java.example;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public LoginServlet() { }

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
doPost(request, response);
}

protected void doPost(HttpServletRequest request, HttpServletResponse


response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String username = request.getParameter("username");
String password = request.getParameter("password");
System.out.println("User Name:"+username);
System.out.println("Password:"+password);

//Perform (or Invoke) Business Logic


if(username.equals("nitin") && password.equals("123"))
{
//Invoke Success response page.
RequestDispatcher rd = request.getRequestDispatcher("/Success.jsp");
rd.forward(request, response);
}

else
{
//Invoke Failure response page.
RequestDispatcher rd = request.getRequestDispatcher("/Failure.jsp");
rd.forward(request, response);
}
}

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Success.jsp
<%@ page import="java.util.Date" %>
<html>
<body>
<h1><font color="green"/>Successfully logged in at:<%= new Date()%></h1>
</body>
</html>

Failure.jsp
<html>
<body>
<h1><font color="red"/>Invalid Username or Password</h1>
</body>
</html>

Conclusion
Now, Servlet class is used for
1. Handle User Inputs
2. Perform (or Invoke) Business logic
3. Control View navigation

Advantages with JSP


1. JSPs are tag-based approach, hence, convenient for page authors.
2. We can use IDEs such as Dreamweaver & other UI Design platforms for designing
JSP pages.
3. JSPs are automatically compiled by the web container.
4. JSPs can be accessed directly without web.xml.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Java Server Pages (JSP) : Elements

• A JSP (JavaServer Pages) file can contain a variety of elements that combine static
content (like HTML, CSS, and JavaScript) with dynamic content generated by
embedded Java code.
• These elements enable JSP to create dynamic web pages efficiently.
• A JSP file can contain various elements such as directives, scriptlets, expressions,
declarations, standard HTML, JSP actions, expression language (EL), JSP standard
tag library (JSTL), and custom tags.
• These elements collectively enable the creation of dynamic and interactive web
pages by combining static HTML with dynamic Java code.

Let's gain a deep understanding of the various JSP elements:

1. Directives : Directives provide global information about the JSP page and are used
to set page-level settings. They do not produce any output.
• Page Directive: Defines page-specific attributes like content type,
language, error page, etc.
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
• Include Directive: Includes a file during the translation phase.
<%@ include file="header.jsp" %>
• Taglib Directive: Declares a tag library that the JSP page uses.
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

2. Scriptlets : Scriptlets contain Java code that is executed every time the JSP page is
requested. The code is inserted into the _jspService method of the generated
Servlet.
<%
int count = 0;
count++;
%>

3. Expressions : Expressions are used to output the value of a Java expression directly
to the client’s browser. The result is converted to a string and inserted into the
output stream.
<%= new java.util.Date() %>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

4. Declarations : Declarations define instance variables and methods that get added
to the Servlet class. These are initialized only once when the Servlet is instantiated.
<%!
private int counter = 0;
public int getCounter() { return counter; }
%>

5. Standard HTML : JSP pages can include regular HTML code, which forms the static
content of the web page.
<html>
<head><title>Sample JSP Page</title></head>
<body>
<h1>Welcome to my JSP page</h1>
</body>
</html>

6. Expression Language (EL) : EL simplifies the accessibility of data stored in


JavaBeans components, usually in the scope of request, session, or application. It
can be used to get and set properties without explicit Java code.
${user.name}

7. JSP Standard Tag Library (JSTL) : JSTL provides a set of tags to handle common
tasks in JSPs, like iteration, conditionals, XML processing, internationalization, and
more.

• Core Tags:
<c:if test="${param.someParam == 'value'}">
<p>Conditional content</p>
</c:if>
or
<c:forEach var="item" items="${items}">
<p>${item}</p>
</c:forEach>

• Formatting Tags:
<fmt:formatNumber value="${price}" type="currency" />

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

• SQL Tags:
<sql:query var="result" dataSource="${dataSource}">
SELECT * FROM users
</sql:query>

8. Custom Tags : Custom tags are user-defined tags created by extending the JSP
tag libraries. They help encapsulate complex behaviors into reusable components.
<mytags:customTag attribute="value" />

9. Implicit Objects : JSP provides a set of implicit objects that are automatically
available to developers without needing to declare them.
These include:
• request: Represents the HttpServletRequest object.
• response: Represents the HttpServletResponse object.
• out: Used to send content to the client (instance of JspWriter).
• session: Represents the HttpSession object associated with the request.
• application: Represents the ServletContext object.
• config: Represents the ServletConfig object.
• pageContext: Provides access to all namespaces associated with a JSP page.
• page: Represents the instance of the JSP page itself (similar to this in a Java
class).
• exception: Used for error pages to represent the uncaught exception.

Java Server Pages (JSP) : Comments

JSP (JavaServer Pages) comments are used to insert remarks or notes within JSP files.
There are two main types of comments in JSP: JSP comments and HTML comments. Each
type serves a different purpose and behaves differently at runtime and when viewed in
the client’s browser.

1. JSP Comments
JSP comments are used to insert comments that are not included in the HTML
output sent to the client. These comments are processed by the JSP engine and
are stripped out during the translation phase, making them useful for leaving notes
and explanations for developers without affecting the client-side content.
Syntax
<%-- This is a JSP comment --%>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Characteristics
• Not Sent to Client: JSP comments are removed during the translation
phase, so they do not appear in the HTML source code sent to the client.
• Invisible in Browser: Since they are stripped out during translation, they
are completely invisible to anyone viewing the page source in a web
browser.
• Used for Documentation: Ideal for leaving notes, explanations, or
documentation within the JSP file that is intended for developers or
maintainers.

Example
<%-- This is a JSP comment and will not be visible in the HTML source --%>
<%
// Some Java code here
%>
<html>
<head><title>Sample JSP Page</title></head>
<body>
<h1>Welcome to my JSP page</h1>
</body>
</html>

2. HTML Comments
HTML comments are standard HTML comments that can be included in a JSP file.
These comments are sent to the client as part of the HTML output and can be
viewed by anyone who views the page source in a web browser.
Syntax
<!-- This is an HTML comment -->

Characteristics
• Sent to Client: HTML comments are included in the HTML output and sent
to the client’s browser.
• Visible in Browser: These comments can be seen by anyone viewing the
page source in the browser.
• Used for Client-Side Notes: Useful for leaving notes or explanations in the
HTML source code that might be useful for web designers or developers
inspecting the page in the browser.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Example
<%-- This is a JSP comment --%>
<html>
<head>
<title>Sample JSP Page</title>
</head>
<body>
<!-- This is an HTML comment and will be visible in the HTML source -->
<h1>Welcome to my JSP page</h1>
</body>
</html>

Usage Considerations

• Performance: JSP comments do not affect the size of the response sent to the
client, which can be beneficial for performance, especially when the comments are
extensive.
• Security: Because JSP comments are not visible to the client, they can be used to
leave sensitive implementation details or debugging information without exposing
them to users.
• Code Maintenance: Using comments effectively can improve code readability and
maintainability, providing context and explanations for complex logic or important
sections of the JSP file.

Best Practices

• JSP Comments for Server-Side Notes: Use JSP comments for internal
documentation, such as explaining complex code logic, leaving notes for future
developers, or marking TODOs.
• HTML Comments for Client-Side Notes: Use HTML comments sparingly for
client-side notes, such as reminders for web designers or comments that might
assist with browser-side debugging.
• Avoid Sensitive Information in HTML Comments: Since HTML comments are
visible to anyone viewing the source code, avoid placing sensitive information or
internal logic explanations in HTML comments.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

JSP Scriptlet
• JSP Scriptlets are used to embed Java code directly within a JSP page.
• This allows for dynamic content generation and server-side logic execution within
the web page.
• Scriptlets are a key part of the JSP technology, enabling the creation of dynamic
web applications by embedding Java code within HTML.
• JSP Scriptlets are a powerful feature for embedding Java code directly within a JSP
page. While they provide flexibility and control over the page content, it’s
important to use them judiciously to maintain clean and maintainable code.

JSP Scriptlet Syntax


A scriptlet is enclosed within <% and %> tags. The Java code inside these tags is inserted
into the _jspService method of the generated servlet.

Syntax
<%
// Java code here
%>

Characteristics of JSP Scriptlet


• Embedded Java Code: The Java code written within the scriptlet tags is executed
on the server side.
• Output to Client: The result of the scriptlet can be output to the client, typically
by modifying the response object or writing directly to the response writer.
• Access to Implicit Objects: Scriptlets can access implicit objects like request,
response, session, application, out, config, pageContext, page, and exception.

Usage of Scriptlets
Scriptlets are used for performing server-side computations, accessing databases,
controlling page flow, and interacting with JavaBeans and other server-side components.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Example
<html>
<head><title>Scriptlet Example</title></head>
<body>
<%
// Java code block inside a scriptlet
String message = "Learn2Earn Labs Training Institute";
out.println("<h1>" + message + "</h1>");
%>
</body>
</html>

In the above example, a Java string message is created, and its value is written to the
HTML output using out.println.

Example with Conditional Logic


<html>
<head><title>Conditional Scriptlet Example</title></head>
<body>
<h1>Welcome to My Web Page</h1>
<%
// Java code to check the time of day
java.util.Date date = new java.util.Date();
int hours = date.getHours();

if (hours < 12) {


out.println("<p>Good morning!</p>");
} else if (hours < 18) {
out.println("<p>Good afternoon!</p>");
} else {
out.println("<p>Good evening!</p>");
}
%>
</body>
</html>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Another Example
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head><meta charset="ISO-8859-1"><title>JSP Page</title></head>
<body>
<%
for(int i=0;i<10;i++){
out.println("Hello students");
%>
<br>
<%
}
%>

</body>
</html>

Example Using Implicit Objects


<html>
<head><title>Implicit Objects Example</title></head>
<body>
<%
// Get a parameter from the request
String name = request.getParameter("name");

if (name == null || name.isEmpty()) {


out.println("<p>Please provide your name.</p>");
} else {
out.println("<p>Hello, " + name + "!</p>");
}
%>
</body>
</html>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

JSP Expression
• JSP (JavaServer Pages) expressions are used to embed Java code within HTML in a
JSP file.
• JSP expressions are a useful tool for embedding Java code within HTML, but they
should be used judiciously.
• They allow you to dynamically generate content for web pages.
• For more complex applications, consider using a framework that separates
concerns and maintains cleaner code.
• the code inside the JSP Expression is passed as a parameter to the out.print()
method.

Syntax
The syntax for a JSP expression is:
<%= expression %>

How It Works

• The expression is evaluated, converted to a string, and inserted in the HTML output.
• Expressions can include variables, method calls, or any valid Java code that returns
a value.

Example
Here’s a basic example of using JSP expressions:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>


<html>
<head>
<title>JSP Expression Example</title>
</head>
<body>
<h1>Welcome to JSP!</h1>
<p>Current date and time: <%= new java.util.Date() %></p>
<p>2 + 3 = <%= 2 + 3 %></p>
<p>Username: <%= request.getParameter("username") %></p>
</body>
</html>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Breakdown of the Example

• Date Example
<%= new java.util.Date() %>
This expression creates a new Date object and inserts the current date and time.

• Arithmetic Example
<%= 2 + 3 %>
This evaluates the expression 2 + 3 and displays 5.

• Request Parameter Example


<%= request.getParameter("username") %>
This retrieves the value of a request parameter named username from the query
string or form data and displays it.

Points to Remember
• No Semicolon: Unlike regular Java code, expressions do not end with a semicolon.
• Implicit Objects: JSP expressions can use several implicit objects like request,
response, session, application, out, etc.
• Type Safety: The result of the expression should be convertible to a string.

Advantages
• Simplicity: Embedding Java code directly in HTML can simplify dynamic content
generation.
• Readability: Short and straightforward expressions improve code readability.

Disadvantages
• Maintainability: Mixing Java code and HTML can make code harder to maintain,
especially in large projects.
• Logic Separation: It's often better to separate business logic from presentation
using JavaBeans or MVC frameworks.

Best Practices
• Use JSP expressions sparingly to maintain separation between logic and
presentation.
• Prefer using JavaBeans or custom tags for complex logic.
• Use MVC frameworks like Spring or Struts to separate concerns more effectively.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

JSP Expression : Additional Examples

Example : Concatenating Strings


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>String Concatenation</title>
</head>
<body>
<h1>Concatenated String</h1>
<p><%= "Hello, " + "world!" %></p>
</body>
</html>

Example : Displaying User Agent


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>User Agent</title>
</head>
<body>
<h1>Your User Agent</h1>
<p><%= request.getHeader("User-Agent") %></p>
</body>
</html>

Example : Calculating Square of a Number


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Square Calculation</title>
</head>
<body>
<h1>Square of 5</h1>
<p><%= 5 * 5 %></p>
</body>
</html>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Example : Displaying Current Year


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Current Year</title>
</head>
<body>
<h1>Year</h1>
<p>Current Year: <%=
java.util.Calendar.getInstance().get(java.util.Calendar.YEAR) %></p>
</body>
</html>

Example : Formatting a Number


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Number Formatting</title>
</head>
<body>
<h1>Formatted Number</h1>
<p><%= String.format("%.2f", 12345.6789) %></p>
</body>
</html>

Example : Displaying Environment Variables


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Environment Variables</title>
</head>
<body>
<h1>Java Version</h1>
<p><%= System.getProperty("java.version") %></p>
</body>
</html>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Example : Boolean Expression


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Boolean Check</title>
</head>
<body>
<h1>Is 10 Greater Than 5?</h1>
<p><%= 10 > 5 %></p>
</body>
</html>

Example : Conditional Message


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Conditional Message</title>
</head>
<body>
<h1>Access Level</h1>
<p><%= user.isAdmin() ? "Admin Access" : "User Access" %></p>
</body>
</html>

Example : Generating a Random Number


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Random Number</title>
</head>
<body>
<h1>Random Number</h1>
<p><%= Math.random() %></p>
</body>
</html>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Example : Capitalizing Input


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Capitalize Input</title>
</head>
<body>
<h1>Capitalized Input</h1>
<p><%= request.getParameter("name").toUpperCase() %></p>
</body>
</html>

Example : Displaying Server Name and Port


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Server Information</title>
</head>
<body>
<h1>Server Details</h1>
<p>Server Name: <%= request.getServerName() %></p>
<p>Server Port: <%= request.getServerPort() %></p>
</body>
</html>

Example : Formatting Date


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Formatted Date</title>
</head>
<body>
<h1>Current Date</h1>
<p><%= new java.text.SimpleDateFormat("EEEE, MMMM d, yyyy").format(new
java.util.Date()) %></p>
</body>
</html>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

JSP Declarations
• JSP declarations are used to declare variables and methods that can be used in the
JSP page.
• Unlike expressions and scriptlets, declarations allow you to define reusable
components that persist throughout the JSP file.
• JSP declarations are powerful for defining methods and variables that can be
reused within a JSP page.
• However, to maintain cleaner and more maintainable code, consider using
JavaBeans or adopting an MVC framework, especially for larger applications.
• JSP declarations are used to declare variables, methods, java classes, etc.
• The code statements written inside JSP Declaration, exist outside the service
method servlet.

Syntax
The syntax for a JSP declaration is:
<%! declaration %>

How It Works

• Code within the <%! %> tags is placed in the servlet’s class body.
• It can include fields, methods, or initialization blocks.
• Declarations are evaluated once when the JSP is compiled.

Example
Here’s a basic example of JSP declarations:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head> <title>JSP Declaration Example</title></head>
<body>
<h1>Using JSP Declarations</h1>
<%! // Declaration of a field
String message = "Hello from JSP Declaration!";
public int addNumbers(int a, int b) { // Declaration of a method
return a + b;
}
%>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

<p>Sum of 10 and 20 is: <%= addNumbers(10, 20) %></p>


<p>Message: <%= message %></p>
</body>
</html>

Breakdown of the Example

• Field Declaration
String message = "Hello from JSP Declaration!";
This declares a field message that can be used anywhere in the JSP.

• Method Declaration
public int addNumbers(int a, int b) {
return a + b;
}
This declares a method addNumbers() that takes two integers and returns their
sum. It can be called within expressions.

Points to Remember

• Scope: Variables and methods declared are available throughout the JSP page.
• Initialization: Declarations are initialized only once when the JSP is compiled.
• No HTML Output: Declarations do not produce HTML output directly.

Advantages

• Reusability: Methods and variables can be reused multiple times within the page.
• Cleaner Code: Helps keep JSP code cleaner by separating logic from HTML.

Disadvantages

• Code Mixing: Embedding too much Java logic in JSP can lead to maintainability
issues.
• Less Structure: Excessive use can lead to a less structured codebase compared to
using JavaBeans or MVC patterns.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

JSP Declaration : Additional Examples

Example: Static Variables and Methods


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head> <title>Static Example</title> </head>
<body>
<h1>Static Counter</h1>
<%! // Static variable
static int counter = 0;
public static int incrementCounter() { // Static method
return ++counter;
}
%>
<p>Counter: <%= incrementCounter() %></p>
</body>
</html>

Example : Array Initialization


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head> <title>Array Example</title> </head>
<body>
<h1>Color List</h1>
<%!
String[] colors = {"Red", "Green", "Blue", "Yellow"}; // Array declaration
%>
<ul>
<% for (String color : colors) { %>
<li><%= color %></li>
<% } %>
</ul>
</body>
</html>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Example : Utility Methods


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head> <title>Utility Methods</title></head>
<body>
<h1>String Reversal</h1>
<p>Original: Hello</p>
<%! // Method to reverse a string
public String reverseString(String input) {
return new StringBuilder(input).reverse().toString();
}
%>
<p>Reversed: <%= reverseString("Hello") %></p>
</body>
</html>

Example : Simple Logging Mechanism


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head> <title>Logging Example</title></head>
<body>
<h1>Logging Messages</h1>
<%! // Method to log a message
public String logMessage(String message) {
System.out.println("Log: " + message);
return "Message logged successfully.";
}
%>
<p><%= logMessage("This is a test log message.") %></p>
</body>
</html>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Example : String Length


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>String Length</title>
</head>
<body>
<h1>String Length</h1>
<%! // Method to get the length of a string
public int getStringLength(String input) {
return input.length();
}
%>
<p>Length of 'Hello World': <%= getStringLength("Hello World") %></p>
</body>
</html>

Example : Generating Random Numbers


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Random Number Generator</title>
</head>
<body>
<h1>Random Number</h1>
<%! // Method to generate a random number between min and max
public int getRandomNumber(int min, int max) {
return (int) (Math.random() * (max - min + 1)) + min;
}
%>
<p>Random number between 1 and 100: <%= getRandomNumber(1, 100)
%></p>
</body>
</html>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Example : Greeting Based on Time


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Greeting</title>
</head>
<body>
<h1>Greeting</h1>
<%! // Method to return a greeting based on the current time
public String getGreeting() {
int hour =
java.util.Calendar.getInstance().get(java.util.Calendar.HOUR_OF_DAY);
if (hour < 12) {
return "Good Morning!";
} else if (hour < 18) {
return "Good Afternoon!";
} else {
return "Good Evening!";
}
}
%>
<p><%= getGreeting() %></p>
</body>
</html>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

JSP Directives
• JSP directives provide global information about an entire JSP page and are used to
control the processing of the page.
• Directives do not produce any output but affect the overall structure of the servlet
generated from the JSP.
• These directives help structure JSP applications effectively, improving
maintainability and reusability.

Reasons of using Directives in JSP

We use directives in JSP for several important reasons:

1. Configuration Control
Page Behavior: Directives allow you to set attributes that influence the entire JSP
page, such as session management, content type, and buffering.
Error Handling: Directives can specify error pages to handle exceptions gracefully.
2. Code Reusability
Include Directive: This directive lets you include static resources or other JSP files,
promoting code modularity and reuse.
Common Layouts: You can maintain consistent headers, footers, or navigation
menus across multiple pages.
3. Integration with Tag Libraries
Custom Tags: The taglib directive allows you to incorporate custom tag libraries
(like JSTL), which enhance the functionality of JSP pages and simplify the coding of
common tasks.
4. Performance Optimization
Buffering: You can control output buffering, which can improve performance by
reducing the number of times the output stream is flushed.
Session Management: By controlling session usage, you can manage resources
more efficiently.
5. Importing Java Classes
Java Classes and Packages: The page directive allows the import of Java classes,
making it easier to use Java functionality directly within the JSP page.
6. Simplified Maintenance
Centralized Configuration: Directives enable centralized configuration for page
settings, making it easier to maintain and update the application.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Types of JSP Directives

• Page Directive: Configures page-level settings such as imports, session usage, and
error handling.
• Include Directive: Includes the content of other files at compile time, useful for
modularizing JSPs.
• Taglib Directive: Declares tag libraries for using custom tags, enhancing the
functionality of JSPs.

Detailed Overview of Each Directive

• Page Directive
Purpose: Defines page-level attributes.
Example:
<%@ page contentType="text/html;charset=UTF-8" import="java.util.List"
session="true" %>
Use Cases:
▪ Specifying the MIME type and character encoding.
▪ Importing Java classes.
▪ Controlling session behavior.
▪ Setting error handling pages.

• Include Directive
Purpose: Includes static resources or other JSP files at compile time.
Example:
<%@ include file="header.jsp" %>
Use Cases:
▪ Reusing common page components like headers and footers.
▪ Modularizing JSP pages for better organization.

• Taglib Directive
Purpose: Declares custom tag libraries for use in the JSP page.
Example:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
Use Cases:
▪ Utilizing JSTL or other custom tags to simplify complex tasks.
▪ Improving code readability and maintainability by replacing scriptlets
with tags.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Best Practices

• Use directives to manage page settings and include reusable components.


• Use the taglib directive to incorporate powerful tag libraries like JSTL, promoting
cleaner and more maintainable JSP code.
• Limit the use of page directives to only what’s necessary for the page's
requirements.

Benefits of Using Directives


• Flexibility: Directives provide the ability to customize the JSP page environment to
suit specific needs.
• Modularity: By including reusable components and tag libraries, directives promote
modular development.
• Performance: Proper use of directives can optimize resource usage, such as
controlling buffer sizes and session management.
• Maintainability: Centralized configurations and reusable components make the
application easier to maintain.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

JSP Page Directives


• Page directives in JSP are used to provide global information about an entire JSP
page and control its behaviour.
• They enhance performance, ensure proper error handling, and allow for the reuse
of common Java functionality within JSP pages.
• By setting attributes such as content type, imports, session management, and error
handling, developers can control how the JSP interacts with clients and the server.
• Page directives in JSP provide extensive control over various aspects of page
behaviour and environment setup.
• By utilizing the page directive attributes effectively, developers can optimize
performance, ensure compatibility, manage session handling, and maintain clean
and efficient code.
• Each attribute serves specific purposes that contribute to the overall functionality
and usability of JSP applications.

Syntax
<%@ page attribute="value" %>

Common Attributes and Use Cases

1. contentType
Description: Sets the MIME type and character encoding of the response.
Use Case: Ensures the correct display of text in browsers.
Example:
<%@ page contentType="text/html;charset=UTF-8" %>
The default value of this attribute is text/html.

2. import
Description: Imports Java classes or packages.
Use Case: Allows use of Java classes directly in JSP.
Example:
<%@ page import="java.util.List, java.util.ArrayList" %>
The default values of this attribute are java.lang, javax.servlet, javax.servlet.http,
javax.servlet.jsp.
Note: Among all the JSP page attributes only import attribute is repeatable
attribute, no other attribute is repeatable.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

3. session
Description: Specifies whether the page uses a session.
Use Case: Manages session tracking based on application requirements.
Example:
<%@ page session="true" %>
It is a boolean attribute, it is used to give intimation to the container about to allow
or not to allow session implicit object into the present JSP page. The default value
of this attribute is true.

4. buffer
Description: Sets the size of the buffer used by the out (JspWriter) object.
Use Case: Optimizes performance by controlling output buffering.
Example:
<%@ page buffer="8kb" %>
Note: Jsp technology is having its own writer object to track the generated dynamic
response, JspWriter will provide very good performance when compared with
PrintWriter in servlets.

5. bufferSize
Description: Sets the initial size of the buffer used for the response.
Use Case: Controls the amount of data buffered before sending it to the client.
Example:
<%@ page bufferSize="8192" %>

6. autoFlush
Description: Specifies whether the buffer should be flushed automatically when full.
Use Case: Controls buffer flushing behaviour to handle large outputs.
Example:
<%@ page autoFlush="true" %>
Note:
• It is a boolean attribute, it can be used to give an intimation to the container
about to flush or not to flush dynamic response to client automatically when
JspWriter buffer filled with the response completely.
• If autoFlush attribute value is true then container will flush the complete
response to the client from the buffer when it reaches its maximum capacity.
• If autoFlush attribute value is false then container will raise an exception
when the buffer is filled with the response.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

• if we provide 0kb as value for buffer attribute and false as value for
autoFlush attribute then container will raise an exception like
org.apache.jasper.JasperException:/myjsp.jsp(1,2) jsp.error.page.badCombo
• The default value of this attribute is true.

7. isThreadSafe
Description: Indicates if the page can handle multiple requests simultaneously.
Use Case: Ensures thread safety in shared resources.
Example:
<%@ page isThreadSafe="true" %>
Note:
• It is a boolean attribute, it can be used to give an intimation to the container
about to allow or not to allow multiple number of requests at a time into
the present JSP page.
• If we provide true as value to this attribute then container will allow multiple
number of requests at a time.
• If we provide false as value to this attribute then automatically container will
allow only one request at a time and it will implement SingleThreadModel
interface in the translated servlet.
• The default value of this attribute is true.
• Indicates whether the code in JSP already provides thread-safe (or) the
generated servlet class to provide thread-safe by implementing
SingleThreadModel interface.

8. errorPage
Description: Defines a custom error page for handling exceptions.
Use Case: Provides user-friendly error messages.
Example:
<%@ page errorPage="error.jsp" %>

9. isErrorPage
Description: Specifies whether the current page is an error page.
Use Case: Identifies a page as an error handler.
Example:
<%@ page isErrorPage="true" %>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Note:
• It is a boolean attribute, it can be used to give an intimation to the container
about to allow or not to allow exception implicit object into the present JSP
page.
• If we provide value as true to this attribute then container will allow
exception implicit object into the present JSP page.
• If we provide value as false to this attribute then container will not allow
exception implicit object into the present JSP page.
• The default value of this attribute is false.

10. language
Description: Defines the scripting language of the page (usually Java).
Use Case: Specifies the language used in scripting elements.
Example:
<%@ page language="java" %>

11. extends
Description: Specifies a superclass for the generated servlet.
Use Case: Allows custom servlet behavior by extending a specific class.
Example:
<%@ page extends="com.example.MyCustomServlet" %>
Where MyCustomServlet should be an implementation class to HttpJspPage
interface and should be a subclass to HttpServlet.

The default value of this attribute is HttpJspBase class because Java doesn't support
the multiple inheritance concept, then importing any other class to JSP page will
not work.

12. info
Description: Provides a description of the JSP page.
Use Case: Supplies information about the page, accessible via getServletInfo().
Example:
<%@ page info="This is a sample JSP page" %>
If we want to get the specified metadata programmatically then we have to use the
following method from Servlet interface.
public String getServletInfo()
The default value of this attribute is Jasper JSP2.2 Engine.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

13. pageEncoding
Description: Sets the character encoding for the JSP page itself.
Use Case: Ensures the JSP file is read with the correct encoding.
Example:
<%@ page pageEncoding="UTF-8" %>

14. isELIgnored
Description: Controls whether Expression Language (EL) expressions are processed.
Use Case: Allows disabling EL to prevent its evaluation in specific contexts.
Example:
<%@ page isELIgnored="true" %>
Note:
• It is a boolean attribute, it can be used to give an intimation to the container
about to allow or not to allow Expression Language syntaxes in the present
JSP page.
• Expression Language is a Scripting language, it can be used to eliminate java
code completely from the JSP pages.
• If isELIgnored attribute value is true then container will eliminate Expression
Language syntaxes from the present JSP page.
• If we provide false as value to this attribute then container will allow
Expression Language syntaxes into the present JSP pages.
• The default value in JSP1.2 version is: true & The default value from JSP2.0
version is: false.

15. isContentTypeSupported
Description: Indicates whether the specified content type is supported.
Use Case: Ensures compatibility with different browsers or client applications.
Example:
<%@ page isContentTypeSupported="true" %>

16. deferredSyntaxAllowedAsLiteral
Description: Determines whether ${ and #{ syntax is treated as literals or evaluated
as EL expressions.
Use Case: Helps in compatibility with older JSP versions or specific requirements.
Example:
<%@ page deferredSyntaxAllowedAsLiteral="false" %>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

17. trimDirectiveWhitespaces
Description: Controls whitespace removal around JSP directives.
Use Case: Minimizes HTML output size by eliminating unnecessary whitespace.
Example:
<%@ page trimDirectiveWhitespaces="true" %>

18. errorOnUndeclaredNamespace
Description: Determines whether undeclared XML namespaces in JSP documents
cause an error.
Use Case: Ensures strict adherence to XML namespace declaration rules.
Example:
<%@ page errorOnUndeclaredNamespace="true" %>

19. sessionMaxInactiveInterval
Description: Specifies the maximum time, in seconds, that a session is kept alive
between client requests.
Use Case: Customizes session timeout for different security or usability
requirements.
Example:
<%@ page sessionMaxInactiveInterval="1800" %>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Example : Setting Content Type and Importing Classes


<%@ page contentType="text/html;charset=UTF-8" import="java.util.Date,
java.text.SimpleDateFormat" %>
<html>
<head>
<title>Current Date</title>
</head>
<body>
<h1>Current Date: <%= new SimpleDateFormat("dd-MM-yyyy").format(new
Date()) %></h1>
</body>
</html>

Example : Using Session and Error Handling


<%@ page session="true" errorPage="error.jsp" %>
<html>
<head>
<title>Session Example</title>
</head>
<body>
<h1>Welcome, <%= session.getAttribute("username") %></h1>
</body>
</html>

Example : Controlling Buffer and AutoFlush


<%@ page buffer="16kb" autoFlush="true" %>
<html>
<head>
<title>Buffered Output</title>
</head>
<body>
<h1>This page uses a 16kb buffer.</h1>
</body>
</html>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Example : Defining an Error Page


Main Page:
<%@ page errorPage="error.jsp" %>
<%
int result = 10 / 0; // This will throw an exception
%>

Error Page:
<%@ page isErrorPage="true" %>
<html>
<head>
<title>Error Page</title>
</head>
<body>
<h1>An error occurred: <%= exception.getMessage() %></h1>
</body>
</html>

Example: Disabling Expression Language (EL)


<%@ page isELIgnored="true" %>
<html>
<head>
<title>No EL Example</title>
</head>
<body>
<h1>Today's Date: <%= new java.util.Date() %></h1>
</body>
</html>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Example: Setting Session Timeout


<%@ page session="true" sessionMaxInactiveInterval="1800" %>
<html>
<head>
<title>Session Timeout Example</title>
</head>
<body>
<h1>Welcome, <%= session.getAttribute("username") %></h1>
<p>Your session will expire in 30 minutes.</p>
</body>
</html>

Example: Controlling Buffer Size


<%@ page buffer="16384" %>
<html>
<head>
<title>Large Buffer Example</title>
</head>
<body>
<h1>This page uses a large buffer.</h1>
</body>
</html>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Best Training Institute
for Graduates
with
Live Online & Offline Classes Available

Join us for Better Career and Job Guarantee

Full Stack Web Development


Top Edge (MERN Stack) HTML, CSS, JavaScript, ES,
Git, ReactJS, Node, Express, MySQL & MongoDB

Training Full Stack Engineer


Java, JavaScript, ReactJS, Spring, SpringBoot
Hibernate, Linux, AWS, Git, DevOps & Jira

Programs Digital Marketing


Social Media, Website Design, SEO,
Google Ads, Freelancing & Many More

Guaranteed Package (In Writing)


▪ 3-5 Lakhs (With 6 Months Training Programs)
▪ 6-8 Lakhs (With 12 Months Training Programs)
▪ 10 Lakhs+ (With 2 Years Training Programs)

Amenities
▪ Digital Notes ▪ Working Experience
▪ Live Training Sessions ▪ Job Recommendations
▪ Project Assistance ▪ Professional Development
▪ Interview Preparation ▪ Digital Resume & Portfolio

LEARN-2-EARN LABS TRAINING INSTITUTE


Anna Icon Complex, near Kargil Petrol Pump, Sikandra-Bodla Road, Sikandra, Agra
Website : www.LearntoearnLabs.com
Call : 91-9548868337 / +91-9837705705
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Scopes in JSP
There are four scopes in JSP

- Page
- Request
- Session
- Application

Page scope

- ‘page’ scope means, the JSP object can be accessed only from within the same
page where it was created.
- The default scope for JSP objects created using <jsp:useBean> tag is page.
- JSP implicit objects out, exception, response, pageContext, config and page
have ‘page’ scope.

Request scope
- A JSP object created using the ‘request’ scope can be accessed from any pages
that serves that request.
- More than one page can serve a single request. The JSP object will be bound
to the request object.
- Implicit object request has the ‘request’ scope.

Session scope

- ‘session’ scope means, the JSP object is accessible from pages that belong to
the same session from where it was created.
- The JSP object that is created using the session scope is bound to the session
object.
- Implicit object session has the ‘session’ scope.

Application scope

- A JSP object created using the ‘application’ scope can be accessed from any
pages across the application. The JSP object is bound to the application object.
- Implicit object application has the ‘application’ scope.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Details about JSP scopes

Scope Maintained by Methods


Public void setAttribute(String name, Object value)
PageContext
Page Public Object getAttribute(String name)
<<abstract class>>
Public void removeAttribute(String name)
Public Enumeration getAttributeNamesInScope(int scope)

Public void setAttribute(String name, Object value)


ServletRequest
Public Object getAttribute(String name)
Request <<interface>>
Public void removeAttribute(String name)
Public Enumeration getAttributeNames()

Public void setAttribute(String name, Object value)


HttpSession
Public Object getAtribute(String name)
Session <<interface>>
Public void removeAttribute(String name)
Public Enumeration getAttributeNames()

Public void setAttribute(String name, Object value)


ServletContext
Application Public Object getAttribute(String name)
<<interface>>
Public void removeAttribute(String name)
Public Enumeration getAttributeNames()

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

PageContext
• pageContext is an implicit object in JSP of type PageContext object.
• The PageContext object is used to set or get or remove the attributes from
following scopes
o Page
o Request
o Session
o Application

form.html
<html>
<body>
<form action="welcome.jsp" method="post">
Enter user name = <input type="text" name="uname"/>
<input type="submit" value="submit"/>
</form>
</body>
</html>
welcome.jsp
<%@ page language="java" contentType="text/html"%>
<html>
<body>
<%
String uname = request.getParameter("uname");
pageContext.setAttribute("uname",uname, PageContext.SESSION_SCOPE);
out.println("<a href='second.jsp'>click here to get msg</a>");
%>
</body>
</html>
second.jsp
<%@ page language="java" contentType="text/html"%>
<html>
<body>
<%String uname =
(String)pageContext.getAttribute("uname",PageContext.SESSION_SCOPE);
out.println("Welcome="+uname);
%>
</body>
</html>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Config & application implicit objects

form.html
<html><body>
<a href="First">click here to get First jsp</a><br>
<a href="Second">click here to get Second jsp</a><br>
</body></html>

first.jsp
<%@ page language="java" contentType="text/html"%>
<html><body>
<%!String animal;
String uname;
String upwd;
%>
<%animal = config.getInitParameter("Animal");
uname = application.getInitParameter("username");
upwd = application.getInitParameter("password");
%>
Init param-1 <%=animal%><br>
context param-1 <%=uname%><br>
context param-2 <%=upwd%><br>
</body></html>

second.jsp
<%@ page language="java" contentType="text/html"%>
<html><body>
<%! String animal;
String uname;
String upwd;
%>
<% animal = config.getInitParameter("Fruit");
uname = application.getInitParameter("username");
upwd = application.getInitParameter("password");
%>
Init param-1 <%=animal%><br>
context param-1 <%=uname%><br>
context param-2 <%=upwd%><br>
</body>
</html>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

web.xml

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


<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID"
version="4.0">
<display-name>jspexample</display-name>
<welcome-file-list>
<welcome-file>form.html</welcome-file>
</welcome-file-list>

<context-param>
<param-name>username</param-name>
<param-value>nitin</param-value>
</context-param>

<context-param>
<param-name>password</param-name>
<param-value>123</param-value>
</context-param>

<servlet>
<servlet-name>aaa</servlet-name>
<jsp-file>/first.jsp</jsp-file>
<init-param>
<param-name>Animal</param-name>
<param-value>Tiger</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>aaa</servlet-name>
<url-pattern>/first</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>bbb</servlet-name>
<jsp-file>/second.jsp</jsp-file>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

<init-param>
<param-name>Fruit</param-name>
<param-value>Mango</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>bbb</servlet-name>
<url-pattern>/second</url-pattern>
</servlet-mapping>
</web-app>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Session implicit object


• A session is an object associated with a visitor. We can set the data & get data of
particular user.
• The data is visible until the user is invalidate the session. Once the user invalidate
the session we will get null values.
session.invalidate();
when you declare session=false in jsp, it is not possible to use session object inside
the JSP.
<%@ page language="java" contentType="text/html" session="false"%>

form.html
<html>
<body>
<form method="post" action="savename.jsp">
what's your name? <input type="text" name="uname" size=20>
<p><input type=submit value="submit">
</form>
</body>
</html>

savename.jsp
<%@ page language="java" contentType="text/html"%>
<html>
<body>
<% String name = request.getParameter("uname");
session.setAttribute( "theName", name );
%>
<a href="NextPage.jsp">Continue</A>
</body>
</html>

nextPage.jsp
<%@ page language="java" contentType="text/html"%>
<html>
<head>
Hello,<%= session.getAttribute("theName")%>
</body>
</html>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Example

form1.html
<html>
<body bgcolor="pink">
<center> <form method="get" action="./First.jsp">
Name : <input type="text" name="uname"/><br><br>
Age : <input type="text" name="uage"/><br><br>
<input type="submit" value="Next"/>
</form>
</center>
</body></html>

first.jsp

<%@ page language="java" contentType="text/html"%>


<html><body>
<%!String name;
int age;
%>
<% name = request.getParameter("uname");
age = Integer.parseInt(request.getParameter("uage"));
session.setAttribute("name", name);
session.setAttribute("age", age); %>
<jsp:forward page="form2.html"/>
</body>
</html>

form2.html
<html>
<body bgcolor="pink">
<center>
<form method="get" action="./second.jsp">
Qualification : <input type="text" name="uqual"/><br><br>
Designation : <input type="text" name="udesig"/><br><br>
<input type="submit" value="Next"/>
</form>
</center>
</body></html>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

second.jsp
<%@ page language="java" contentType="text/html"%>
<html>
<body>
<%!
String qual;
String desig;
%>
<%
qual = request.getParameter("uqual");
desig = request.getParameter("udesig");
%>
User name : <%=session.getAttribute("name")%><br>
User Age : <%=session.getAttribute("age")%><br>
User Qualifications : <%=qual%><br>
User Designation : <%=desig%><br>
</body>
</html>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Exception handling in JSP


We can handle the exceptions in 3-ways
1. Programmatic approach using simple try-catch
2. Programmatic approach. Using isErrorPage errorPage
3. Declarative approach. Using <error-page> tag in Deployment Descriptor
(web.xml).

Programmatic approach. Using try-catch:-


<html>
<body>
<%
try{
out.println(10/0);
}
catch (ArithmeticException e){
out.println("An exception occurred: " + e.getMessage());
}
%>
</body>
</html>

Programmatic approach. Using isErrorPage errorPage

This approach specify one error for all kind of exceptions, so we can’t specify the error
page different exceptions like,
SQLException ---> dbError.jsp
IOException ---> ioerror.jsp
When the file name of error page is changed we have to update all referenced jsp files.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Exception handling programmatic Approach

process.jsp
<%@ page language="java" errorPage="error.jsp" contentType="text/html"%>
<html>
<body>
<%out.print("Shekhar".charAt(20)); %>
</body>
</html>

web.xml
<web-app>
<error-page>
<exception-type>java.lang.StringIndexOutOfBoundsException</exception-type>
<location>/error.jsp</location>
</error-page>
</web-app>

error.jsp
<%@ page contentType="text/html"%>
<html>
<body>
<%out.print("Hello Mr. Shubham StringIndexOutOfBounds Exception raised");
%>
</body>
</html>

• The above error pages can be used across all JSPs in a given web application.
Declarative approach is always recommended.
• In error page no need to specify the isErrorPage attribute.

Difference between PrintWriter and JspWriter


• PrintWriter is a writer in servlet applications, it can be used to carry the response.
• PrintWriter is not BufferedWriter so that its performance is very less in servlets
applications.
• JspWriter is a writer in JSP technology to carry the response.
• JspWriter is a BufferedWriter so that its performance will be more when compared
with PrintWriter.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

JSP Actions
• In JSP technology, by using scripting elements we are able to provide java code
inside the JSP pages, but the main theme of JSP technology is not to allow java
code inside JSP pages.
• To eliminate java code from JSP pages we have to eliminate scripting elements, to
eliminate scripting elements from JSP pages we have to provide an alternative i.e.
JSP Actions.
• In case of JSP Actions, we will define a scripting tag in JSP page and we will provide
a block of java code with respect to scripting tag.
• When container encounters the scripting tag then container will execute respective
java code, by this an action will be performed called as JSP Action.

In JSP technology, there are 2 types of actions.


• Standard Actions
• Custom Actions

Standard Actions
• Standard Actions are JSP Actions, which could be defined by the JSP technology to
perform a particular action.
• JSP technology has provided all the standard actions in the form of a set of
predefined tags called Action Tags.
1. <jsp:useBean---->
2. <jsp:setProperty---->
3. <jsp:getProperty---->
4. <jsp:include---->
5. <jsp:forward---->
6. <jsp:param---->
7. <jsp:plugin---->
8. <jsp:fallback---->
9. <jsp:params---->
10. <jsp:declaration---->
11. <jsp:scriptlet---->
12. <jsp:expression---->

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Java Beans
• Java Bean is a reusable component.
• Java Bean is a normal java class which may declare properties, setter and getter
methods in order to represent a particular user form at server side.
• If we want to prepare Java Bean components then we have to use the following
rules and regulations.
1. Java Bean is a normal java class, it is suggestible to implement Serializable
interface.
2. Always Java Bean classes should be public, non-abstract and non-final.
3. In Java Bean classes, we have to declare all the properties w.r.t. the
properties define in the respective user form.
4. In Java Bean classes, all the properties should be private.
5. In Java Bean classes, all the behaviors / methods should be public.
6. If we want to declare any constructor in Java Bean class then that
constructor should be public and zero argument.

<jsp:useBean>:
• The main purpose of <jsp:useBean> tag is to interact with bean object from a
particular JSP page.
• This tag used to locate or instantiate bean class. If the bean object is already
created it doesn’t create a bean based on scope. But if the bean is not created it
instantiate the bean.
<jsp:useBean id=”--” class=”--” type=”--” scope=”--”/>
Id = instance name
Class = fully qualified name of the bean class
Scope =page request session application (scope of the bean object)

note:
• In <jsp:useBean> tag, always it is suggestible to provide either application or
session scope to the scope attribute value.
• When container encounters the above tag then container will pick up class
attribute value i.e. fully qualified name of Bean class then container will recognize
Bean class .class file and perform Bean class loading and instantiation.
• After creating Bean object container will assign Bean object reference to the
variable specified as value to id attribute.
• After getting Bean object reference container will store Bean object in a scope
specified as value to scope attribute.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

<jsp:setProperty>
• The main purpose of <jsp:setProperty> tag is to execute a particular setter method
in order to set a value to a particular Bean property.

Syntax: <jsp:setProperty name=”--” property=”--” value=”--”/>

• Where name attribute will take a variable which is same as id attribute value in
<jsp:useBean> tag.
• Where property attribute will take a property name in order to access the
respective setter method.
• Where value attribute will take a value to pass as a parameter to the respective
setter method.

<jsp:getProperty>
The main purpose of <jsp:getProperty> tag is to execute a getter method in order to get
a value from Bean object.

<jsp:getProperty name=”--” property=”--”/>

Where name attribute will take a variable which is same as id attribute value in
<jsp:useBean> tag.
Where property attribute will take a particular property to execute the respective getter
method.

Note:
• In case of <jsp:useBean> tag, in general we will provide a separate
<jsp:setProperty> tag to set a particular value to the respective property in Bean
object.
• In case of <jsp:useBean> tag, it is possible to copy all the request parameter values
directly onto the respective Bean object.
• To achieve this we have to provide “*” as value to property attribute in
<jsp:setProperty> tag.

Ex: <jsp:setProperty name=”e” property=”*”/>

• If we want to achieve the above requirement then we have to maintain same names
in the request
• parameters i.e. form properties and Bean properties.

Note: The above “*” notation is not possible with <jsp:getProperty> tag.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

form.html
<html>
<h5> *******Employee Details********</h5>
<body>
<form method="post" action="main.jsp">
Employee id :<input type="text" name="eid"/><br>
Employee name : <input type="text" name="ename"/><br>
Employee salary :<input type="text" name="esal"/></br>
<input type="submit" value="submit"/>
</form>
</body>
</html>

Main.jsp
<%@ page language="java" contentType="text/html"%>
<html>
<body>
<%! int eid;
String ename;
double esal;
%>
<% eid = Integer.parseInt(request.getParameter("eid"));
ename = request.getParameter("ename");
esal = Double.parseDouble(request.getParameter("esal"));
%>
<jsp:useBean id="eb" class="com.mohit" scope="page"/>
<jsp:setProperty property="ename" name="eb" value="<%=ename%>"/>
<jsp:setProperty property="eid" name="eb" value="<%=eid%>"/>
<jsp:setProperty property="esal" name="eb" value="<%=esal%>"/>
<h5>**********Employee Details**********</h5>
Employee name : <jsp:getProperty property="ename" name="eb"/><br>
Employee id : <jsp:getProperty property="eid" name="eb"/> <br>
Employee salary: <jsp:getProperty property="esal" name="eb"/><br>
</body>
</html>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

EmpBean.java
package com.mohit;
import java.io.Serializable;
public class EmpBean implements Serializable{
int eid;
String ename;
double esal;
publicint getEid() {
return eid;
}
publicvoid setEid(int eid) {
this.eid = eid;
}
public String getEname() {
return ename;
}
publicvoid setEname(String ename) {
this.ename = ename;
}
publicdouble getEsal() {
return esal;
}
publicvoid setEsal(double esal) {
this.esal = esal;
}
}

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

<jsp:include>

Q: What are the differences between include directive and <jsp:include> action
tag?
1. In JSP applications, include directive can be used to include the content of the
target resource into the present JSP page.
In JSP pages, <jsp:include> action tag can be used to include the target resource
response into the present JSP page response.

2. In general include directive can be used to include static resources where the
frequent updations are not available.
<jsp:include> action tag can be used to include dynamic resources where the
frequent updations are available.

3. In general directives will be resolved at the time of translation and actions will be
resolved at the time of request processing. Due to this reason include directive will
be resolved at the time of translation but <jsp:include> action tag will be resolved
at the time of request processing.

• If we are trying to include a target JSP page into present JSP page by using include
directive then container will prepare only one translated servlet.
• To include a target JSP page into the present JSP page if we use <jsp:include>
action tag then container will prepare 2 separate translated servlets.
• In JSP applications, include directives will provide static inclusion, but <jsp:include>
action tag will provide dynamic inclusion.
• In JSP technology, <jsp:include> action tag was designed on the basis of Include
Request Dispatching Mechanism.

Syntax
<jsp:include page=”--” flush=”--”/>

• Where page attribute will take the name and location of the target resource to
include its response.
• Where flush is a boolean attribute, it can be used to give an intimation to the
container about to autoFlush or not to autoFlush dynamic response to client when
JspWriter buffer filled with the response at the time of including the target resource
response into the present JSP page.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Working with Database

form.html
<html>
<body bgcolor="lightgreen">
<form action="add.jsp">
<pre>
<u>Product Details</u>
Product Id : <input type="text" name="pid"/>
Product Name : <input type="text" name="pname"/>
Product Cost : <input type="text" name="pcost"/>
<input type="submit" value="ADD"/>
</pre>
</form>
</body>
</html>

add.jsp
<%@page import="java.sql.*"%>
<%!
String pid;
String pname;
int pcost;
static Connection con;
static Statement st;
ResultSet rs;
ResultSetMetaData rsmd;

static{
try{
Class.forName("com.mysql.cj.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/
servletdb","root","android");
st=con.createStatement();
}
catch(Exception e)
{

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

e.printStackTrace();
System.out.println("exception occured");
}
}
%>
<% pid=request.getParameter("pid");
pname=request.getParameter("pname");
pcost=Integer.parseInt(request.getParameter("pcost"));

try{
st.executeUpdate("insert into product values('"+pid+"','"+pname+"',"+pcost+")");
}
catch(Exception e)
{
e.printStackTrace();
}
out.println("values are inserted successfully");
%>
<jsp:include page="form.html"/>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Include Directive
• It is used to include the target jsp page into present jsp page.
• Include directive include the target page data into present jsp file at translation
time(jsp-servlet).
• If any modification done in jsp file will not be visible until jsp file compiles again.
• Include directive is static import.
• It is better for static pages, if we are using for dynamic pages for every change it
requires translation.
• By using include directive we are unable to pass parameters to target page.

Syntax
<%@ include file="file_name" %>

Example
<%@ include file="hello.jsp" %>

Include Action
• It is used to include the target JSP into present JSP page.
• The content of the target JSP included at runtime instead of translation time.
• If you done the modifications these are effected when we send the request to JSP.
• Include action is dynamic import.
• Instead of including original data it is calling include method at runtime.
• By using include action we are able to pass parameters to the included page.

<jsp:include page="file_name" />


<jsp:param name="parameter_name" value="parameter_value" />
</jsp:include>

Syntax
<jsp:include page="file_name" />
Example
<jsp:include page="hello.jsp"/>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

main.jsp
<%@ page language="java" contentType="text/html" %>
<html>
<body>

This is info about main.jsp file

<br><br><br>

<jsp:include page="hello.jsp">
<jsp:param name="a" value="10"/>
</jsp:include>
</body>
</html>
hello.jsp
<%@ page language="java" contentType="text/html" %>
<%@page import="java.util.*"%>
<html>
<body>
hi this is hello.jsp file content<br>
welcome to Learn2Earn Labs<br>
<%="Today date ="+new Date()%><br>
<%="param tag value="+request.getParameter("a")%>
</body>
</html>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

<jsp:forward>

What are the differences between<jsp:include> action tag and <jsp:forward>


action tag?

<jsp:include> action tag can be used to include the target resource response into the
present JSP page.
<jsp:forward> tag can be used to forward request from present JSP page to the target
resource.

<jsp:include> tag was designed on the basis of Include Request Dispatching Mechanism.
<jsp:forward> tag was designed on the basis of Forward Request Dispatching Mechanism.

In case of <jsp:include> tag client is able to receive all the resources response which are
participated in the present request processing.
In case of <jsp:forward> tag client is able to receive only target resource response.

Syntax
<jsp:forward page=”--”/>
Where page attribute specifies the name and location of the target resource.

Example

<jsp:include>&<jsp:forward>

login.html
<html>
<body>
<form action="main.jsp">
<h5> Welcome to Learn2Earn Labs Training Institute</h5>
User name : <input type="text" name="uname"/><br>
Password : <input type="password" name=upwd/><br>
<input type="submit" value="login"/>
</form>
</body>
</html>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

main.jsp
<%@ page language="java" contentType="text/html"%>
<html>
<body>
<%!
String uname;
String upwd;
%>
<%
String uname = request.getParameter("uname");
String upwd = request.getParameter("upwd");
if(uname.equals("Learn2earnLabs") && upwd.equals(“123”))
{
%>
<jsp:forward page="success.jsp"/>
<%
}
else
{
out.println("Login is failed, try with another username & password");
}
%>
<jsp:include page="login.html"/>
</body>
</html>

success.jsp
<%@ page language="java" contentType="text/html"%>
<html>
<body>
Hi this is Success jsp<br>
U r login is Success
</body>
</html>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

<jsp:param>:

This action tag can be used to provide a name value pair to the request object at the time
of passing request object from present JSP page to target page either in include
mechanism or in forward mechanism or in both.

This tag must be utilized as a child tag to <jsp:include> tag and <jsp:forward> tags.

Syntax
<jsp:param name=”--” value=”--”/>

forwardapp
registrationform.html
<html>
<body bgcolor="lightgreen">
<form action="registration.jsp">
<pre>
<u>Registration Form</u>
Name : <input type="text" name="uname"/>
Age : <input type="text" name="uage"/>
Address : <input type="text" name="uaddr"/>
<input type="submit" value="Registration"/>
</pre>
</form>
</body>
</html>

existed.jsp
<center><h1>User Existed</h1></center>
success.jsp
<center><h1>Registration Success</h1></center>
failure.jsp
<center><h1>Registration Failure</h1></center>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

registration.jsp
<%@ page import="java.sql.*" language="java" contentType="text/html;
charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Learn2EarnLabs Training Institute</title>
</head>
<body>
<%!
String uname;
int uage;
String uaddr;
static Connection con;
static Statement st;
ResultSet rs;
static{
try{
Class.forName("com.mysql.cj.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:
3306/servletdb","root","android");
st=con.createStatement();
}
catch(Exception e){
e.printStackTrace();
}
}
%>

<%
try{
uname=request.getParameter("uname");
uage=Integer.parseInt(request.getParameter("uage"));
uaddr=request.getParameter("uaddr");

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

rs=st.executeQuery("select * from regusers where


name='"+uname+"'");

boolean b=rs.next();
if(b==true)
{
%>
<jsp:forward page="existed.jsp"/>
<%
}
else
{
int rowCount=st.executeUpdate("insert into regusers
values('"+uname+"',"+uage+",'"+uaddr+"')");
if(rowCount == 1)
{
%>
<jsp:forward page="success.jsp"/>
<%
}
else
{
%>
<jsp:forward page="failure.jsp"/>
<%
}
}
}
catch(Exception e){
%>
<jsp:forward page="failure.jsp"/>
<%
e.printStackTrace();
}
%>
</body>
</html>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

<jsp:plugin>

This tag can be used to include an applet into the present JSP page.
Syntax
<jsp:plugin code=”--” width=”--” height=”--” type=”--”/>

Where code attribute will take fully qualified name of the applet.
Where width and height attributes can be used to specify the size of applet.
Where type attribute can be used to specify which one, we are going to include whether
it is applet or bean.
Example
<jsp:plugin code=”Logo” width=”1000” height=”150” type=”applet”/>

<jsp:params>

In case of the applet applications, we are able to provide some parameters to the applet
in order to provide input data.
Similarly if we want to provide input parameters to the applet from <jsp:plugin> tag we
have to use <jsp:param> tag.
<jsp:param> tag must be utilized as a child tag to <jsp:params> tag.
<jsp:params> tag must be utilized as a child tag to <jsp:plugin> tag.
Syntax
<jsp:plugin>
<jsp:params>
<jsp:param name=”--” value=”--”/>
<jsp:param name=”--” value=”--”/>
----------
</jsp:params>
----------
</jsp:plugin>

If we provide any input parameter to the applet then that parameter value we are able to
get by using the following method from Applet class.
public String getParameter(String name)
Example
String msg=getParameter(“message”);

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

pluginapp

LogoApplet.java
import java.awt.*;
import java.applet.*;
public class LogoApplet extends Applet
{
String msg;
public void paint(Graphics g)
{
msg=getParameter("message");
Font f=new Font("arial",Font.BOLD,40);
g.setFont(f);
this.setBackground(Color.blue);
this.setForeground(Color.white);
g.drawString(msg,150,70);
}
}

logo.jsp
<jsp:plugin code="LogoApplet" width="1000" height="150" type="applet">
<jsp:params>
<jsp:param name="message" value="Learn2Earn Labs Training Institute"/>
</jsp:params>
</jsp:plugin>

note : Applet concept is now deprecated.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

<jsp:fallback>

The main purpose of <jsp:fallback> tag is to display an alternative message when client
browser is not supporting <OBJECT---> tag and <EMBED---> tag.

Syntax
<jsp:fallback>-------Description---------</jsp:fallback>

In Jsp applications, we have to utilize <jsp:fallback> tag as a child tag to <jsp:plugin>


tag.

Example
<jsp:plugin code=”LogoApplet” width=”1000” height=”150” type=”applet”>
<jsp:fallback>Applet Not Allowed</jsp:fallback>
</jsp:plugin>

<jsp:declaration>

This tag is almost all same as the declaration scripting element, it can be used to provide
all the Java declarations in the present JSP page.

Syntax
<jsp:declaration>
-------- Java Declarations
</jsp:declaration>

<jsp:scriptlet>

This tag is almost all same as the scripting element scriptlets, it can be used to provide a
block of Java code in JSP pages.

Syntax
<jsp:scriptlet>
-------- Block of Java code
</jsp:scriptlet>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

<jsp:expression>

This tag is almost all same as the scripting element expression, it can be used to provide
a Java expression in the present JSP page.

Syntax
<jsp:expression> Java Expression </jsp:expression>

<%@page import="java.util.*"%>

<jsp:declaration>
Date d=null;
String date=null;
</jsp:declaration>

<jsp:scriptlet>
d=new Date();
date=d.toString();
</jsp:scriptlet>
<html>
<body bgcolor="lightyellow">
<center><b>
<font size="6" color="red"><br><br>

Today Date : <jsp:expression>date</jsp:expression>

</font>
</b></center>
</body>
</html>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Custom Actions
• Custom Actions are JSP Actions which could be prepared by the developers as per
the project requirements.
• In JSP technology, standard actions will be represented in the form of a set of
predefined
• tags are called as Action Tags.
• Similarly, all the custom actions will be represented in the form of a set of user
defined tags are called as Custom Tags.

To prepare custom tags in JSP pages we have to use the following syntax.

Syntax
<prefix_Name:tag_Name>
--------
-------- Body
--------
</prefix_Name>

If we want to design custom tags in our JSP applications then we have to use the following
three elements.
a) JSP page with taglib directive
b) TLD(Tag Library Descriptor) file
c) TagHandler class

• Where TagHandler class is a normal Java class it is able to provide the basic
functionality for the custom tags.
• Where TLD file is a file, it will provide the mapping between custom tag names and
respective TagHandler classes.
• Where taglib directive in the JSP page can be used to make available the tld files
into the present Jsp page on the basis of custom tags prefix names.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Internal Flow
• When container encounters a custom tag container will pick up the custom tag
name and the respective prefix name then recognize a particular taglib directive
on the basis of the prefix attribute value.
• After recognizing taglib directive container will pick up uri attribute value i.e. the
name and location of tld file then container will recognize the respective tld file.
• After getting tld file container will identify the name and location of TagHandler
class on the basis of custom tag name.
• When container recognize the respective TagHandler class .class file then container
will perform TagHandler class loading, instantiation and execute all the life cycle
methods.

1. Taglib Directive
In custom tags design, the main purpose of taglib directive is to make available the
required tld file into the present JSP page and to define prefix names to the custom tags.
Syntax
<%@taglib uri=”--” prefix=”--”%>
Where prefix attribute can be used to specify a prefix name to the custom tag, it will have
page scope i.e. the specified prefix name is valid up to the present JSP page.
Where uri attribute will take the name and location of the respective tld file.

2. TLD File
The main purpose of TLD file is to provide the mapping between custom tag names and
the respective TagHandler classes and it is able to manage the description of the custom
tags attributes.
To provide the mapping between custom tag names and the respective TagHandler class
we have to use the following tags.
<taglib>
<jsp-version>jsp version</jsp-version>
<tlib-version>tld file version</tlib-version>
<short-name>tld file short name</short-name>
<description>description about tld file</description>
<tag>
<name>custom tag name</name>
<tag-class>fully qualified name of TagHandler class</tag-class>
<body-content>jsp or empty</body-content>
<short-name>custom tag short name</short-name>
<description>description about custom tags</description>
</tag>
</taglib>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

3. TagHandler class

• In custom tags preparation, the main purpose of TagHandler class is to define the
basic functionality for the custom tags.
• To design TagHandler classes in custom tags preparation Jsp API has provided
some predefined library in the form of javax.servlet.jsp.tagext package (tagext→tag
extension).
• javax.servlet.jsp.tagext package has provided the following library to design
TagHandler classes.

The Tag library was divided into 2 types.


1. Classic Tag library
2. Simple Tag library

As per the tag library provided by JSP technology there are 2 types of custom tags.
1. Classic tags
2. Simple Tags

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

1. Classic Tags

Classic Tags are the custom tags will be designed on the basis of Classic tag library
provided by JSP API.

As per the classic tag library provided by Jsp API there are 3 types of classic tags.
1. Simple Classic Tags
2. Iterator Tags
3. Body Tags

Simple Classic Tags:


Simple Classic Tags are the classic tags, which should not have body and attributes list.

To design simple classic tags the respective TagHandler class must implement Tag
interface either directly or indirectly.

Predefined support
package javax.servlet.jsp.tagext;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;

public interface Tag extends JspTag


{
public abstract void setPageContext(PageContext pagecontext);
public abstract void setParent(Tag tag);
public abstract Tag getParent();
public abstract int doStartTag()throws JspException;
public abstract int doEndTag()throws JspException;
public abstract void release();
public static final int SKIP_BODY = 0;
public static final int EVAL_BODY_INCLUDE = 1;
public static final int SKIP_PAGE = 5;
public static final int EVAL_PAGE = 6;
}
Userdefined class
public class MyHandler extends Tag
{
//write the code here
}

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

• Where the purpose of setPageContext(_) method is to inject pageContext implicit


object into the present TagHandler class.
• Where the purpose of setParent(_) method is to inject parent tags TagHandler class
object into the present TagHandler class.
• Where the purpose of getParent() method is to return the parent tags TagHandler
class object from the TagHandler class.
• Where the purpose of doStartTag() method is to perform a particular action when
container encounters the start tag of the custom tag.

After the custom tags start tag evaluating the custom tag body is completely depending
on the return value provided by doStartTag () method.

There are 2 possible return values from doStartTag() method.


• EVAL_BODY_INCLUDE
• SKIP_BODY
If doStartTag() method returns EVAL_BODY_INCLUDE constant then container will
evaluate the custom tag body.
If doStartTag() method returns SKIP_BODY constant then container will skip the custom
tag body and encounter end tag.

Where the purpose of doEndTag() method is to perform an action when container


encounters end tag of the custom tag.

Evaluating the remaining the Jsp page after the custom tag or not is completely
depending on the return value provided by doEndTag() method.

There are 2 possible return values from doEndTag() method.


• EVAL_PAGE
• SKIP_PAGE

If doEndTag() method returns EVAL_PAGE constant then container will evaluate the
remaining Jsp page.
If doEndTag() method returns SKIP_PAGE constant then container will not evaluate the
remaining Jsp page.

Where release() method can be used to perform TagHandler class deinstantiation.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Life Cycle of Tag interface:

Note: In Tag interface life cycle, container will execute getParent() method when the
present custom tag is child tag to a particular parent tag otherwise container will not
execute getParent() method.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Steps to design custom tag application

• create the TagHandler class to provide the action


• create the Tag Library Discriptor file(tld) file to configure custom tags.
• write the jsp file to declare the custom tag configured in tld file.

Example

hello.jsp
<%@taglib uri="/WEB-INF/hello.tld" prefix="mytags"%>
<mytags:hello>
hi nitin how r u
</mytags:hello>
<br>
this is remaining page of JSP

hello.tld
<taglib>
<jsp-version>2.1</jsp-version>
<tlib-version>1.0</tlib-version>
<tag>
<name>hello</name>
<tag-class>com.java.example.CustomTag</tag-class>
<body-content>jsp</body-content>
</tag>
</taglib>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Customtag.java
package com.java.example;

import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.Tag;

public class Customtag implements Tag{


PageContext context;
publicint doEndTag() throws JspException {
System.out.println("doEndTag method");
returnSKIP_PAGE;
}
Public int doStartTag() throws JspException {
JspWriter writer = context.getOut();
try {
writer.println("this is custom tag application by Mohit");
writer.print("<br>");
}
catch (IOException e) {
e.printStackTrace();
}
return EVAL_BODY_INCLUDE;
}

public Tag getParent() {


System.out.println("getParent method");
return null;
}
Public void release() { }
public void setPageContext(PageContext arg0) {
this.context=arg0;
System.out.println("page context method");
}
Public void setParent(Tag arg0) {
System.out.println("set parent method");
}
}

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Attributes in Custom Tags

• In custom tag it is possible to provide multiple attributes.


• If we want to provide attributes in custom tags then we have to perform the
following steps.

Step 1: Define attribute in the custom tag.


<mytags:hello name=”Mohit”/>
Step 2: Provide attributes description in the respective tld file.
To provide attributes description in tld file we have to use the following tags in tld file.

<taglib>
<tag>
<attribute>
<name>attribute_name</name>
<required>true/false</required>
<rtexprvalue>true/false</rtexprvalue>
</attribute>
</tag>
</taglib>

• Where <attribute> tag can be used to represent a single attribute in the tld file.
• Where <name> tag will take attribute name.
• Where <required> tag is a boolean tag, it can be used to specify whether the
attribute is mandatory or optional.
• Where <rtexprvalue> tag can be used to specify whether the attribute accept
runtime values or not.

Step 3: Declare a property and setter method in TagHandler class with the same
name of the attribute defined in custom tag.
public class MyHandler implements Tag {
private String name;

public void setName(String name) {


this.name=name;
}
}

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Iterator Tags

• Iterator tags are the custom tags, it will allow to evaluate custom tag body
repeatedly.
• If we want to prepare iterator tags the respective TagHandler class must
implements javax.servlet.jsp.tagext.IterationTag interface.

Predefined support
package javax.servlet.jsp.tagext;
import javax.servlet.jsp.JspException;
public interface IterationTag extends Tag
{
public abstract int doAfterBody()throws JspException;
public static final int EVAL_BODY_AGAIN = 2;
}

Userdefined class

class MyHandler implements IterationTag


{
//write the body here
}

In general there are two possible return values from doStartTag() method.
1) EVAL_BODY_INCLUDE
If we return EVAL_BODY_INCLUDE constant from doStartTag() method then
container will execute the custom tag body.
2) SKIP_BODY
If we return SKIP_BODY constant from doStartTag() method then container will skip
the custom tag body.

Note: In case of iterator tags, we must return EVAL_BODY_INCLUDE from doStartTag()


method.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

After evaluating the custom tag body in case of iterator tags, container will access
doAfterBody() method.

In this context, evaluating the custom tag body again or not is completely depending on
the return value which we are going to return from doAfterBody() method.
1) EVAL_BODY_AGAIN
If we return EVAL_BODY_AGAIN constant from doAfterBody() method then
container will execute the custom tag body again.
2) SKIP_BODY
If we return SKIP_BODY constant from doAfterBody() method then container will
skip out custom tag body evaluation and encounter end tag of the custom tag.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Life Cycle of IterationTag interface

• If we want to design custom tags by using above approach then the respective
TagHandler class must implement Tag interface and IterationTag interface i.e. we
must provide the implementation for all the methods which are declared in Tag
and IterationTag interfaces in our TagHandler class.
• This approach will increase burden to the developers and unnecessary methods in
TagHandler classes.
• To overcome this problem JSP API has provided an alternative in the form of
TagSupport class.
• TagSupport is a concrete class, which was implemented Tag and IterationTag
interfaces with the default implementation.
• If we want to prepare custom tags with the TagSupport class then we have to take
a user defined class, which must be a subclass to TagSupport class.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Predefined support
public interface TagSupport implements IterationTag {
public static final int EVAL_BODY_INCLUDE;
public static final int SKIP_BODY;
public static final int EVAL_PAGE;
public static final int SKIP_PAGE;
public static final int EVAL_BODY_AGAIN;
public PageContext pageContext;
public Tag t;
public void setPageContext(PageContext pageContext) {
this.pageContext=pageContext;
}
public void setParent(Tag t) {
this.t=t;
public Tag getParent() {
return t;
}
public int doStartTag()throws JspException {
return SKIP_BODY;
}
public int doAfterBody()throws JspException {
return SKIP_BODY;
}
public int doEndTag()throws JspException {
return EVAL_PAGE;
}
public void release() { }
}
User defined class
public class MyHandler implements TagSupport
{
}

Example

hello.jsp
<%@taglib uri="/WEB-INF/hello.tld" prefix="mytags"%>
<mytags:iterate times="10"><br>
Hi Mohit how r u
</mytags:iterate>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

hello.tld
<taglib>
<jsp-version>2.1</jsp-version>
<tlib-version>1.0</tlib-version>
<tag>
<name>iterate</name>
<tag-class>com.java.example.Iteration</tag-class>
<body-content>jsp</body-content>
<attribute>
<name>times</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>

Iteration.java
package com.java.example;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
public class Iteration extends TagSupport{
private int times;
private int count=1;
public void setTimes(int times) {
this.times = times;
}
@Override
public int doAfterBody() throws JspException {
if(count<times){
count++;
return EVAL_BODY_AGAIN;
}
else{
return SKIP_BODY;
}}
@Override
public int doStartTag() throws JspException {
return EVAL_BODY_INCLUDE;
}}

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Example

Hello.jsp
<%@taglib uri="/WEB-INF/hello.tld" prefix="mytags"%>
<mytags:loop start="1" end="20"><br>
Hi Mohit how r u
</mytags:loop>
remaining page of the JSP

hello.tld
<taglib>
<jsp-version>2.1</jsp-version>
<tlib-version>1.0</tlib-version>
<tag>
<name>loop</name>
<tag-class>com.java.example.Iteration</tag-class>
<body-content>jsp</body-content>
<attribute>
<name>start</name>
<required>true</required>
</attribute>
<attribute>
<name>end</name>
<required>true</required>
</attribute>
</tag>
</taglib>

Iteration.jsp
package com.java.example;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
public class Iteration extends TagSupport{
private int start;
private int end;
public void setStart(int start)
{
this.start = start;
}

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

public void setEnd(int end)


{
this.end = end;
}
@Override
public int doAfterBody() throws JspException
{
if(end>start)
{
start++;
return EVAL_BODY_AGAIN;
}
else
{
return EVAL_PAGE;
}
}
@Override
public int doStartTag() throws JspException
{
return EVAL_BODY_INCLUDE;
}
}

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Best Training Institute
for Graduates
with
Live Online & Offline Classes Available

Join us for Better Career and Job Guarantee

Full Stack Web Development


Top Edge (MERN Stack) HTML, CSS, JavaScript, ES,
Git, ReactJS, Node, Express, MySQL & MongoDB

Training Full Stack Engineer


Java, JavaScript, ReactJS, Spring, SpringBoot
Hibernate, Linux, AWS, Git, DevOps & Jira

Programs Digital Marketing


Social Media, Website Design, SEO,
Google Ads, Freelancing & Many More

Guaranteed Package (In Writing)


▪ 3-5 Lakhs (With 6 Months Training Programs)
▪ 6-8 Lakhs (With 12 Months Training Programs)
▪ 10 Lakhs+ (With 2 Years Training Programs)

Amenities
▪ Digital Notes ▪ Working Experience
▪ Live Training Sessions ▪ Job Recommendations
▪ Project Assistance ▪ Professional Development
▪ Interview Preparation ▪ Digital Resume & Portfolio

LEARN-2-EARN LABS TRAINING INSTITUTE


Anna Icon Complex, near Kargil Petrol Pump, Sikandra-Bodla Road, Sikandra, Agra
Website : www.LearntoearnLabs.com
Call : 91-9548868337 / +91-9837705705
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Nested Tags

• Defining a tag inside a tag is called as Nested Tag.


• In custom tags application, if we declare any nested tag then we have to provide a
separate configuration in tld file and we have to prepare a separate TagHandler
class under classes folder.

hello.jsp
<%@taglib uri="/WEB-INF/hello.tld" prefix="mytags"%>
<mytags:if condition='<%=10<20%>'>
<mytags:true>condition is true</mytags:true><br>
<mytags:false>condition is false</mytags:false><br>
</mytags:if>
rest of the JSP code

hello.tld
<taglib>
<jsp-version>2.1</jsp-version>
<tlib-version>1.0</tlib-version>
<tag>
<name>if</name>
<tag-class>com.java.example.IfCondition</tag-class>
<body-content>jsp</body-content>
<attribute>
<name>condition</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
<tag>
<name>true</name>
<tag-class>com.java.example.True</tag-class>
<body-content>jsp</body-content>
</tag>
<tag>
<name>false</name>
<tag-class>com.java.example.False</tag-class>
<body-content>jsp</body-content>
</tag>
</taglib>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Condition.java
package com.java.example;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
public class IfCondition extends TagSupport{
private boolean condition;
public void setCondition(boolean condition) {
this.condition = condition;
}
public boolean getCondition(){
return condition;
}
@Override
public int doStartTag() throws JspException {
return EVAL_BODY_INCLUDE;
}
@Override
public int doEndTag() throws JspException
{
return EVAL_PAGE;
}
}

True.java
package com.java.example;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
public class True extends TagSupport {
@Override
public int doStartTag() throws JspException {
IfCondition f = (IfCondition)getParent();
boolean b = f.getCondition();
if(b==true){
return EVAL_BODY_INCLUDE;
}
else {
return SKIP_BODY;
}
}
}

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

False.java
package com.java.example;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
public class False extends TagSupport {
@Override
public int doStartTag() throws JspException {
IfCondition f = (IfCondition)getParent();
boolean b = f.getCondition();
if(b==true)
{
return SKIP_BODY;
}
else
{
return EVAL_BODY_INCLUDE;
}
}
}

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Example

empdetails.jsp
<%@taglib uri="/WEB-INF/emp.tld" prefix="emp"%>
<emp:empDetails/>

emp.tld
<taglib>
<jsp-version>2.1</jsp-version>
<tlib-version>1.0</tlib-version>
<tag>
<name>empDetails</name>
<tag-class> com.java.example.EmpDetails</tag-class>
<body-content>empty</body-content>
</tag>
</taglib>

EmpDetails.java
package com.java.example;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.sql.*;
public class EmpDetails extends TagSupport{
Connection con;
Statement st;
ResultSet rs;

public EmpDetails(){
try{
Class.forName("com.mysql.cj.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/se
rvletdb","root","android");
st=con.createStatement();
}
catch (Exception e){
e.printStackTrace();
}
}

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

public int doStartTag() throws JspException


{
try
{
JspWriter out=pageContext.getOut();
rs=st.executeQuery("select * from emp");
ResultSetMetaData rsmd=rs.getMetaData();
int count=rsmd.getColumnCount();
out.println("<html><body bgcolor='pink'>");
out.println("<center><br><br>");
out.println("<table border='1' bgcolor='lightyellow'>");
out.println("<tr>");
for (int i=1;i<=count;i++)
{
out.println("<td><b><font size='6'
color='red'><center>"+rsmd.getColumnName(i)+"</center></fon
t></b></td>");
}
out.println("</tr>");
while (rs.next())
{
out.println("<tr>");
for (int i=1;i<=count;i++)
{
out.println("<td><b><font
size='5'>"+rs.getString(i)+"</font></b></td>");
}
out.println("</tr>");
}
out.println("</table></center></body></html>");
}
catch (Exception e)
{
e.printStackTrace();
}
return SKIP_BODY;
}
}

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Body Tags

• Up to now in our custom tags (simple classic tags, iteration tags) we prepared
custom tags with the body, where we did not perform updations over the custom
tag body, just we scanned custom tag body and displayed on the client browser.
• If we want to perform updations over the custom tag body then we have to use
Body Tags.
• If we want to design body tags in JSP technology then the respective TagHandler
class must implement BodyTag interface either directly or indirectly.

BodyTag
package javax.servlet.jsp.tagext;
import javax.servlet.jsp.JspException;
public interface BodyTag extends IterationTag
{
public abstract void setBodyContent(BodyContent bodycontent);
public abstract void doInitBody()throws JspException;
public static final int EVAL_BODY_TAG = 2;
public static final int EVAL_BODY_BUFFERED = 2;
}

All methods at inherited level


public interface BodyTag extends IterationTag
{
public static final int EVAL_BODY_INCLUDE;
public static final int SKIP_BODY;
public static final int EVAL_PAGE;
public static final int SKIP_PAGE;
public static final int EVAL_BODY_AGAIN;
public static final int EVAL_BODY_BUFFERED;
public void setPageContext(PageContext pageContext);
public void setParent(Tag t);
public Tag getParent();
public int doStartTag()throws JspException;
public void doInitBody()throws JspException;
public void setBodyContent(BodyContent bodyContent);
public int doAfterBody()throws JspException;
public int doEndTag()throws JspException;
public void release();
}

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

User defined class


public class MyHandler implements BodyTag
{
//write the logics here;
}

In case of body tags, there are 3 possible return values from doStartTag() method.
a) EVAL_BODY INCLUDE
If we return EVAL_BODY_INCLUDE constant from doStartTag() method then
container will evaluate the custom tag body i.e. display as it is the custom tag body
on client browser.
b) SKIP_BODY
If we return SKIP_BODY constant from doStartTag() method then container will skip
the custom tag body.
c) EVAL_BODY_BUFFERED
If we return EVAL_BODY_BUFFERED constant from doStartTag() method then
container will store custom tag body in a buffer then access setBodyContent(_)
method.

To access setBodyContent(_) method container will prepare BodyContent object with the
buffer.
After executing setBodyContent(_) method container will access doInitBody() method in
order to prepare BodyContent object for allow modifications.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Life Cycle of BodyTag interface

• To prepare custom tags if we use above approach then the respective TagHandler
class must implement all the methods declared in BodyTag interface irrespective
of the application requirement.
• This approach may increase burden to the developers and unnecessary methods
in the custom tag application.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

To overcome this problem we will use an alternative provided by JSP technology i.e.
javax.servlet.jsp.tagext.BodyTagSupport class.

• BodyTagSupport class is a concrete class, a direct implementation class to BodyTag


interface and it has provided the default implementation for all the methods
declared in BodyTag interface.
• If we want to prepare custom tags with BodyTagSupport class then the respective
TagHandler class must extend BodyTagSupport and overrides the only required
methods.

public class BodyTagSupport implements BodyTag {


public static final int EVAL_BODY_INCLUDE;
public static final int SKIP_BODY;
public static final int EVAL_PAGE;
public static final int SKIP_PAGE;
public static final int EVAL_BODY_AGAIN;
public static final int EVAL_BODY_BUFFERED;
public PageContext pageContext;
public Tag t;
public BodyContent bodyContent;
public void setPageContext(PageContext pageContext) {
this.pageContext=pageContext;
}
public void setParent(Tag t) {
this.t=t;
}
public Tag getParent() {
return t;
}
public int doStartTag()throws JspException {
return EVAL_BODY_BUFFERED;
}
public void setBodyContent(BodyContent bodyContent) {
this.bodyContent=bodyContent;
}
public void doInitBody()throws JspException
{}
public int doAfterBody()throws JspException {
return SKIP_BODY;
}

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

public int doEndTag()throws JspException


{
return EVAL_PAGE;
}
public void release()
{
}
}

In case of body tags, custom tag body will be available in BodyContent object, to get
custom tag body from BodyContent object we have to use the following method.

public String getString()

To send modified data to the response object we have to get JspWriter object from
BodyContent, for this we have to use the following method.

public JspWriter getEnclosingWriter()

Example

hello.jsp
<%@taglib uri="/WEB-INF/hello.tld" prefix="mytags"%>
<mytags:reverse>
Learn2Earn Labs
</mytags:reverse>

hello.tld
<taglib>
<jsp-version>2.1</jsp-version>
<tlib-version>1.0</tlib-version>
<tag>
<name>reverse</name>
<tag-class>com.java.example.Reverse</tag-class>
<body-content>jsp</body-content>
</tag>
</taglib>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Reverse.java
package com.java.example;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;

public class Reverse extends BodyTagSupport{

public int doEndTag()throws JspException


{
try
{
String data=bodyContent.getString();
StringBuffer sb=new StringBuffer(data);
StringBuffer rdata=sb.reverse();
bodyContent.getEnclosingWriter().println(rdata);
}
catch(Exception e)
{
e.printStackTrace();
}
return EVAL_PAGE;
}
}

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Example

editor.html
<html>
<body bgcolor="lightgreen">
<b><font size="6" color="red">
<form action="./result.jsp">
<pre>
Enter SQL Query
<textarea name="query" rows="5" cols="50"></textarea>
<input type="submit" value="GetResult"/>
</pre>
</form></font></b>
</body>
</html>

result.jsp
<%@taglib uri="/WEB-INF/result.tld" prefix="dbtags"%>
<jsp:declaration>
String query;
</jsp:declaration>
<jsp:scriptlet>
query=request.getParameter("query");
</jsp:scriptlet>
<dbtags:query>
<jsp:expression>query</jsp:expression>
</dbtags:query>

result.tld
<taglib>
<jsp-version>2.1</jsp-version>
<tlib-version>1.0</tlib-version>
<tag>
<name>query</name>
<tag-class>com.java.example.Result</tag-class>
<body-content>jsp</body-content>
</tag>
</taglib>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Result.java
package com.java.Example;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.sql.*;
public class Result extends BodyTagSupport{
Connection con;
Statement st;
ResultSet rs;
public Result()
{
try
{
Class.forName("com.mysql.cj.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/se
rvletdb","root","android");
st=con.createStatement();
}
catch (Exception e)
{
e.printStackTrace();
}
}
public int doEndTag() throws JspException
{
try
{
JspWriter out=pageContext.getOut();
String query=bodyContent.getString();
boolean b=st.execute(query);
if (b==true)
{
rs=st.getResultSet();
ResultSetMetaData rsmd=rs.getMetaData();
out.println("<html>");
out.println("<body bgcolor='lightblue'>");
out.println("<center><br><br>");
out.println("<table border='1' bgcolor='lightyellow'>");
int count=rsmd.getColumnCount();
out.println("<tr>");

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

for (int i=1;i<=count;i++)


{
out.println("<td><center><b><font size='6'
color='red'>"+rsmd.getColumnName(i)+"</font></b></ce
nter></td>");
}
out.println("</tr>");
while (rs.next())
{
out.println("<tr>");
for (int i=1;i<=count;i++){
out.println("<td><h1>"+rs.getString(i)+"</h1></td>");
}
out.println("</tr>");
}
out.println("</table></center></body></html>");
}
else
{
int rowCount=st.getUpdateCount();
out.println("<html>");
out.println("<body bgcolor='lightyellow'>");
out.println("<center><b><font size='7' color='red'>");
out.println("<br><br>");
out.println("Record Updated : "+rowCount);
out.println("</font></b></center></body></html>");
}
}
catch (Exception e)
{
e.printStackTrace();
}
return EVAL_PAGE;
}
}

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Simple Tags

Classic tags Vs Simple tags

• Classic tags are more API independent, but Simple tags are less API independent.
• If we want to design custom tags by using classic tag library then we have to
remember three types of life cycles.
• If we want to design custom tags by using simple tag library then we have to
remember only one type of life cycle.
• In case of classic tag library, all the TagHandler class objects are cacheable objects,
but in case of simple tag library, all the TagHandler class objects are non-cacheable
objects.
• In case of classic tags, all the custom tags are not body tags by default, but in case
of simple tags, all the custom tags are having body tags capacity by default.
• If we want to design custom tags by using simple tag library then the respective
TagHandler class must implements SimpleTag interface either directly or indirectly.

Predefind support
package javax.servlet.jsp.tagext;
import java.io.IOException;
import javax.servlet.jsp.JspContext;
import javax.servlet.jsp.JspException;
public interface SimpleTag extends JspTag{
public abstract void doTag()throws JspException, IOException;
public abstract void setParent(JspTag jsptag);
public abstract JspTag getParent();
public abstract void setJspContext(JspContext jspcontext);
public abstract void setJspBody(JspFragment jspfragment);
}

User defined class


public class MyHandler implements SimpleTag{
//write the logics here
}

• Where jspContext is an implicit object available in simple tag library, it is same as


pageContext, it can be used to make available all the JSP implicit objects.
• Where jspFragment is like bodyContent in classic tag library, it will accommodate
custom tag body directly.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

• Where setJspContext(_) method can be used to inject JspContext object into the
present web application.
• Where setParent(_) method can be used to inject parent tags TagHandler class
object reference into the present TagHandler class.
• Where getParent() method can be used to get parent tags TagHandler class object.
• Where setJspBody(_) method is almost all equal to setBodyContent(_) method in
order to accommodate custom tag body.
• Where doTag() method is equivalent to doStartTag() method and doEndTag()
method in order to perform an action.

Life Cycle of SimpleTag interface

• To design custom tags if we use approach then the respective TgaHandler class
must implement SimpleTag interface i.e. it must implement all the methods which
are declared in SimpleTag interface.
• This approach will increase burden to the developers and unnecessary methods in
the custom tags.
To overcome this problem JSP technology has provided an alternative in the form of
javax.servlet.jsp.tagext.SimpleTagSupport class.

• SimpleTagSupport is a concrete class provided by Jsp technology as an


implementation class to SimpleTag interface with default implementation.
• If we want to design custom tags by using SimpleTagSupport class then the
respective TagHandler class must be extended from SimpleTagSupport class and
where we have to override the required methods.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Predefined support

public interface SimpleTag extends JspTag {


private JspContext jspContext;
private JspFragment jspFragment;
private JspTag jspTag;
public void setJspContext(JspContext jspContext) {
this.jspContext=jspContext;
}
public void setParent(JspTag t) {
this.jspTag=jspTag;
}
public void setJspBody(JspFragment jspFragment) {
this.jspFragment=jspFragment;
}
public JspTag getParent() {
return jspTag;
}

public JspFragment getJspBody() {


return jspFragment;
}
public JspContext getJspContext() {
return jspContext;
}
public void doTag()throws JspException, IOException
{}
}

User defined class


public class MyHandler extends SimpleTagSupport
{
//write the logics here
}

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Example

hello.jsp
<%@taglib uri="/WEB-INF/hello.tld" prefix="mytags"%>
<mytags:hello/>

hello.tld
<taglib>
<jsp-version>2.1</jsp-version>
<tlib-version>1.0</tlib-version>
<tag>
<name>hello</name>
<tag-class>com.java.example.Hello</tag-class>
<body-content>empty</body-content>
</tag>
</taglib>

Hello.java
package com.java.example;
import java.io.IOException;
import javax.servlet.jsp.JspContext;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.SimpleTagSupport;

public class Hello extends SimpleTagSupport{


@Override
public void doTag() throws JspException, IOException {
JspContext context = getJspContext();
JspWriter writer = context.getOut();
writer.println("this is Sample Tag application");
}
}

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Accessing Tag Body


To print custom tag body use below code.

Example

hello.jsp
<%@taglib uri="/WEB-INF/hello.tld" prefix="mytags"%>
<mytags:hello>
hi this is body of custom tag<br>
</mytags:hello>

hello.tld
<taglib>
<jsp-version>2.1</jsp-version>
<tlib-version>1.0</tlib-version>
<tag>
<name>hello</name>
<tag-class>com.java.example.Hello</tag-class>
<body-content>scriptless</body-content>
</tag>
</taglib>

Hello.java
package com.java.example;
import java.io.IOException;
import java.io.StringWriter;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.SimpleTagSupport;
public class Hello extends SimpleTagSupport{
@Override
public void doTag() throws JspException, IOException {
JspWriter writer = getJspContext().getOut();
StringWriter stringWriter = new StringWriter();
getJspBody().invoke(stringWriter);
writer.println("this is Sample Tag application");
writer.println(stringWriter.toString());
}
}

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Attributes in custom tags


To provide the attributes in custom tags use below code.

Example
hello.jsp
<%@taglib uri="/WEB-INF/hello.tld" prefix="mytags"%>
<mytags:hello msg="learn2earn labs">
hi this is body of custom tag<br>
</mytags:hello>

hello.tld
<taglib>
<jsp-version>2.1</jsp-version>
<tlib-version>1.0</tlib-version>
<tag>
<name>hello</name>
<tag-class>com.java.example.Hello</tag-class>
<body-content>scriptless</body-content>
<attribute>
<name>msg</name>
</attribute>
</tag>
</taglib>

Hello.java
package com.java.example;

import java.io.IOException;
import java.io.StringWriter;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.SimpleTagSupport;

public class Hello extends SimpleTagSupport{


private String msg;
public void setMsg(String msg) {
this.msg = msg;
}

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

@Override
public void doTag() throws JspException, IOException {
JspWriter writer = getJspContext().getOut();
StringWriter stringWriter = new StringWriter();
getJspBody().invoke(stringWriter);
writer.println("this is Sample Tag application");
writer.println(stringWriter.toString());
writer.println("<br>");
writer.println(msg);
}
}

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Custom URI in JSP custom tags

We can use custom uri in jsp custom tags by specifying tld file location in web.xml file.
The web container will get the information about tld file from web.xml file.

Example

hello.jsp
<%@taglib uri="mytags" prefix="xxx"%>
<xxx:hello>
Hello Students how r u <br>
</xxx:hello>
this is rest of the JSP Application

web.xml
<web-app>
<jsp-config>
<taglib>
<taglib-uri>mytags</taglib-uri>
<taglib-location>/WEB-INF/hello.tld</taglib-location>
</taglib>
</jsp-config>
</web-app>

hello.tld
<taglib>
<jsp-version>2.1</jsp-version>
<tlib-version>1.0</tlib-version>
<uri>mytags</uri>
<tag>
<name>hello</name>
<tag-class>com.java.example.TaglibUri</tag-class>
<body-content>jsp</body-content>
</tag>
</taglib>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

TaglibUri.java
package com.java.example;

import java.io.IOException;
import java.util.Date;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.TagSupport;

public class TaglibUri extends TagSupport{


@Override
public int doStartTag() throws JspException {
JspWriter writer = pageContext.getOut();
try {
Date d = new Date();
writer.println("this is custom tag application URI attribute");
writer.println("<br/>");
writer.println("today date is="+d);
writer.println("<br/>");
}
catch (IOException e) {
e.printStackTrace();
}
returnEVAL_BODY_INCLUDE;
}
@Override
publicint doEndTag() throws JspException {
returnEVAL_PAGE;
}
}

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Best Training Institute
for Graduates
with
Live Online & Offline Classes Available

Join us for Better Career and Job Guarantee

Full Stack Web Development


Top Edge (MERN Stack) HTML, CSS, JavaScript, ES,
Git, ReactJS, Node, Express, MySQL & MongoDB

Training Full Stack Engineer


Java, JavaScript, ReactJS, Spring, SpringBoot
Hibernate, Linux, AWS, Git, DevOps & Jira

Programs Digital Marketing


Social Media, Website Design, SEO,
Google Ads, Freelancing & Many More

Guaranteed Package (In Writing)


▪ 3-5 Lakhs (With 6 Months Training Programs)
▪ 6-8 Lakhs (With 12 Months Training Programs)
▪ 10 Lakhs+ (With 2 Years Training Programs)

Amenities
▪ Digital Notes ▪ Working Experience
▪ Live Training Sessions ▪ Job Recommendations
▪ Project Assistance ▪ Professional Development
▪ Interview Preparation ▪ Digital Resume & Portfolio

LEARN-2-EARN LABS TRAINING INSTITUTE


Anna Icon Complex, near Kargil Petrol Pump, Sikandra-Bodla Road, Sikandra, Agra
Website : www.LearntoearnLabs.com
Call : 91-9548868337 / +91-9837705705
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

JSP Standard Tag Library (JSTL)


• In JSP technology, by using scripting elements we are able to provide Java code
inside the JSP pages.
• To preserve JSP principles we have to eliminate scripting elements, for this we have
to use JSP Actions.
• In case of JSP Actions, we will use standard actions as an alternative to scripting
elements, but which are limited in number and having bounded functionality so
that standard actions are not specified the required application format.
• Still, it is required to provide Java code inside the JSP pages.
• In above context, to eliminate Java code completely from JSP pages we have to
use custom actions. In case of custom actions, to implement simple Java syntaxes
like if condition, for loop & so on, we have to provide a lot of Java code internally.

To overcome the above problem JSP technology has provided a separate tag library with
simple Java syntaxes implementation and frequently used operations.
JSTL is an abstraction provided by Sun Microsystems (now owned by Oracle), but where
implementations are provided by all the server vendors. With the above convention
Apache Tomcat has provided JSTL implementation in the form of the jar files as
standard.jar, jstl.jar.
Apache Tomcat has provided the above two jar files in the following location.
C:\Tomcat7.0\webapps\examples\WEB_INF\lib
If we want to get JSTL support in our JSP pages then we have to keep the standard.jar,
jstl.jar files in our web application lib folder.
JSTL has provided the complete tag library in the form of the following five types of tags.
1. Core Tags
2. XML Tags
3. Internationalization or I18N Tags (Formatted tags)
4. SQL Tags
5. Functions tags
To get a particular tag library support into the present JSP page we have to use the
following standard URL’s to the attribute in the respective taglib directive.
http://java.sun.com/jstl/core
http://java.sun.com/jstl/xml
http://java.sun.com/jstl/fmt
http://java.sun.com/jstl/sql
http://java.sun.com/JSP/jstl/function

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Core Tags
In JSTL, core tag library was divided into the following 4 types.
1. General Purpose Tags
• <c:set----->
• <c:remove----->
• <c:catch----->
• <c:out----->
2. Conditional Tags
• <c:if----->
• <c:choose----->
• <c:when----->
• <c:otherwise----->
3. Iterate Tags
• <c:forEach----->
• <c:forTokens----->
4. Url-Based Tags
• <c:import----->
• <c:url----->
• <c:redirect----->

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

General Purpose Tags


1. <c:set----->
This tag can be used to declare a single name value pair onto the specified scope.

Syntax
<c:set var=”--” value=”--” scope=”--”/>
Where var attribute will take a variable i.e. key in key-value pair.
Where value attribute will take a particular value i.e. a value in key-value pair.
Where scope attribute will take a particular scope to include the specified key-value pair.

2. <c:out----->
This tag can be used to display a particular value on the client browser.
Syntax
<c:out value=”--”/>
Where value attribute will take a static data or an expression.
To present an expression with value attribute we have to use the following format.
Syntax: ${expression}
<c:out value”${a}”/>
If the container encounters above tag then container will search for ‘a’ attribute in the
page scope, request scope, session scope and application scope.

Example
core.jsp
<%@taglib uri="http://java.sun.com/jstl/core" prefix="c"%>
<%@page isELIgnored="true"%>
<html><body>
<center><b>
<font size="7">
<c:set var="a" value="Learn2Earn Labs" scope="request"/>
<br>
<c:out value="core tag library"/>
<br><br>
<c:out value="${a}"/>
</font></b>
</center>
<body><html>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

3. <c:remove----->
This tag can be used to remove an attribute from the specified scope.

Syntax
<c:remove var=”--” scope=”--”/>
Where scope attribute is optional, if we have not specified scope attribute then container
will search for the respective attribute in the page scope, request scope, session scope
and application scope.

Example
core.jsp
<%@taglib uri="http://java.sun.com/jstl/core" prefix="c"%>
<%@page isELIgnored="true"%>
<html>
<body>
<center><b><font size="7">
<c:set var="a" value="Learn2Earn Labs" scope="request"/>
<br>
a-----><c:out value="${a}"/>
<br><br>
<c:remove var="a" scope="request"/>
a-----><c:out value="${a}"/>
</font></b></center>
<body>
<html>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

4. <c:catch----->:
This tag can be used to catch an Exception raised in its body.

Syntax
<c:catch var=”--”>
---------- </c:catch>
Where var attribute will take a variable to hold the generated Exception object reference.

Example
core.jsp
<%@taglib uri="http://java.sun.com/jstl/core" prefix="c"%>
<%@page isELIgnored="true"%>
<html>
<body>
<center><b><font size="7">
<c:catch var="e">

<JSP:scriptlet>
java.util.Date d=null;
out.println(d.toString());
</JSP:scriptlet>

</c:catch>
<c:out value="${e}"/>
</font></b></center>
<body>
<html>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Conditional Tags

1. <c:if----->
This tag can be used to implement if conditional statement.

Syntax
<c:if test=”--”/>

Where test attribute is a boolean attribute, it may take either true or false values.

Example
Core.jsp
<%@taglib uri="http://java.sun.com/jstl/core" prefix="c"%>
<%@page isELIgnored="true"%>
<html>
<body>
<center><b>
<font size="7">
<c:set var="a" value="10"/>
<c:set var="b" value="20"/>
<c:if test="${a<b}">
condition is true
</c:if>
<br>
out of if
</font></b>
</center>
<body>
<html>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

2. <c:choose----->, <c:when-----> and <c:otherwise----->


These tags can be used to implement switch programming construct.

Syntax
<c:choose>
<c:when test=”--”>
-----------
</c:when>
-----------
<c:otherwise>
-----------
</c:otherwise>
</c:choose>

Example
core.jsp
<%@taglib uri="http://java.sun.com/jstl/core" prefix="c"%>
<%@page isELIgnored="true"%>
<html>
<body>
<center><b><font size="7">
<c:set var="a" value="10"/>
<c:choose>
<c:when test="${a==10}">
TEN
</c:when>
<c:when test="${a==15}">
FIFTEEN
</c:when>
<c:when test="${a==20}">
TWENTY
</c:when>
<c:otherwise>
Number is not in 10,15 and 20
</c:otherwise>
</c:choose>
</font></b></center>
<body>
<html>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Iterator Tags

1. <c:forEach----->
This tag can be used to implement for loop to provide iterations on its body and it can
be used to perform iterations over an array of elements or Collection of elements.

Syntax 1
<c:forEach var=”--” begin=”--” end=”--” step=”--”>
------------
</c:forEach>
Where var attribute will take a variable to hold up the loop index value at each and every
iteration.
Where begin and end attribute will take start index value and end index value.

Syntax 2
<c:forEach var=”--” items=”--”>
------------
</c:forEach>
Where var attribute will take a variable to hold up an element from the respective
Collection at each and every iteration.
Where items attribute will take the reference of an array or Collection from either of the
scopes page, request, session and application.

Example
core.jsp
<%@taglib uri="http://java.sun.com/jstl/core" prefix="c"%>
<%@page isELIgnored="true"%>
<html><body>
<center><b><font size="7">
<c:forEach var="a" begin="0" end="10" step="2">
<c:out value="${a}"/><br>
</c:forEach>
<% String[] s={"A","B","C"};
request.setAttribute("s",s);
%>
<br>
<c:forEach var="x" items="${s}">
<c:out value="${x}"/><br>
</c:forEach>
</font></b></center><body><html>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

2. <c:forTokens----->
This tag can be used to perform String Tokenization on a particular String.

Syntax
<c:forTokens var=”--” items=”--” delims=”--”>
------------
</c:forTokens>

Where var attribute will take a variable to hold up token at each and every iteration.
Where items attribute will take a String to tokenize.
Where delims attribute will take a delimiter to perform tokenization.

Example
core.jsp
<%@taglib uri="http://java.sun.com/jstl/core" prefix="c"%>
<%@page isELIgnored="true"%>
<html>
<body>
<center><b><font size="7">
<c:forTokens var="token" items="Learn2Earn Labs is the Best Training
Institute" delims="">
<c:out value="${token}"/><br>
</c:forTokens>
</font></b>
</center>
<body>
<html>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Url-Based Tags

1. <c:import----->
This tag can be used to import the content of the specified target resource into the
present JSP page.

Example
section.jsp
<center><h1>This is section.JSP</h1></center>

core.jsp
<%@taglib uri="http://java.sun.com/jstl/core" prefix="c"%>
<%@page isELIgnored="true"%>
<html>
<body>
<center>
<b><font size="7">
Start
<br>
<c:import url="section.jsp"/>
<br>
End
</font></b>
</center>
<body>
<html>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

2. <c:url----->
This tag can be used to represent the specified url.

Syntax
<c:url value=”--”/>
Example
core.jsp
<%@taglib uri="http://java.sun.com/jstl/core" prefix="c"%>
<%@page isELIgnored="true"%>
<html>
<body>
<center><b><font size="7">
<a href='<c:url value="http://localhost:2020/loginapp"/>'>Login
Application</a>
</font></b></center>
<body>
<html>

3. <c:redirect----->
This tag can be used to implement Send Redirect Mechanism from a particular JSP page.

Syntax
<c:redirect url=”--”/>

Example

core.jsp
<%@taglib uri="http://java.sun.com/jstl/core" prefix="c"%>
<%@page isELIgnored="true"%>
<html>
<body>
<center><b><font size="7">
<c:redirect url="/editor.html"/>
</font></b></center>
<body>
<html>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

SQL Tags

The main purpose of SQL tag library is to interact with the database in order to perform
the basic database operations.

JSTL has provided the following set of tags as part of SQL tag library.
1. <sql:setDataSource----->
2. <sql:update----->
3. <sql:query----->
4. <sql:transaction----->
5. <sql:param----->
6. <sql:dateParam----->

<sql:setDataSource----->
This tag can be used to prepare the Jdbc environment like Driver loading, establish the
connection.
Syntax
<sql:setDataSource driver=”--” url=”--” user=”--” password=”--”/>

Where driver attribute will take the respective Driver class name.
Where url attribute will take the respective Driver url.
Where user and password attributes will take database user name and password.

2. <sql:update----->
This tag can be used to execute all the updation group SQL queries like create, insert,
update, delete, drop and alter.
Syntax 1
<sql:update var=”--” sql=”--”/>
Syntax 2
<sql:update var=”--”> ------ query ------ </sql:update>

In the above <sql:update> tag we are able to provide the SQL queries in 2 ways.
a) Statement style SQL queries, which should not have positional parameters.
b) PreparedStatement style SQL queries, which should have positional parameters.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

If we use PreparedStatement style SQL queries then we have to provide values to the
positional parameters, for this we have to use the following SQL tags.

1. <sql:param----->
This tag can be used to set a normal value to the positional parameter.
Syntax 1
<sql:param value=”--”/>
Syntax 2
<sql:param> ------ value ------ </sql:param>
2. <sql:dateParam----->
This tag can be used to set a value to parameter representing data.
Syntax 1
<sql:dateParam value=”--”/>
Syntax 2
<sql:dateParam>value</sql:dateParam>

Example
sql.jsp
<%@taglib uri="http://java.sun.com/jstl/core" prefix="c"%>
<%@taglib uri="http://java.sun.com/jstl/sql" prefix="sql"%>
<%@page isELIgnored="true"%>
<html>
<body>
<center><b><font size="7">
<sql:setDataSource driver="com.mysql.cj.jdbc.Driver"
url="jdbc:mysql://localhost:3306/jspdb" user="root" password="android"/>

<sql:update var="result">
create table emp12 (eid INT, ename VARCHAR(10), esal DECIMAL(10, 2))
</sql:update>
Row Count ...... <c:out value="${result}"/>
</font></b></center>
</body>
</html>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Example
sql.jsp
<%@taglib uri="http://java.sun.com/jstl/core" prefix="c"%>
<%@taglib uri="http://java.sun.com/jstl/sql" prefix="sql"%>
<%@page isELIgnored="true"%>
<html>
<body>
<center><b><font size="7">
<sql:setDataSource driver="com.mysql.cj.jdbc.Driver"
url="jdbc:mysql://localhost:3306/jspdb" user="root"
password="android"/>
<sql:update var="result" sql="insert into emp1 values(101,'neha',5000)"/>
Row Count ...... <c:out value="${result}"/>
</font></b></center>
</body>
</html>

Example
sql.jsp
<%@taglib uri="http://java.sun.com/jstl/core" prefix="c"%>
<%@taglib uri="http://java.sun.com/jstl/sql" prefix="sql"%>
<%@page isELIgnored="true"%>
<html>
<body>
<center><b><font size="7">
<sql:setDataSource driver="com.mysql.cj.jdbc.Driver"
url="jdbc:mysql://localhost:3306/jspdb" user="root"
password="android"/>
<sql:update var="result" sql="insert into emp1 values(?,?,?)">
<sql:param value="103"/>
<sql:param>udit</sql:param>
<sql:param value="7000"/>
</sql:update>
Row Count ...... <c:out value="${result}"/>
</font></b>
</center>
</body>
</html>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Example
sql.jsp
<%@taglib uri="http://java.sun.com/jstl/core" prefix="c"%>
<%@taglib uri="http://java.sun.com/jstl/sql" prefix="sql"%>
<%@page isELIgnored="true"%>
<html>
<body>
<center><b><font size="7">
<sql:setDataSource driver="com.mysql.cj.jdbc.Driver"
url="jdbc:mysql://localhost:3306/jspdb" user="root" password="android"/>
<sql:update var="result">
update emp1 set esal=esal+? where esal>?
<sql:param>500</sql:param>
<sql:param>5000</sql:param>
</sql:update>
Row Count ...... <c:out value="${result}"/>
</font></b></center></body>
</html>

Example
sql.jsp
<%@taglib uri="http://java.sun.com/jstl/core" prefix="c"%>
<%@taglib uri="http://java.sun.com/jstl/sql" prefix="sql"%>
<%@page isELIgnored="true"%>
<html>
<body>
<center><b><font size="7">
<sql:setDataSource driver="com.mysql.cj.jdbc.Driver"
url="jdbc:mysql://localhost:3306/jspdb" user="root" password="android"/>
<sql:update var="result">
DELETE FROM emp1 WHERE esal > 5000
</sql:update>
Row Count ...... <c:out value="${result}"/>
</font></b></center>
</body>
</html>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

3. <sql:query----->
This tag can be used to execute selection group SQL queries in order to fetch the data
from database table.

Syntax 1
<sql:query var=”--” sql=”--”/>
Syntax 2
<sql:query var=”--”> ----- query ----- </sql:query>

• If we execute selection group SQL queries by using <sql:query> tag then SQL tag
library will prepare result object to hold up fetched data.
• In SQL tag library, result object is a combination of ResultSet object and
ResultSetMetaData object.
• In result object, all the column names will be represented in the form a single
dimensional array referred by columnNames predefined variable and column data
(table body) will be represented in the form of 2-dimensionnal array referred by
rowsByIndex predefined variable.

Example
sql.jsp
<%@taglib uri="http://java.sun.com/jstl/core" prefix="c"%>
<%@taglib uri="http://java.sun.com/jstl/sql" prefix="sql"%>
<%@page isELIgnored="true"%>
<html>
<body>
<center><b><font size="7">
<sql:setDataSource driver="com.mysql.cj.jdbc.Driver"
url="jdbc:mysql://localhost:3306/jspdb" user="root" password="android"/>
<sql:query var="result" sql="select * from emp"/>
<table border="1" bgcolor="lightyellow">
<tr>
<c:forEach var="columnName"
items="${result.columnNames}">
<td><center><b><font size="6" color="red">
<c:out value="${columnName}"/>
</font></b></center></td>
</c:forEach>
</tr>
<c:forEach var="row" items="${result.rowsByIndex}">
<tr>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

<c:forEach var="column" items="${row}">


<td><b><font size="5">
<c:out value="${column}"/>
</font></b></td>
</c:forEach>
</tr>
</c:forEach>
</table>
</font></b></center>
</body>
</html>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

4. <sql:transaction----->
This tag will represent a transaction, which includes collection of <sql:update> tags and
<sql:query> tags.

I18N Tags(Formatted Tags)


1. <fmt:setLocale----->
This tag can be used to represent a particular Locale.
Syntax
<fmt:setLocale value=”--”/>
Where value attribute will take Locale parameters like en_US, it_IT and so on.
2. <fmt:formatNumber----->
This tag can be used to represent a number w.r.t the specified Locale.
Syntax
<fmt:formatNumber var=”--” value=”--”/>
Where var attribute will take a variable to hold up the formatted number.
Where value attribute will take a number.

3. <fmt:formatDate----->
This tag can be used to format present system date w.r.t. a particular Locale.
Syntax
<fmt:formatDate var=”--” value=”--”/>
Where var attribute will take a variable to hold up the formatted date.
Where value attribute will take the reference of Date object.

4. <fmt:setBundle----->
This tag can be used to prepare ResourceBundle object on the basis of a particular
properties file.
Syntax
<fmt:setBundle var=”--” basename=”--”/>
Where var attribute will take a variable to hold up ResourceBundle object reference.
Where basename attribute will take base name of the properties file.

5. <fmt:message----->
This tag can be used to get the message from ResourceBundle object on the basis of
provided key.
Syntax
<fmt:message var=”--” key=”--”/>
Where var attribute will take a variable to hold up message.
Where key attribute will take key of the message defined in the respective properties file.

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

Example

abc_en_US.properties
#abc_en_US.properties
#-------------------------------
welcome=Welcome to US user

abc_it_IT.properties
#abc_it_IT.properties
#-------------------------------
welcome=Welcome toe Italiano usereo

fmt.jsp
<%@taglib uri="http://java.sun.com/jstl/core" prefix="c"%>
<%@taglib uri="http://java.sun.com/jstl/fmt" prefix="fmt"%>
<%@page isELIgnored="true"%>
<html>
<body>
<center><b><font size="7">
<fmt:setLocale value="it_IT"/>
<fmt:formatNumber var="num" value="123456.789"/>
<c:out value="${num}"/><br><br>
<JSP:useBean id="date" class="java.util.Date">
<fmt:formatDate var="fdate" value="${date}"/>
<c:out value="${fdate}"/>
</JSP:useBean>
<br><br>
<fmt:setBundle basename="abc"/>
<fmt:message var="msg" key="welcome"/>
<c:out value="${msg}"/>
</font></b></center>
</body>
</html>

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability

JSTL Functions

The main purpose of functions tag library is to perform all the String operations which are
defined in the String class.

Example

<%@taglib uri="http://java.sun.com/jstl/core" prefix="c"%>


<%@taglib uri="http://java.sun.com/jstl/functions" prefix="fn"%>
<c:set var="a" value="Learn2Earn Labs"/>
${fn:length(a)}
${fn:concat(a, "Agra")}
${fn:toLowerCase(a)}
${fn:toUpperCase(a)}
${fn:contains(a, "Learn2Earn Labs")}
${fn:startsWith(a, "Join")}
${fn:endsWith(a, "Training Institute")}
${fn:substring(a, 4, 20)}

Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Best Training Institute
for Graduates
with
Live Online & Offline Classes Available

Join us for Better Career and Job Guarantee

Full Stack Web Development


Top Edge (MERN Stack) HTML, CSS, JavaScript, ES,
Git, ReactJS, Node, Express, MySQL & MongoDB

Training Full Stack Engineer


Java, JavaScript, ReactJS, Spring, SpringBoot
Hibernate, Linux, AWS, Git, DevOps & Jira

Programs Digital Marketing


Social Media, Website Design, SEO,
Google Ads, Freelancing & Many More

Guaranteed Package (In Writing)


▪ 3-5 Lakhs (With 6 Months Training Programs)
▪ 6-8 Lakhs (With 12 Months Training Programs)
▪ 10 Lakhs+ (With 2 Years Training Programs)

Amenities
▪ Digital Notes ▪ Working Experience
▪ Live Training Sessions ▪ Job Recommendations
▪ Project Assistance ▪ Professional Development
▪ Interview Preparation ▪ Digital Resume & Portfolio

LEARN-2-EARN LABS TRAINING INSTITUTE


Anna Icon Complex, near Kargil Petrol Pump, Sikandra-Bodla Road, Sikandra, Agra
Website : www.LearntoearnLabs.com
Call : 91-9548868337 / +91-9837705705
LEARN-2-EARN LABS TRAINING INSTITUTE
F-4, First Floor, Anna Icon Complex,
near Kargil Petrol Pump, Sikandra-Bodla Road,
Sikandra, Agra, Uttar Pradesh, India

Website : www.LearntoearnLabs.com

Call : 91-9548868337 / +91-9837705705

You might also like