0% found this document useful (0 votes)
15 views36 pages

4 Introduction To Servlets

Servlets are Java programs that operate on web servers to handle requests and responses, enhancing web application performance and enabling dynamic content generation. They follow a lifecycle that includes loading, initialization, request handling, and destruction, and can be integrated with databases and other technologies. Filters and servlet collaboration mechanisms further enhance the functionality of servlets by allowing for request/response modification and information sharing between servlets.

Uploaded by

Sharda Kaur
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views36 pages

4 Introduction To Servlets

Servlets are Java programs that operate on web servers to handle requests and responses, enhancing web application performance and enabling dynamic content generation. They follow a lifecycle that includes loading, initialization, request handling, and destruction, and can be integrated with databases and other technologies. Filters and servlet collaboration mechanisms further enhance the functionality of servlets by allowing for request/response modification and information sharing between servlets.

Uploaded by

Sharda Kaur
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 36

Introduction to Servlets

Definition: Servlets are Java programs that run on a web server or application server
and handle requests and responses.

Significance:
- Platform-independent server-side components.
- Enhance web application performance.
- Enable dynamic web page generation.
Use:
- Processing and storing user data.
- Managing sessions and cookies.
- Communicating with databases.
Advantages of Java Servlets:

• Performance: Faster execution as Servlets do not create new


processes for each request.
• Portability: Write-once, run-anywhere feature of Java..
• Memory: Single instance handles multiple requests.
• Integration: Easily integrates with databases using JDBC.
• Security: Inherits robust security features from web servers.
• Cost-Effective: Many web servers like Apache Tomcat are free to use
with Java Servlets.
Java Servlets Architecture
Execution of Java Servlets
Execution of Servlets basically involves following steps:
• The Clients send the request to the Web Server.

• The Web Server receives the request.

• The Web Server passes the request to the corresponding


servlet.
• The Servlet processes the request and generates the response
in the form of output.
• The Servlet sends the response back to the webserver.

• The Web Server sends the response back to the client and the
client browser displays it on the screen.
Servlet Life Cycle

Phases:
1. Loading and Instantiation: The server loads the servlet class and
instantiates it.
2. Initialization (`init` method): Called once when the servlet is first
loaded.
3. Service (`service` method): Handles client requests (GET, POST, etc.).
4. Destruction (`destroy` method): Cleans up resources before the
servlet is removed.
Contd…
1. init(): This method intializes the Servlet instance.

@Override
public void init() throws ServletException {
// Initialization: Called once when the servlet is loaded into memory
System.out.println("Servlet initialized");
}
2. service(): This method Processes requests and invokes either doGet() and doPost() based on
the request type.
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// Request handling: Called each time a request is made
String method = request.getMethod();
if ("GET".equalsIgnoreCase(method)) {
doGet(request, response);
} else if ("POST".equalsIgnoreCase(method)) {
doPost(request, response);
}
}
3. destroy(): This method cleans up resources when the servlet is terminated.

@Override
public void destroy() {
// Cleanup: Called once when the servlet is being destroyed
System.out.println("Servlet destroyed");
}
Server-Side Extensions

The Server-Side Extensions are technologies that are used to create


dynamic Web pages. To enable dynamic web pages, a web server or
container is required.

To meet this requirement, independent Web server providers offer some


proprietary solutions in the form of APIs (Application Programming
Interface).
These APIs allow us to build programs that can run with a Web server.
In this case, Java Servlet is also one of the component APIs of Java Servlets
are part of Jakarta EE (formerly Java EE). which sets standards for creating
dynamic Web applications in Java.

The Servlet technology is similar to other Web server extensions such as


Common Gateway Interface (CGI) scripts and Hypertext Preprocessor (PHP).
However, Java Servlets are more acceptable since they solve the limitations
Introduction to Jakarta EE

• Jakarta Platform, Enterprise Edition (formely Java EE) is a


set of specifications and tools for building enterprise
software. It's built on top of the Java SE platform.
• Jakarta EE is a collection of services that help you write
enterprise applications that run on the Java Platform. It
provides the infrastructure often required for these
applications so you that you can focus on core features
and business logic.
• It is used to develop web based application and other
applications.
Installation of Jakarta EE over Java SE platform

Already performed in class for more reference check the following


video

https://www.youtube.com/watch?v=NZrw-bnj4AQ&list=PLSDyGb_vta
nzKR6hzVb-ftJ1Irf6oGdza&index=6
Introduction to Apache tomcat webServer

Apache Tomcat is an open-source Java web server and


servlet container that's used to host Java
applications. It's developed by the Apache Software
Foundation.

How does Tomcat work?


• Tomcat acts as a bridge between web servers and Java
applications
• It forwards requests and responses to the selected
Java application server
• The application server processes the request,
Installation steps for Apache Tomcat server

Already performed in class for more reference check the following


video

https://www.youtube.com/watch?v=1eHzp51-xX4&list=PLSDyGb_v
tanzKR6hzVb-ftJ1Irf6oGdza&index=6
Java Servlet API, Packages, Classes and Interface

Servlets are built from two packages:


• jakarta.servlet(Basic): Provides basic Servlet classes and
interfaces.
• jakarta.servlet.http(Advance): Advanced classes for handling
HTTP-specific requests.
Key Classes and Interfaces

Component Type Package


Servlet Interface jakarta.servlet.*
ServletRequest Interface jakarta.servlet.*
ServletResponse Interface jakarta.servlet.*
GenericServlet Class jakarta.servlet.*
HttpServlet Class jakarta.servlet.http.*
HttpServletRequest Interface jakarta.servlet.http.*
HttpServletResponse Interface jakarta.servlet.http.*
Filter Interface jakarta.servlet.*
ServletConfig Interface jakarta.servlet.*
Writing Service Methods

Common HTTP Methods:


- `doGet(HttpServletRequest req, HttpServletResponse res)`: Handles
GET requests.
- `doPost(HttpServletRequest req, HttpServletResponse res)`: Handles
POST requests.
- `doPut`, `doDelete` (for RESTful services).
Handling Responses:
- Setting response type: `response.setContentType("text/html")`
- Writing response using `PrintWriter`.
Filtering Requests and Responses

Definition: Filters modify request and response objects before


reaching servlets.
Uses:
- Authentication and authorization.
- Logging and auditing.
- Compression and encoding responses.
Implementation:
- `jakarta.servlet.Filter` interface.
- Methods: `init()`, `doFilter()`, `destroy()`.
Conclusion

- Servlets provide a powerful way to handle web requests dynamically.


- Understanding lifecycle, initialization, and filtering is crucial.
- Next Steps: Explore JSP and Servlet integration.
Configure Java EE and Tomcat for servlet with eclipse

https
://www.youtube.com/watch?v=1eHzp51-xX4&list=PLSDyGb_vtanzKR6
hzVb-ftJ1Irf6oGdza&index=6

https://www.youtube.com/watch?v=NZrw-bnj4AQ&list=PLSDyGb_vtan
zKR6hzVb-ftJ1Irf6oGdza&index=5

https://www.youtube.com/watch?v=t9fwDFel-OQ

https://www.youtube.com/watch?v=r3o_eN-QJNw
Java Servlet Filter

Filters are part of Servlet API Since 2.3. Like a Servlet, a


filter object is instantiated and managed by the
Container and follows a life cycle that is similar to that
of a Servlet. A Servlet has 4 stages as depicted below
1.Instantiate.
2.Initialize.
3.Filter.
4.destroy.
These stages are similar to a servlet’s Instantiate,
Initialize, Filter, destroy. The filter is used to pre-process
the request and Post-processing the response. A Filter
is a java object that performs the Filtering task on either
the request to a resource or on the response from a
resource or both.
Some of the Applications using Filter

Authentication.
• Logging and Auditing Filters
• Image Conversion Filters.
• Data Compression Filters.
• Encryption and Decryption Filters.
Interfaces belong to Filters.
• Filter.
• FilterConfig.
• FilterChain.
All these interfaces are available in jakarta.Servlet Package
Filter
• A Filter is an interface.
• Every Filter must be inherited from this interface.
• It provides lifecycle methods
Filter Methods

Method Action performed


Called by the web container to indicate to
init(FilterConfig filterconfig) a filter that it is being placed into service
It is called by the container each time a
doFilter(HttpServletRequest request, request/response pair is passed through
HttpServletResponse response, FilterChain the chain due to a client request for a
chain) resource at the end of the chain.
to indicate to a filter that is being out of
destroy() service.

Note:
• Filter information must be provide inside web.xml .

• Filter is mapped with one or more than one servlet.


Filter Chain

FilterChain is an interface, which is implemented by a servlet container.


Filters use the FilterChain to invoke the next filter in the chain, or if the
calling filter is the last filter in the chain to invoke the resource at the end of
the chain.
Method: doFilter()
Causes the next Filter in the chain to be invoked, or if the calling filter is the last filter in the
chain, causes the resource at the end of the chain to be invoked.
Return Type: Void
Parameters:

HttpServletRequest request
HttpServletResponse response
Syntax:
void doFilter(HttpServletRequest request, HttpServletResponse response)
We can Develop three types of filters as listed below as follows:
(1) Request Filter: Contain only pre-request Processing logic.
Example: Request count filter, Authentication filter,
Authorization filter, Validation filter and etc.
(2) Response Filter: Contain only Post-response generation
logic.
Example: Conversion filter, Compression filter and etc.
• (3) Request-Response Filter: Contain both pre-request and
post-response generation logic.
Advantages of using filter

• Authentication and authorization of requests for resources. (To


check whether the user is valid or not and then forward its
request.)
• Formatting of request body or header before sending it to the
servlet. (To format the unformatted data)
• Compressing the response data sent to the client. (e.g.,
encrypting)
• Alter the response by adding some cookies, header information,
etc.
• Input validation.
Servlet Collaboration In Java Using
RequestDispatcher and
HttpServletResponse
What is Servlet Collaboration?
• The exchange of information among servlets of a particular Java web
application is known as Servlet Collaboration. This enables
passing/sharing information from one servlet to the other through method
invocations.

Principle ways provided by Java to achieve Servlet Collaboration


The servlet api provides two interfaces namely:
1. jakarta.servlet.RequestDispatcher

2. jakarta.servlet.http.HttpServletResponse

• These two interfaces include the methods responsible for achieving the
objective of sharing information between servlets.
Using RequestDispatcher Interface

The RequestDispatcher interface provides the option of dispatching the


client’s request to another web resource, which could be an HTML page,
another servlet, JSP etc. It provides the following two methods:
• public void forward(ServletRequest request, ServletResponse
response)throws ServletException, java.io.IOException:
The forward() method is used to transfer the client request to another
resource (HTML file, servlet, jsp etc). When this method is called, the
control is transferred to the next resource called. On the other hand, the
include() method is used to include the content of the calling file into the
called file. After calling this method, the control remains with the calling
resource, but the processed output is included into the called resource.
public void include(ServletRequest request,
ServletResponse response)throws ServletException,
java.io.IOException:

The include() method is used to include the contents of the


calling resource into the called one. When this method is called,
the control still remains with the calling resource. It simply
includes the processed output of the calling resource into the
called one.
Sharing Information in Servlets

Methods for Sharing Data:


- Request Scope: `request.setAttribute("key", value);`
- Session Scope: `session.setAttribute("key", value);`
- Application Scope: `getServletContext().setAttribute("key", value);`
Inter-Servlet Communication:
- `RequestDispatcher`: Forward and include mechanisms.
- Redirecting responses.
Initializing a Servlet

• Ways to Initialize a Servlet:


• - Using `init()` method.
• - Using web.xml `<init-param>` for configuration.
• - Using annotations `@WebServlet` and `@WebInitParam`.

You might also like