Servlet & JSP Reference Notes
Servlet & JSP Reference Notes
Notes
[Digital Copy]
Servlet &
Java Server Pages
Institute Director(s)
Institute Vision
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.
Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability
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.
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
Get 5 LPA Or 8 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;
Get 5 LPA Or 8 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>
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
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.
Get 5 LPA Or 8 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");
}}
Get 5 LPA Or 8 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>
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;
Get 5 LPA Or 8 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>
Get 5 LPA Or 8 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
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>
<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
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;
Get 5 LPA Or 8 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>
<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.
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
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
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
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
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;
@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
Amenities
▪ Digital Notes ▪ Working Experience
▪ Live Training Sessions ▪ Job Recommendations
▪ Project Assistance ▪ Professional Development
▪ Interview Preparation ▪ Digital Resume & Portfolio
• 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
To install MySQL Server and MySQL Workbench on your system, follow the below steps.
Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability
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.
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
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
Get 5 LPA Or 8 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");
}
}
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
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
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;
Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability
statement.setString(1, name);
statement.setString(2, city);
status=statement.executeUpdate();
} 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
<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
Get 5 LPA Or 8 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.
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;
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;
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.
Get 5 LPA Or 8 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>
• 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
Get 5 LPA Or 8 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.
Get 5 LPA Or 8 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.
• 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.
Get 5 LPA Or 8 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
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.
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).
Get 5 LPA Or 8 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).
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
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;
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;
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
Amenities
▪ Digital Notes ▪ Working Experience
▪ Live Training Sessions ▪ Job Recommendations
▪ Project Assistance ▪ Professional Development
▪ Interview Preparation ▪ Digital Resume & Portfolio
• 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.
Get 5 LPA Or 8 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.
• 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();
Get 5 LPA Or 8 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 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.
• 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.
• 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 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
Get 5 LPA Or 8 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>
<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;
Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability
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;
gender=request.getParameter("gender");
city=request.getParameter("city");
HttpSession session=request.getSession();
Get 5 LPA Or 8 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
Challenges of HttpSession
• 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.
• 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 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 {
Get 5 LPA Or 8 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();
Get 5 LPA Or 8 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", "");
Get 5 LPA Or 8 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.
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;
response.setContentType("text/html");
PrintWriter out=response.getWriter();
user=request.getParameter("user");
rollno=request.getParameter("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;
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
• 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).
• 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
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;
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
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
• 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.
Get 5 LPA Or 8 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
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
Amenities
▪ Digital Notes ▪ Working Experience
▪ Live Training Sessions ▪ Job Recommendations
▪ Project Assistance ▪ Professional Development
▪ Interview Preparation ▪ Digital Resume & Portfolio
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.
@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;
Get 5 LPA Or 8 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;
@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;
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
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.
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
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
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
}
Get 5 LPA Or 8 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.
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
Get 5 LPA Or 8 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 Listeners offer several use cases and benefits that can significantly enhance the
functionality, performance, and maintainability of a web application.
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
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
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.
• 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
• 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.
Get 5 LPA Or 8 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. Open Eclipse
Start Eclipse and select your workspace.
Get 5 LPA Or 8 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>
Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability
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
Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability
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.
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.
<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>
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();
}
}
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-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>
<!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
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
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);
Get 5 LPA Or 8 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;
Get 5 LPA Or 8 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.
Get 5 LPA Or 8 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;
Get 5 LPA Or 8 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>
Get 5 LPA Or 8 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.
• 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;
Get 5 LPA Or 8 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;
Get 5 LPA Or 8 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");
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;
Get 5 LPA Or 8 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;
Get 5 LPA Or 8 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
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
Amenities
▪ Digital Notes ▪ Working Experience
▪ Live Training Sessions ▪ Job Recommendations
▪ Project Assistance ▪ Professional Development
▪ Interview Preparation ▪ Digital Resume & Portfolio
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.
Get 5 LPA Or 8 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 {
@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;
Get 5 LPA Or 8 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
Get 5 LPA Or 8 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.
Get 5 LPA Or 8 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;
Get 5 LPA Or 8 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;
Get 5 LPA Or 8 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
• 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.
Get 5 LPA Or 8 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.
Get 5 LPA Or 8 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;
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
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
Get 5 LPA Or 8 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.
• 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.
Get 5 LPA Or 8 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 {
@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;
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>
• 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
Get 5 LPA Or 8 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.
Get 5 LPA Or 8 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
{
@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;
Get 5 LPA Or 8 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
• 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.
Get 5 LPA Or 8 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 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
Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability
• 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
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;
Get 5 LPA Or 8 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>
<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>
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
Amenities
▪ Digital Notes ▪ Working Experience
▪ Live Training Sessions ▪ Job Recommendations
▪ Project Assistance ▪ Professional Development
▪ Interview Preparation ▪ Digital Resume & Portfolio
• 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
• 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:
Get 5 LPA Or 8 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
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
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.
Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability
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.
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.
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.
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
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.
Get 5 LPA Or 8 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>
</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
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() { }
Get 5 LPA Or 8 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.
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() { }
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
Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability
• 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.
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>
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.
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.
Syntax
<%
// Java code here
%>
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.
Get 5 LPA Or 8 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>
Get 5 LPA Or 8 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:
Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability
• 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.
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
Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability
Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability
Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability
Get 5 LPA Or 8 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
• 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
Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability
Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability
Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability
Get 5 LPA Or 8 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.
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
• 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.
• 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
Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability
Syntax
<%@ page attribute="value" %>
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
Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability
Error Page:
<%@ page isErrorPage="true" %>
<html>
<head>
<title>Error Page</title>
</head>
<body>
<h1>An error occurred: <%= exception.getMessage() %></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
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
Amenities
▪ Digital Notes ▪ Working Experience
▪ Live Training Sessions ▪ Job Recommendations
▪ Project Assistance ▪ Professional Development
▪ Interview Preparation ▪ Digital Resume & Portfolio
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
Get 5 LPA Or 8 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
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
<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
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
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
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
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.
Get 5 LPA Or 8 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.
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.
• 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.
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.
• 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
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.
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>
<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>
<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
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>
Get 5 LPA Or 8 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>
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>
</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.
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
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;
Get 5 LPA Or 8 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 the custom tags start tag evaluating the custom tag body is completely depending
on the return value provided by doStartTag () method.
Evaluating the remaining the Jsp page after the custom tag or not is completely
depending on the return value provided by doEndTag() method.
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.
Get 5 LPA Or 8 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: 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
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;
Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability
<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;
Get 5 LPA Or 8 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
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.
Get 5 LPA Or 8 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
• 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
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
Amenities
▪ Digital Notes ▪ Working Experience
▪ Live Training Sessions ▪ Job Recommendations
▪ Project Assistance ▪ Professional Development
▪ Interview Preparation ▪ Digital Resume & Portfolio
Nested Tags
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
Get 5 LPA Or 8 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;
}
Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability
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
• 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.
Get 5 LPA Or 8 LPA Guaranteed Package | Live Online Classes | for more information, visit – www.learntoearnlabs.com
Learn-2-Earn Labs - Best Institute for job opportunities, & career stability
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.
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.
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;
Get 5 LPA Or 8 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
Get 5 LPA Or 8 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 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);
}
Get 5 LPA Or 8 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.
• 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.
Get 5 LPA Or 8 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
Get 5 LPA Or 8 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;
Get 5 LPA Or 8 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>
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
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;
Get 5 LPA Or 8 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
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;
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
Amenities
▪ Digital Notes ▪ Working Experience
▪ Live Training Sessions ▪ Job Recommendations
▪ Project Assistance ▪ Professional Development
▪ Interview Preparation ▪ Digital Resume & Portfolio
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
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
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
Get 5 LPA Or 8 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.
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
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
Amenities
▪ Digital Notes ▪ Working Experience
▪ Live Training Sessions ▪ Job Recommendations
▪ Project Assistance ▪ Professional Development
▪ Interview Preparation ▪ Digital Resume & Portfolio
Website : www.LearntoearnLabs.com