Unit 5 WT
Unit 5 WT
Request Handling: A servlet receives a request from a client (e.g., a web browser),
processes it, and sends a response back to the client.
Lifecycle Management: Servlets follow a well-defined lifecycle consisting of
initialization, request handling, and destruction.
Servlet Container: A servlet container, such as Apache Tomcat, manages the
servlets, handles requests, and maintains their lifecycle.
Advantages of Servlets:
Platform Independence: Since Servlets are written in Java, they are platform-
independent and can run on any server that supports the Java Servlet API.
Performance: Servlets are faster than traditional CGI scripts because they are
executed within a servlet container, and multiple requests can be handled by a
single servlet instance.
Scalability: Servlets support multi-threading, meaning multiple requests can be
handled simultaneously without the need for multiple processes.
Security: Servlets benefit from the security mechanisms provided by the Java
platform.
Types of Servlets:
Step 1 : Client i.e. web browser sends the request to the web server.
Step 2 : Web server receives the request and sends it to the servlet container.
Servlet container is also called web container or servlet engine. It is responsible for
handling the life of a servlet.
Step 3 : Servlet container understands the request’s URL and calls the particular
servlet. Actually, it creates a thread for execution of that servlet. If there are multiple
requests for the same servlet, then for each request, one thread will be created.
Step 4 : Servlet processes the request object and prepares response object after
interacting with the database or performing any other operations and sends the
response object back to the web server.
Step 5 : Then web server sends the response back to the client.
Interface Servlet
The Servlet interface is the central part of the Java Servlet API, which defines the contract
that all servlets must adhere to. A servlet is a Java object that runs on a web server or
servlet container and handles client requests, typically HTTP requests, and generates
dynamic responses.
The Servlet interface is part of the javax.servlet package, and all servlets must implement
this interface (or its subclass, like GenericServlet or HttpServlet) to ensure they can be
managed and invoked by a servlet container.
This method is called just before the servlet is destroyed (when the servlet container
shuts down or the servlet is unloaded). It is used for cleanup.
Servlet Lifecycle
The Servlet Lifecycle is a sequence of stages that a servlet undergoes from its creation to
its destruction. The servlet container (e.g., Tomcat) manages the lifecycle of a servlet.
When the servlet container starts or when a client makes the first request to a
servlet (depending on the configuration), the servlet is loaded and instantiated. The
container creates an instance of the servlet class.
A servlet is typically loaded when the container is started or when it is requested for
the first time (this can be controlled via configuration settings like load-on-startup in
web.xml).
After the servlet is instantiated, the container calls the init() method once. This
method is used to initialize the servlet, such as setting up resources (e.g., database
connections, file I/O streams).
The init() method receives a ServletConfig object as a parameter, which provides
configuration parameters defined in the web.xml file.
After initialization, the servlet is ready to handle requests. Every time a client makes
a request, the servlet container calls the service() method, passing in the ServletRequest
and ServletResponse objects.
The service() method processes the request and generates an appropriate response.
For example, in an HttpServlet, the doGet() or doPost() methods are invoked depending
on the HTTP request type.
When the servlet is no longer needed (either due to server shutdown or the servlet
being unloaded), the container calls the destroy() method to allow the servlet to
release any resources it is holding (e.g., closing database connections, clearing
caches).
This method is called once before the servlet is removed from memory.
Servlet Termination:
o After the destroy() method is executed, the servlet is removed from memory,
and the servlet container terminates its lifecycle.
Handling HTTP GET Requests
The HTTP GET method is used to request data from a specified resource. GET requests are
typically used to retrieve data from a server without making any changes to the server's
state.
Idempotent: GET requests should not modify the server's state. They are used purely for
fetching data.
Query Parameters: Data is sent in the URL as query parameters (e.g.,
http://example.com/resource?id=1&name=John).
Data Length: The data sent via GET is limited by the maximum URL length (which can vary
by browser or server).
Caching: GET requests can be cached by browsers or servers because they do not change
the server’s state.
In servlets, GET requests are handled by overriding the doGet() method of the HttpServlet
class. This method is invoked when the server receives an HTTP GET request.
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
response.setContentType("text/html");
String id = request.getParameter("id");
out.println("<html><body>");
out.println("</body></html>"); }}
doGet() Method: This method is automatically called by the servlet container when an
HTTP GET request is received for the servlet.
request.getParameter(): The getParameter() method is used to retrieve query parameters
from the URL. For example, if the URL is http://example.com?name=John&id=5, calling
request.getParameter("name") will return John.
Response: The servlet generates an HTML response that includes the parameters
received from the client.
The HTTP POST method is used to send data to the server to create or update a resource.
POST requests are used for actions that may have side effects, such as form submissions,
creating new records, or updating information on the server.
Characteristics of POST Requests:
Non-idempotent: POST requests can modify the server’s state. Each POST request may
result in a different outcome, such as a new database record being created.
Request Body: POST data is sent in the body of the request, which allows for larger data
transmission compared to GET. This is useful for sending form data, file uploads, etc.
No Caching: POST requests are generally not cached by browsers, as they often modify the
server’s state.
In servlets, POST requests are handled by overriding the doPost() method of the HttpServlet
class. This method is invoked when the server receives an HTTP POST request.
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
@Override
response.setContentType("text/html");
out.println("<html><body>");
out.println("</body></html>");
} else {
out.println("<html><body>");
out.println("<h1>Invalid input!</h1>");
out.println("</body></html>");
}}}
doPost() Method: This method is automatically invoked by the servlet container when an
HTTP POST request is received for the servlet.
request.getParameter(): Similar to GET requests, POST data can be accessed using
request.getParameter(). For POST requests, the data is sent in the request body, typically
through form submissions.
Processing: The servlet processes the form data or performs any other actions like
database insertion, file uploads, etc.
In a web application, you may sometimes need to forward a request to another resource
(such as another servlet, a JSP page, or a static file) or redirect the client’s browser to a
different URL. These actions can be achieved in two primary ways:
1. Request Dispatcher Forward (RequestDispatcher.forward())
2. HTTP Redirect (HttpServletResponse.sendRedirect())
Both methods are used to redirect or forward requests, but they differ in their purpose,
behavior, and usage. Below are detailed notes on these two approaches.
The request dispatcher is used to forward a request from one servlet to another or to a
JSP page within the same server or application. The forwarding process is handled by the
server internally, and the client is unaware of it.
Characteristics of Forwarding:
Internal to the Server: The forward action happens within the server, meaning the client is
unaware that a forward has occurred.
Request and Response Objects: The original request and response objects are passed
along to the forwarded resource. This allows the target servlet or JSP page to continue
working with the original request data.
No Change in URL: The URL in the browser’s address bar does not change when a forward
is made. The same URL remains visible to the client.
To forward a request, you need to use the RequestDispatcher object. The RequestDispatcher is
obtained by calling the getRequestDispatcher() method on the ServletRequest or ServletContext
object.
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
@Override
dispatcher.forward(request, response); }}
The HTTP redirect is used to send an HTTP response to the client, instructing the client to
make a new request to a different URL. This is typically used when you want the client’s
browser to load a new resource, which can be another servlet, a JSP page, or a completely
different URL.
Characteristics of Redirecting:
Client-Side Action: In a redirect, the client (browser) is informed that it needs to send a
new request to a different URL. The browser changes the URL in the address bar and re-
requests the new resource.
URL Change: The browser's URL changes after a redirect. This is visible to the user.
No Request Data Passed: When redirecting, the request data (e.g., query parameters or
form data) is not automatically passed to the new resource unless explicitly specified (e.g.,
using URL parameters).
New HTTP Request: A redirect involves a new HTTP request, meaning the target resource
is requested from scratch.
To perform a redirect in a servlet, you use the sendRedirect() method of the HttpServletResponse
object.
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.sendRedirect("http://www.example.com"); }}
internal resource, you can use relative paths (e.g., "nextServlet"), but for external URLs, you
must specify the full URL (e.g., "http://www.example.com").
When redirecting, you may want to pass parameters to the target resource. This can be
done by appending query parameters to the URL in the sendRedirect() method.
response.sendRedirect("nextPage.jsp?name=John&age=30");
Session Tracking
Session tracking is a technique used to maintain user state or session across multiple HTTP
requests and responses. Since HTTP is a stateless protocol (i meaning that each request is
independent and has no memory of previous requests), maintaining information about a
user’s interaction with the web application over multiple requests is essential for many
web-based applications (e.g., online shopping carts, login systems, etc.).
In Java Servlets, session tracking enables a web application to store and retrieve user-
specific data across multiple HTTP requests, thereby maintaining continuity for the user
across their session.
1. Cookies
2. URL Rewriting
3. HttpSession Object
response.addCookie(cookie);
if (c.getName().equals("user")) {
}}
response.sendRedirect(url);
The HttpSession class is the most common and preferred method for session tracking in
servlets. The session object allows storing user-specific data across multiple HTTP
requests.
The session object is automatically created when a user first accesses the web application.
The session object can store and retrieve attributes (data) across multiple requests.
The session ID can be passed via cookies or URL rewriting, depending on the servlet
container's configuration.
session.setAttribute("username", "john_doe");
session.invalidate();
getSession(): Retrieves the current session or creates a new one if it doesn't exist.
getAttribute(name): Retrieves an attribute from the session.
setAttribute(name, value): Sets an attribute in the session.
invalidate(): Invalidates the session and removes all associated data.
getId(): Retrieves the unique session ID.
isNew(): Checks if the session is new or was created earlier.
Session Timeout:
While session tracking is essential for maintaining state in web applications, it also
introduces certain security concerns:
Security Risks:
JSP Overview
What is JSP?
JavaServer Pages (JSP) is a technology that enables the creation of dynamic, data-driven
web pages using HTML or XML and Java. JSP pages are similar to traditional HTML pages,
but they can contain Java code embedded within special tags. This makes it possible to
write dynamic content in a standard web page structure, where the HTML tags define the
page structure and Java code generates the content.
JSP allows Java code to be embedded into HTML via special tags, which are then processed
on the server-side. When a client (usually a web browser) requests a JSP page, the web
server (such as Apache Tomcat) processes the page, executes the Java code, and returns a
dynamic response to the client.
1. Client Request: A client sends an HTTP request for a JSP page to the web server.
2. JSP Compilation: When the server receives the request, it checks whether the
requested JSP page has already been compiled. If not, the JSP page is compiled into a
Java Servlet (a Java class).
3. Servlet Execution: The compiled servlet is executed by the server. The Java code
embedded within the JSP page is executed at this point.
4. HTML Response: The servlet generates the resulting HTML (or other content, like
XML) dynamically, which is then sent as an HTTP response to the client.
5. Client Receives the Page: The client receives the dynamically generated content
(HTML, XML, etc.) and renders it in the browser.
JSP Lifecycle:
The JSP lifecycle refers to the series of stages a JSP page goes through from the time the
client makes a request until the response is sent back to the client. The stages in the JSP
lifecycle are:
1. Translation Phase:
o The JSP page is translated into a Java Servlet (if not already done) by the web
container (such as Tomcat).
o During this phase, the HTML and embedded Java code are converted into a
servlet class.
2. Compilation Phase:
o The translated servlet is compiled into bytecode (a .class file).
o The servlet is ready for execution by the web container.
3. Initialization Phase:
o When the servlet is first invoked, the init() method is called.
o The servlet is initialized only once during its lifecycle.
4. Request Processing Phase:
o The service() method is invoked each time the servlet is requested. This
method processes the client request and generates a dynamic response.
5. Destroy Phase:
o The destroy() method is called when the servlet is removed from memory
(typically when the server shuts down or when the JSP page is no longer in
use).
o This method is used for cleanup tasks like releasing resources.
Components of JSP:
1. JSP Directives:
Page Directive: Defines page-level properties such as the content type,
language, error pages, etc.
Include Directive: Includes content from another file at the time of page
translation.
2. JSP Scriptlets:
Scriptlets are pieces of Java code embedded directly in the JSP page using <%
... %> tags.
<%
String message = "Hello, World!";
out.println(message);
%>
Scriptlets are executed on the server when the page is requested, and the
output is inserted into the response.
3. JSP Expressions:
JSP expressions allow embedding Java code in the form of an expression that
is evaluated and converted to a string. The result is inserted into the
response.
4. JSP Declarations:
Declarations are used to declare variables and methods that can be used
within the JSP page. These are inserted into the servlet class.
5. JSP Actions:
JSP actions are predefined tags that provide functionality like forwarding
requests, including files, or interacting with JavaBeans.
i. jsp:forward: Forwards the request to another page or servlet.
ii. jsp:include: Includes another file’s content.
iii. jsp:useBean: Instantiates a JavaBean for use within the page.
Example of <jsp:useBean>:
Example:
<p>Hello, ${user.name}!</p>
A JavaServer Page (JSP) is a powerful way to create dynamic, data-driven web pages using
HTML and Java. Here’s a simple introduction to creating and running your first JSP page.
HTML Content: The static part of the page that is sent to the browser.
Java Code: Embedded within the HTML using special JSP tags.
<html>
<head>
</head>
<body>
<p>
</p>
</body>
</html>
JSP Directive:
<%@ page language="java" contentType="text/html" %> specifies the language used (Java)
and the content type (HTML).
HTML Content:
The HTML structure (<html>, <head>, <body>) contains static content that is directly
sent to the client’s browser.
JSP Expression:
<%= new java.util.Date() %> is a JSP expression. This Java code is executed on the server,
and the result (current date and time) is dynamically inserted into the page. The
output is directly rendered in the HTML.
How It Works:
Implicit Objects
In Node.js, Implicit Objects are not part of the core framework, but the term can be
understood in the context of objects that are automatically available to the developer
within certain environments or frameworks built on top of Node.js, like Express.js. These
objects are "implicitly" made available for you to use without explicitly passing them
around.
Scripting
Scripts are used to make systems more efficient, simplify complex tasks, and integrate
various components of a software ecosystem. They can range from small programs to
larger systems but are typically easier to write and modify compared to traditional
compiled programs.
Interpreted: Scripting languages are typically interpreted, which means the code is
executed line-by-line by an interpreter. This allows for faster development and testing
because the code doesn't need to be compiled first.
Automation: Scripts are often written to automate repetitive tasks, such as file
management, data manipulation, system monitoring, or web scraping. Automation saves
time and reduces human error.
Flexibility: Scripts allow for flexible and quick changes. Since they are not compiled,
they can be edited on the fly and executed immediately.
Environment-Specific: Scripting is often tightly coupled with the environment in which
it runs. For example, JavaScript is a scripting language for web browsers, while Bash
scripting is used for automating tasks in Unix-based operating systems.
Standard Actions in the context of web development and programming typically refer to
predefined, common operations or functions that are part of a framework, library, or platform.
These actions are generally standardized and can be used to simplify and streamline the
development process. In various contexts like Node.js, web development frameworks (like
Express.js), or even in CMS (Content Management Systems) and web applications, "standard
actions" refer to basic functionalities that are frequently used.
In web development, especially when dealing with databases and HTTP requests, CRUD
(Create, Read, Update, Delete) operations are considered standard actions. These represent
the basic set of actions for manipulating data.
Create: Adding new data to the system (e.g., inserting a new record into a database).
o Example: POST /users to create a new user.
Read: Retrieving data from the system (e.g., fetching a user record from a database).
o Example: GET /users/:id to fetch user details by ID.
Update: Modifying existing data in the system (e.g., updating a user’s information).
o Example: PUT /users/:id to update user details.
Delete: Removing data from the system (e.g., deleting a user record from a
database).
o Example: DELETE /users/:id to delete a user.
GET: Used to retrieve data. This is the most common standard action to fetch
resources.
o Example: app.get('/users', (req, res) => { /* Handle Get request */ });
POST: Used to create new resources or submit data to the server.
o Example: app.post('/users', (req, res) => { /* Handle Post request */ });
PUT: Used to update an existing resource.
o Example: app.put('/users/:id', (req, res) => { /* Handle Put request */ });
DELETE: Used to delete a resource.
o Example: app.delete('/users/:id', (req, res) => { /* Handle Delete request */ });
Directives
directives are not a core feature of the runtime itself but are often used in the context of
template engines or web frameworks built on top of Node.js, such as Angular (for front-
end development), EJS, Handlebars, or Pug (for templating). However, in the broader
sense, directives refer to specific commands or instructions that are used within the
context of these tools to control the rendering logic or behavior of templates.
In template engines like EJS, Pug, or Handlebars, directives are special syntax or
keywords used within templates to control the rendering process, such as looping
through data, conditional rendering, and including other templates.
Example in Pug:
if user
o The if directive in Pug is used for conditional rendering.
Custom Tag Libraries refer to libraries or frameworks that allow developers to define
their own custom HTML tags or components, which can be used to extend the functionality
of web pages in a modular and reusable way. These custom tags often encapsulate specific
behavior or logic, and can be reused across different parts of an application or across
multiple projects.
In the context of Node.js and web development, custom tag libraries are often used with
template engines or front-end frameworks to improve the flexibility and maintainability of
code. Here's a brief overview:
Some template engines allow you to define custom tags or helpers that can be used within
templates to create reusable components. For example:
Handlebars: Handlebars allows you to define custom helpers, which can be used as
tags to encapsulate logic or dynamic content rendering. This is not exactly the same
as HTML custom tags, but they offer a similar reusable functionality.
Handlebars.registerHelper('formatDate', function(date) {
});
{{formatDate date}}
EJS (Embedded JavaScript): EJS doesn’t support custom tags in the same way as Handlebars, but
developers can create reusable components by including partial templates.
Web Components is a set of web platform APIs that allow developers to create custom
HTML tags (elements) with their own behavior. These custom elements can encapsulate
functionality and styles, making them reusable and shareable across different projects.
Custom Elements API: This API allows developers to define their own tags (e.g.,
<my-button> or <user-profile>). The behavior of these tags is controlled by JavaScript,
and they can be integrated into any web page.
constructor() {
super();
shadow.innerHTML = `<button><slot></slot></button>`;
customElements.define('my-button', MyButton);
Vue.js: In Vue, components are custom tags that encapsulate template, script, and style.
<template>
</template>
<script>
export default {
methods: {
clickHandler() {
alert('Button clicked');
};
</script>
Angular: In Angular, custom components are often represented as custom HTML tags.
<app-root></app-root>