MODULE 3 BACKEND DEVELOPMENT
JAVA SERVLETS
❖Java Servlets are the java programs that run on the
web server or application server.
❖They are used to handle the request obtained from
the web server, process the request, produce the
response and then send a response back to the web
server
JAVA SERVLETS
Properties of Java Servlet
❖Handle the request obtained from the web server
❖Process the request
❖Produce the response
❖Send a response back to the web server
JAVA SERVLETS
JAVA SERVLET LIFECYCLE
JAVA SERVLET LIFECYCLE
JAVA SERVLET LIFECYCLE
❖There are several phases of servlet lifecycle
1.Loading & Instantiation
The servlet class is loaded into memory when the
web container starts or the first request for the
servlet arrives, depending on configuration. The
container then creates an instance of the servlet
using its no-argument constructor.
JAVA SERVLET LIFECYCLE
2. Initialization (init() method):
The container calls the init() method on the servlet instance
after instantiation.
This method is called only once throughout the servlet's
lifespan and is used for one-time initialization tasks, such as
setting up database connections or loading configuration
data.
A ServletException might be thrown, and the servlet won't
be put into service if initialization fails.
JAVA SERVLET LIFECYCLE
2. Initialization (init() method):
The container calls the init() method on the servlet instance
after instantiation.
This method is called only once throughout the servlet's
lifespan and is used for one-time initialization tasks, such as
setting up database connections or loading configuration
data.
A ServletException might be thrown, and the servlet won't
be put into service if initialization fails.
JAVA SERVLET LIFECYCLE
3. Request Handling (service() method):
The servlet is ready to handle client requests once it's initialized.
The container creates ServletRequest and ServletResponse objects (or
HttpServletRequest and HttpServletResponse for HTTP requests) for every
client request to the servlet.
The container then calls the service() method, passing these request and
response objects.
The service() method determines the type of HTTP request (GET, POST, etc.)
and dispatches it to the corresponding doGet(), doPost(), or other doXxx()
methods.
The doGet() and doPost() methods are the most commonly used, handling GET
and POST requests respectively.
JAVA SERVLET LIFECYCLE
4. Termination (destroy() method):
The container allows any active service() method
threads to complete their tasks when the servlet is no
longer needed (e.g., web application undeployment,
container shutdown). Then, it calls the destroy() method
on the servlet instance. This method is called only once
and is used for cleanup activities, like closing database
connections or releasing resources.
INSTALLATION & CONFIGURATION OF APACHE TOMCAT
INSTALLATION & CONFIGURATION OF APACHE TOMCAT
INSTALLATION & CONFIGURATION OF APACHE TOMCAT
INSTALLATION & CONFIGURATION OF APACHE TOMCAT
INSTALLATION & CONFIGURATION OF APACHE TOMCAT
INSTALLATION & CONFIGURATION OF APACHE TOMCAT
INSTALLATION & CONFIGURATION OF APACHE TOMCAT
INSTALLATION & CONFIGURATION OF APACHE TOMCAT
INSTALLATION & CONFIGURATION OF APACHE TOMCAT
INSTALLATION & CONFIGURATION OF APACHE TOMCAT
INSTALLATION & CONFIGURATION OF APACHE TOMCAT
INSTALLATION & CONFIGURATION OF APACHE TOMCAT
INSTALLATION & CONFIGURATION OF APACHE TOMCAT
INSTALLATION & CONFIGURATION OF APACHE TOMCAT
INSTALLATION & CONFIGURATION OF APACHE TOMCAT
INSTALLATION & CONFIGURATION OF APACHE TOMCAT
INSTALLATION & CONFIGURATION OF APACHE TOMCAT
INSTALLATION & CONFIGURATION OF APACHE TOMCAT
INSTALLATION & CONFIGURATION OF APACHE TOMCAT
INSTALLATION & CONFIGURATION OF APACHE TOMCAT
INSTALLATION & CONFIGURATION OF APACHE TOMCAT
INSTALLATION & CONFIGURATION OF APACHE TOMCAT
INSTALLATION & CONFIGURATION OF APACHE TOMCAT
INSTALLATION & CONFIGURATION OF APACHE TOMCAT
INSTALLATION & CONFIGURATION OF APACHE TOMCAT
INSTALLATION & CONFIGURATION OF APACHE TOMCAT
INSTALLATION & CONFIGURATION OF APACHE TOMCAT
INSTALLATION & CONFIGURATION OF APACHE TOMCAT
INSTALLATION & CONFIGURATION OF APACHE TOMCAT
INSTALLATION & CONFIGURATION OF APACHE TOMCAT
INSTALLATION & CONFIGURATION OF APACHE TOMCAT
INSTALLATION & CONFIGURATION OF APACHE TOMCAT
INSTALLATION & CONFIGURATION OF APACHE TOMCAT
INSTALLATION & CONFIGURATION OF APACHE TOMCAT
INSTALLATION & CONFIGURATION OF APACHE TOMCAT
INSTALLATION & CONFIGURATION OF APACHE TOMCAT
INSTALLATION & CONFIGURATION OF APACHE TOMCAT
INSTALLATION & CONFIGURATION OF APACHE TOMCAT
INSTALLATION & CONFIGURATION OF APACHE TOMCAT
INSTALLATION & CONFIGURATION OF APACHE TOMCAT
INSTALLATION & CONFIGURATION OF APACHE TOMCAT
INSTALLATION & CONFIGURATION OF APACHE TOMCAT
INSTALLATION & CONFIGURATION OF APACHE TOMCAT
INSTALLATION & CONFIGURATION OF APACHE TOMCAT
INSTALLATION & CONFIGURATION OF APACHE TOMCAT
INSTALLATION & CONFIGURATION OF APACHE TOMCAT
INSTALLATION & CONFIGURATION OF APACHE TOMCAT
INSTALLATION & CONFIGURATION OF APACHE TOMCAT
INSTALLATION & CONFIGURATION OF APACHE TOMCAT
DOGET() AND DOPOST()
METHODS IN SERVLETS
INTRODUCTION TO SERVLETS
• •Servlets are Java programs that run on a server
• • Used to handle requests and responses in web
applications
• • Two main methods to process client requests:
• - doGet()
• - doPost()
DOGET() METHOD
• • Handles HTTP GET requests
• • Request parameters are appended to the URL
• • Suitable for:
• - Fetching data
• - Idempotent operations (safe and repeatable)
• • Limited data length (due to URL size restriction)
• • Visible to users (less secure for sensitive data)
DOPOST() METHOD
• • Handles HTTP POST requests
• • Request parameters are sent in the request body
• • Suitable for:
• - Submitting forms
• - Transactions and updates
• • No restriction on data length
• • More secure compared to GET (data not visible in URL)
DOGET() VS DOPOST()
• • doGet(): Data sent via URL | doPost(): Data sent via body
• • doGet(): Limited data size | doPost(): No size limit
• • doGet(): Less secure | doPost(): More secure
• • doGet(): Used for fetching data | doPost(): Used for
submitting data
• • doGet(): Bookmarked/cached | doPost(): Cannot be
bookmarked
EXAMPLE: DOGET() AND DOPOST()
• public void doGet(HttpServletRequest req, HttpServletResponse res)
• throws ServletException, IOException {
• PrintWriter out = res.getWriter();
• out.println("Handled GET Request");
• }
• public void doPost(HttpServletRequest req, HttpServletResponse res)
• throws ServletException, IOException {
• PrintWriter out = res.getWriter();
• out.println("Handled POST Request");
• }
CONCLUSION
• • doGet() and doPost() are essential for handling HTTP
requests in servlets
• • Choose the right method based on application
requirements
• • doGet(): For fetching and displaying data
• • doPost(): For submitting and processing data securely
JAVA SESSION HANDLING
UNDERSTANDING SESSIONS IN JAVA WEB APPLICATIONS
INTRODUCTION TO SESSION HANDLING
• • Session: A conversation between client and
server.
• • HTTP is stateless, session handling provides
state.
• • Used to track user across multiple requests.
WHY SESSION HANDLING IS NEEDED?
• • HTTP does not store information by
default.
• • Example: Online shopping cart, login
systems.
• • Session allows persistence of user data.
WAYS TO MAINTAIN SESSION
• •Cookies
• • Hidden Form Fields
• • URL Rewriting
• • HttpSession
COOKIES
• • Small pieces of information stored at client-
side.
• • Sent with every HTTP request.
• • Can be persistent or non-persistent.
• • Limitations: Disabled by user, storage size.
HIDDEN FORM FIELDS
• • Information stored in hidden fields of HTML
forms.
• • Data submitted with form request.
• • Cannot be seen directly by user.
• • Only works with form submission.
URL REWRITING
• • Session ID appended to URL.
• • Example:
http://example.com/home?sessionid=123
• • Useful when cookies are disabled.
• • Less secure, exposes session ID in URL.
HTTPSESSION
• • Most commonly used session management
method in Java.
• • Provided by Java Servlet API.
• • Stores user information at server-side.
• • Secure and reliable.
HTTPSESSION METHODS
• • getSession(): Returns current session or creates
one.
• • setAttribute(String, Object): Stores object in
session.
• • getAttribute(String): Retrieves stored object.
• • removeAttribute(String): Removes stored object.
• • invalidate(): Ends session.
EXAMPLE: USING HTTPSESSION
• HttpSession session = request.getSession();
• session.setAttribute("username", "TE B");
• String user = (String)
session.getAttribute("username");
• out.println("Welcome, " + user);
SESSION TIMEOUT
• • Each session has a timeout limit.
• • Can be configured in web.xml <session-config>.
• • Example: <session-timeout>30</session-
timeout>
• • Default is usually 30 minutes.
ADVANTAGES OF HTTPSESSION
• • Secure – data stored on server-side.
• • Supports any object type.
• • Independent of browser settings.
• • Easy to implement with servlet API.
DISADVANTAGES OF HTTPSESSION
• • Consumes server memory.
• • More users = more memory usage.
• • Needs proper management to avoid
memory leaks.
•Understanding Cookies
INTRODUCTION TO COOKIES
• Small text file stored on the client
browser.
• Created by the server, stored by the client.
• Helps maintain state in stateless HTTP
protocol.
WHY DO WE NEED COOKIES?
• HTTP does not remember requests (stateless).
• Cookies help track:
• - Login sessions
• - User preferences
• - Shopping carts
TYPES OF COOKIES
• Session Cookies – Temporary, deleted on
browser close.
• Persistent Cookies – Stored with expiry date.
• Secure Cookies – Sent only via HTTPS.
• HttpOnly Cookies – Inaccessible to JavaScript.
COOKIE LIFECYCLE
• 1. Created by Server
• 2. Sent in Response Header
• 3. Stored by Browser
• 4. Sent back to Server in Request Header
• 5. Expiration or Deletion
WORKING WITH COOKIES IN JAVA
• Creating: new Cookie(name, value)
• Sending:
response.addCookie(cookie)
• Reading: request.getCookies()
EXAMPLE CODE: CREATING A COOKIE
• Cookie user = new Cookie("username",
"TE B");
• user.setMaxAge(60*60*24); // 1 day
• response.addCookie(user);
EXAMPLE CODE: READING A COOKIE
• Cookie[] cookies = request.getCookies();
• for(Cookie c : cookies) {
• out.println(c.getName() + " = " +
c.getValue());
•}
ADVANTAGES OF COOKIES
• Easy to implement.
• Browser support is universal.
• Can persist small data between sessions.
LIMITATIONS OF COOKIES
• Limited size (4KB per cookie, ~20 per site).
• Users can disable cookies.
• Security risks (if sensitive data stored).
COOKIES VS HTTPSESSION
• Cookies (Client-Side): Small storage, less
secure.
• HttpSession (Server-Side): Secure, supports
large data.
INTRODUCTION TO JSP
(JAVASERVER PAGES)
DYNAMIC WEB DEVELOPMENT WITH JAVA
WHAT IS JSP?
• JSP stands for JavaServer Pages.
• Technology for developing dynamic web pages.
• Embedded Java code in HTML using special tags.
• Runs on the server, outputs HTML to the client.
WHY JSP?
• Easier to write than Servlets (mix of HTML + Java).
• Separates business logic from presentation layer.
• Reusable components via tags and libraries.
• Faster development for dynamic websites.
JSP VS SERVLET
• Servlets: Pure Java code, difficult to embed
HTML.
• JSP: Java inside HTML, easier for web
designers.
• Both compile to Servlets internally.
• JSP is preferred for UI-focused
development.
JSP LIFECYCLE
• 1. Translation: JSP → Servlet.
• 2. Compilation: Servlet compiled to bytecode.
• 3. Loading: Servlet class loaded into memory.
• 4. Instantiation: Servlet object created.
• 5. Initialization: jspInit() method called.
• 6. Execution: _jspService() method handles requests.
• 7. Destruction: jspDestroy() method called.
JSP LIFECYCLE
JSP LIFECYCLE
• 1. Translation of JSP to Servlet
• The JSP file is parsed and converted into a Java servlet source file
(test.java).
• This step checks for syntax correctness.
• // The JSP is converted to a servlet class.
• public class TestServlet extends HttpServlet {
• // The generated servlet code
• }
JSP LIFECYCLE
• 2. Compilation of JSP page
• The generated test.java file is compiled into a class file
(test.class).
• This step converts the servlet code into bytecode.
• // JSP is automatically converted into a servlet, such as
• public class TestServlet extends HttpServlet {
• // Generated servlet code here
•}
JSP LIFECYCLE
•3. Classloading
•The container dynamically loads the
compiled class.
JSP LIFECYCLE
• 4. Instantiation
• The container creates an instance of the generated
servlet class.
• This instance handles multiple requests unless
explicitly configured otherwise.
• // The container creates an instance automatically.
• TestServlet servlet = new TestServlet();
JSP LIFECYCLE
• 5. Initialization (jspInit())
• This method is called only once when the JSP is first loaded.
• It is used for initializing resources like database connections or
configurations.
• public void jspInit() {
•
• // Initialization code, like setting up resources.
• System.out.println("JSP Initialized.");
•}
JSP LIFECYCLE
• 6. Request Processing (_jspService())
• This method is called for every request.
• It cannot be overridden because it is auto-generated and declared as final.
• It receives HttpServletRequest and HttpServletResponse objects to handle the
request.
• public void _jspService(HttpServletRequest request, HttpServletResponse
response) {
•
• // Code that handles the request, like generating HTML output.
• response.getWriter().write("<html><body>Hello, World!</body></html>");
• }
JSP LIFECYCLE
• 7. JSP Cleanup (jspDestroy())
• This method is called once before removing the JSP from
service.
• It is used for releasing resources, such as closing database
connections or cleaning up open files.
• public void jspDestroy() {
•
• // Clean up resources like closing database connections.
• System.out.println("JSP Destroyed.");
•}
JSP ARCHITECTURE
• Client (Browser) sends request.
• Web Server forwards request to JSP engine.
• JSP page compiled into Servlet.
• Servlet executes, generates dynamic HTML.
• Response sent back to Client browser.
JSP ARCHITECTURE
JSP SCRIPTING ELEMENTS
• 1. Declaration: <%! int x = 10; %>
• 2. Scriptlet: <% out.println("Hello"); %>
• 3. Expression: <%= x %>
• These allow embedding Java code inside
HTML.
EXAMPLE JSP CODE
• <html>
• <body>
• <h2>Welcome, <%= request.getParameter("user")
%></h2>
• </body>
• </html>
ADVANTAGES OF JSP
• Easy to maintain (separates UI & logic).
• Built-in objects simplify coding.
• Supports tag libraries & custom tags.
• Portable across servers (platform independent).
DISADVANTAGES OF JSP
• Difficult to debug complex JSP files.
• Business logic may mix with presentation if not structured.
• Performance overhead on first request (compilation).
JAVA DATABASE CONNECTIVITY (JDBC)
• JDBC is an API that helps applications to
communicate with databases, it allows Java
programs to connect to a database, run queries,
retrieve, and manipulate data.
• Because of JDBC, Java applications can easily work
with different relational databases like MySQL,
Oracle, PostgreSQL, and more.
JAVA DATABASE CONNECTIVITY (JDBC)
JAVA DATABASE CONNECTIVITY (JDBC) COMPONENTS
• There are 4 components
1.JDBC API
2.JDBC Driver Manager
3.JDBC Test Suite
4.JDBC Drivers
JAVA DATABASE CONNECTIVITY (JDBC) COMPONENTS
1.JDBC API
java.sql: This package, is the part of Java Standard Edition (Java SE)
, which contains the core interfaces and classes for accessing and
processing data in relational databases. It also provides essential
functionalities like establishing connections, executing queries, and
handling result sets
javax.sql: This package is the part of Java Enterprise Edition (Java EE)
, which extends the capabilities of java.sql by offering additional
features like connection pooling, statement pooling, and data source
management.
JAVA DATABASE CONNECTIVITY (JDBC) COMPONENTS
2. JDBC Driver Manager
Driver manager is responsible for loading the
correct database-specific driver to establish a
connection with the database. It manages the
available drivers and ensures the right one is used
to process user requests and interact with the
database.
JAVA DATABASE CONNECTIVITY (JDBC) COMPONENTS
3. JDBC Test Suite
It is used to test the operation(such as insertion,
deletion, updating) being performed by JDBC
Drivers.
JAVA DATABASE CONNECTIVITY (JDBC) COMPONENTS
4. JDBC Drivers
JDBC drivers are client-side adapters (installed on the client machine, not on
the server) that convert requests from Java programs to a protocol that the
DBMS can understand.
There are 4 types of JDBC drivers
JAVA DATABASE CONNECTIVITY (JDBC) COMPONENTS
Class/Interfaces Description
DriverManager Manages JDBC drivers and establishes database connections.
Connection Represents a session with a specific database.
Statement Used to execute static SQL queries.
PreparedStatem Precompiled SQL statement, used for dynamic queries with
ent parameters.
CallableStateme
Used to execute stored procedures in the database.
nt
Represents the result set of a query, allowing navigation
ResultSet
through the rows.
SQLException Handles SQL-related exceptions during database operations.
JAVA DATABASE CONNECTIVITY (JDBC)
Steps to Connect to
MySQL Database
Using JDBC
JAVA DATABASE CONNECTIVITY (JDBC)
Step 1: Load the JDBC Driver
Class.forName("com.mysql.cj.jdbc.Driver");
Step 2: Establish a Connection
Connection connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/your_database",
"your_username",
"your_password"
);
Step 3: Create a Statement
Statement statement = connection.createStatement();
JAVA DATABASE CONNECTIVITY (JDBC)
Step 4: Execute a Query
String query = "INSERT INTO students (id, name) VALUES
(412, TE B')";
int rowsAffected = statement.executeUpdate(query);
System.out.println("Rows affected: " + rowsAffected);
Step 5: Close the Connection
statement.close();
connection.close();
JAVA DATABASE CONNECTIVITY (JDBC)
WHAT IS JSTL?
• JSTL stands for JavaServer Pages Standard Tag
Library.
• A collection of useful JSP tags.
• Helps in removing Java code (scriptlets) from
JSP.
• Standardized by Sun Microsystems for
consistency.
WHY USE JSTL?
• Simplifies JSP development.
• Reduces scriptlet usage (better readability).
• Promotes reusability and maintainability.
• Encourages MVC architecture in Java web
apps.
JSTL ARCHITECTURE
• Part of JSP API.
• Provides tag-based approach for logic.
• Divided into 5 major tag libraries:
• - Core
• - Formatting
• - SQL
• - XML
• - Functions
JSTL TAG LIBRARIES OVERVIEW
• Core Tags – General purpose actions.
• Formatting Tags – Internationalization and formatting.
• SQL Tags – Database interaction.
• XML Tags – Work with XML data.
• Functions – String manipulation and other helpers.
JSTL CORE TAGS
• <c:out> – Display value of variable/expression.
• <c:set> – Assign values to variables.
• <c:remove> – Remove scoped variables.
• <c:if> – Conditional execution.
• <c:choose>, <c:when>, <c:otherwise> – Conditional
branching.
• <c:forEach> – Looping over collections.
• <c:forTokens> – Looping over tokens in a string.
EXAMPLE: CORE TAGS
• <c:set var="name" value="John"/>
• <c:if test="${name == 'John'}">
• Hello, John!
• </c:if>
• <c:forEach var="i" begin="1" end="5">
• Number: ${i}<br/>
• </c:forEach>
JSTL FORMATTING TAGS
• <fmt:formatNumber> – Format numbers and
currency.
• <fmt:parseNumber> – Parse numbers from strings.
• <fmt:formatDate> – Format dates.
• <fmt:parseDate> – Parse date strings.
• <fmt:setLocale> – Set locale for i18n.
• <fmt:bundle> – Resource bundles for localization.
EXAMPLE: FORMATTING TAGS
• <fmt:formatNumber value="12345.678"
type="currency"/>
• <fmt:formatDate value="${now}"
pattern="dd-MM-yyyy"/>
JSTL SQL TAGS
• <sql:setDataSource> – Define database connection.
• <sql:query> – Execute SQL SELECT.
• <sql:update> – Execute INSERT, UPDATE, DELETE.
• <sql:param> – Pass parameters in queries.
• <sql:dateParam> – Pass date parameters.
EXAMPLE: SQL TAGS
• <sql:setDataSource var="db" driver="com.mysql.jdbc.Driver"
• url="jdbc:mysql://localhost/test" user="root" password="root"/>
• <sql:query dataSource="${db}" var="rs">
• SELECT * FROM users
• </sql:query>
• <c:forEach var="row" items="${rs.rows}">
• ${row.username}<br/>
• </c:forEach>
JSTL XML TAGS
• <x:parse> – Parse XML data.
• <x:out> – Output XML data.
• <x:forEach> – Iterate over XML nodes.
• <x:choose>, <x:when>, <x:otherwise> –
Conditional logic for XML.
JSTL FUNCTIONS
• fn:length() – Returns length of string/collection.
• fn:contains() – Checks if string contains substring.
• fn:startsWith() – Checks prefix.
• fn:endsWith() – Checks suffix.
• fn:replace() – Replace substring.
• fn:toUpperCase(), fn:toLowerCase() – Case conversion.
• fn:trim() – Remove leading/trailing spaces.
EXAMPLE: FUNCTIONS
• ${fn:length('Hello World')} → 11
• ${fn:contains('Hello', 'He')} → true
• ${fn:toUpperCase('hello')} → HELLO
ADVANTAGES OF JSTL
• Eliminates need for scriptlets in JSP.
• Increases readability of JSP pages.
• Encourages use of MVC pattern.
• Standardized and portable across servers.
• Provides built-in support for i18n and DB handling.
LIMITATIONS OF JSTL
• SQL tags not recommended for enterprise apps
(security issues).
• Mixing too much logic in JSP reduces clarity.
• Limited flexibility compared to custom tags.
• Best used for simple logic, not complex business
rules.