Java servlets
Java Servlets are server-side Java components that allow dynamic generation
of HTML pages, handling HTTP requests and generating dynamic web
pages. They provide a platform-independent, secure and efficient way of
creating web applications. Servlets run on a web server, receiving requests
from clients (typically web browsers) and returning responses back to the
clients.
Servlets are part of the Java EE (Enterprise Edition) platform, and they are
used for building robust and scalable web applications. Servlets are well
suited for handling dynamic requests that require the processing of data and
the generation of HTML content. They can interact with databases, access
APIs, and perform complex operations, making them ideal for web
applications that require server-side processing.
The main advantage of servlets is that they are platform-independent and can
run on any web server that supports the Servlet API. They are also designed
to work with Java, making it easier to develop web applications that can be
used on any platform.
Servlets are written in Java, making them easy to maintain and upgrade, and
they are also highly secure. Java provides built-in security features such as
access control, encryption, and data validation that can be used to secure web
applications.
To create a servlet, a Java class must be written that extends the
javax.servlet.http.HttpServlet class and overrides the doGet or doPost
method. This method handles HTTP requests and generates the HTML
content to be sent back to the client.
In summary, Java Servlets are a powerful and efficient way of building
dynamic web applications that can run on any platform. They are secure,
platform-independent, and easy to maintain, making them a popular choice
for web developers
HTTP Servlets Basics
HTTP Servlets are Java components that are used to handle HTTP requests
and generate dynamic HTML pages. They are an integral part of the Java EE
platform and are used for building robust and scalable web applications.
Basics of HTTP Servlets:
1. Extending the HttpServlet class: To create a servlet, you need to write a Java
class that extends the javax.servlet.http.HttpServlet class. This class provides
the basic functionality for handling HTTP requests and generating HTML
responses.
2. Overriding the doGet or doPost method: The servlet class needs to override
the doGet or doPost method to handle HTTP requests. The doGet method is
used for handling HTTP GET requests and the doPost method is used for
handling HTTP POST requests.
3. Handling HTTP requests: The doGet or doPost method is called by the web
server whenever an HTTP request is made to the servlet. This method can
access the request and response objects to access the request data and
generate a response.
4. Generating HTML responses: The servlet can use the response object to
generate HTML content to be sent back to the client. The response object has
methods for setting the HTTP status code, setting the content type, and
adding content to the response.
5. Deployment: Once the servlet is written, it needs to be deployed to a web
server that supports the Servlet API. The servlet can be deployed as a
standalone component or as part of a web application.
6. URL Mapping: To access a servlet, a URL mapping must be created. The
URL mapping maps a URL to a servlet, and when a client requests that URL,
the servlet is executed.
In conclusion, HTTP Servlets are a powerful and efficient way of building
dynamic web applications. They provide a platform-independent, secure, and
easy-to-maintain way of handling HTTP requests and generating HTML
pages. HTTP Servlets are widely used in the Java EE platform and are an
essential component of many web applications
The Servlets Lifecycle
The Servlets Lifecycle refers to the stages a servlet goes through from its
creation to its destruction. The following are the stages in the Servlets
Lifecycle:
1. Loading and Initialization: When a servlet is first deployed, it is loaded into
memory by the web server. The servlet container then calls the init method of
the servlet, which is used to initialize the servlet. This method is called only
once in the servlet’s lifecycle.
2. Handling Requests: Once the servlet is initialized, it is ready to handle client
requests. The servlet container calls the service method of the servlet to
handle the request. The service method determines the type of request (GET
or POST) and calls the appropriate doGet or doPost method.
3. Generating Responses: The servlet generates a response by writing HTML
content to the response object. The response object is passed to the servlet in
the service method. The servlet can use the response object to set the HTTP
status code, set the content type, and add content to the response.
4. Destruction: When the servlet is no longer needed, the servlet container calls
the destroy method to clean up resources used by the servlet. The destroy
method is called only once in the servlet’s lifecycle, just before the servlet is
removed from memory.
It is important to note that multiple clients can access a single servlet
simultaneously. The servlet container creates a new thread for each client
request, and each thread calls the service method of the servlet. This allows
multiple clients to access the servlet simultaneously, without interfering with
each other
Retrieving Information
Retrieving information refers to the process of accessing data or information
stored in a database, file system, or other storage medium. This information
can be retrieved in various ways, including:
1. HTTP GET Requests: This is the most common method of retrieving
information from a web server. An HTTP GET request is sent from the client
to the server, and the server responds with the requested information. The
information is sent as part of the URL, and the server uses this information to
generate the response.
2. HTTP POST Requests: HTTP POST requests are used to send data from the
client to the server. This method is often used for forms, where the user
enters data into a form and submits it to the server. The server processes the
data and generates a response.
3. SQL Queries: SQL (Structured Query Language) is a standard language for
accessing and manipulating data stored in a relational database. SQL queries
are used to retrieve information from a database. The query specifies what
data is to be retrieved and how it is to be organized.
4. File I/O: Information can also be retrieved from a file system. This can be
done using file I/O (input/output) operations. The file system is accessed, and
the information is read from the file and stored in memory.
5. REST APIs: REST (Representational State Transfer) APIs are used to
retrieve information from a web server. REST APIs define a set of endpoints
that return data in response to client requests. The client specifies the
endpoint and the data to be returned, and the server returns the data
Sending HTML Information
Sending HTML information refers to the process of sending data in HTML
format from a web server to a client. HTML (Hypertext Markup Language) is
the standard language used for creating web pages. The following are the
steps involved in sending HTML information:
1. Generating HTML content: The HTML content is generated by the server-
side code. This can be done using a variety of methods, including dynamic
HTML generation, template engines, and content management systems.
2. Setting the response content type: The content type of the response must be
set to “text/html” to indicate that the response is in HTML format. This is
done by setting the “Content-Type” header in the response object.
3. Writing HTML content to the response object: The HTML content is written
to the response object using the response object’s “write” method. The
“write” method takes the HTML content as a parameter and writes it to the
response.
PrintWriter out = response.getWriter();
out.println(htmlContent);
4. Sending the response to the client: The response is sent to the client by the
web server. The client receives the HTML content and displays it in the
browser.
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h1>Hello, World!</h1>");
out.println("</body></html>");
In conclusion, sending HTML information involves generating the HTML
content, setting the content type of the response, writing the HTML content
to the response object, and sending the response to the client. Understanding
the steps involved in sending HTML information is essential for building
dynamic web pages and web applications.
Session Tracking
Session tracking refers to the process of maintaining state information for a
user across multiple requests. This is necessary because HTTP is a stateless
protocol, meaning that each request is treated as a separate, independent
request. In a web application, it is often necessary to maintain state
information for a user, such as the items in their shopping cart, or their login
status.
Session tracking can be achieved in several ways, including:
1. URL rewriting: URL rewriting involves adding a session identifier to the
URL of each page. This session identifier is used to identify the user and
maintain their state information across requests.
2. Hidden form fields: Hidden form fields are fields in an HTML form that are
not visible to the user. These fields can be used to store session information,
such as a session identifier, that can be sent back to the server with each
request.
3. Cookies: Cookies are small text files that are stored on the client’s machine
by the web server. Cookies can be used to store session information, such as
a session identifier, and this information is sent back to the server with each
request.
4. HTTP session: The HTTP session is a mechanism for maintaining state
information for a user across multiple requests. The HTTP session is
managed by the servlet container, and it stores session information in
memory on the server.
In conclusion, session tracking is an important concept in web development,
and it is used to maintain state information for a user across multiple
requests. Understanding the different methods of session tracking is essential
for building robust and scalable web applications
Database Connectivity
Database connectivity refers to the process of connecting to a database from a
web application in order to retrieve and store data. A database connection is
required in order to interact with a database, and there are several methods
for establishing a database connection, including:
1. JDBC (Java Database Connectivity): JDBC is a standard API for connecting
to databases from Java applications. JDBC provides a set of classes and
interfaces that enable Java applications to interact with databases.
2. JPA (Java Persistence API): JPA is a Java API for connecting to databases
and performing database operations. JPA is a standard API for Java
applications, and it provides a simple and efficient way to connect to
databases and perform database operations.
3. Hibernate: Hibernate is a Java framework for connecting to databases and
performing database operations. Hibernate is a popular framework for Java
applications, and it provides a simple and efficient way to connect to
databases and perform database operations.
4. JNDI (Java Naming and Directory Interface): JNDI is a Java API for
connecting to databases and performing database operations. JNDI provides a
simple and efficient way to connect to databases and perform database
operations.
database connectivity is an important concept in web development, and it is
used to connect to databases from web applications in order to retrieve and
store data. Understanding the different methods for establishing a database
connection is essential for building robust and scalable web applications
// Import required libraries
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;
// Define the servlet by using the @WebServlet annotation
@WebServlet("/helloServlet")
public class HelloServlet extends HttpServlet {
// Override the doGet method to handle GET requests
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
// Set the response content type to HTML
response.setContentType("text/html");
// Get a PrintWriter object to write the HTML response
PrintWriter out = response.getWriter();
// Write HTML content to the response
out.println("<html>");
out.println("<head><title>Hello Servlet</title></head>");
out.println("<body>");
out.println("<h1>Welcome to my simple servlet!</h1>");
out.println("<p>This is a basic example of a servlet responding to an
HTTP GET request.</p>");
out.println("</body>");
out.println("</html>");
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>com.example.HelloServlet</servlet-class> <!-- Update with
your package name -->
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/helloServlet</url-pattern>
</servlet-mapping>
</web-app>
<html>
<head><title>Hello JSP</title></head>
<body>
<h1>Welcome, <%= request.getParameter("name") %>!</h1>
<p>This is generated using JSP.</p>
</body>
</html>
1. Translation of JSP page add.jsp - add.java(servlet)
2. Compilation of JSP page add.class
3. Class loading phase Web container
4. Instantiation phase Object(load into main memory)
5. Initial phase public void _jspInit() only once executed
6. Request Processing phase public void _jspservice() create table,insert
(multiple times based on request)
7. Destruction phase public _jspDestory() only once executed
Difference between Servlet and JSP
Servlet JSP
Servlet is a java code. JSP is a HTML-based compilation code.
Writing code for servlet JSP is easy to code as it is java in HTML.
is harder than JSP as it is
Servlet JSP
HTML in java.
Servlet plays a controller
JSP is the view in the MVC approach for
role in the ,MVC
showing output.
approach.
JSP is slower than Servlet because the
Servlet is faster than first step in the JSP lifecycle is the
JSP. translation of JSP to java code and then
compile.
Servlet can accept all
JSP only accepts HTTP requests.
protocol requests.
In Servlet, we can
In JSP, we cannot override its service()
override the service()
method.
method.
In JSP (JavaServer Pages), there are five main types of tags that are used to
embed Java code and instructions within HTML. Here's a simple
explanation of each:
1. Declaration Tag (<%! ... %>)
Purpose: Used to declare variables and methods in the JSP page that can be
used throughout the page.
Example:
jsp
Copy code
<%! int count = 0; %>
Explanation: This is like defining global variables or methods in a JSP page
that you can use later. These variables or methods get initialized when the
JSP page is loaded.
2. Expression Tag (<%= ... %>)
Purpose: Used to output the result of an expression (usually a variable or
calculation) directly into the HTML.
Example:
jsp
Copy code
<%= 2 + 3 %>
Explanation: This outputs 5 on the web page. It’s useful when you want to
quickly display the result of an expression.
3. Directive Tag (<%@ ... %>)
Purpose: Used to give special instructions to the JSP engine, like importing
Java classes, defining the page’s language, etc.
Example:
jsp
Copy code
<%@ page language="java" contentType="text/html" %>
Explanation: This tells the JSP page to use the Java language and that the
content type of the response is HTML. It’s for configuring the environment
of the JSP page.
4. Scriptlet Tag (<% ... %>)
Purpose: Used to insert regular Java code into the JSP page.
Example:
jsp
Copy code
<%
int x = 10;
out.println("The value of x is: " + x);
%>
Explanation: You can write any Java code inside this tag. It’s like writing
Java code directly in an HTML page. This tag allows you to create logic,
loops, and conditions inside the JSP page.
5. Action Tag (<jsp:action ... />)
Purpose: Used to perform certain tasks like including other pages,
forwarding requests, or interacting with JavaBeans.
Example:
jsp
Copy code
<jsp:include page="header.jsp" />
Explanation: This tag is used for actions like including another JSP page
(like a header or footer) or managing JavaBeans (reusable components). It
simplifies things like reusing code or linking other pages.
In Summary:
Declaration (<%! ... %>) - Declares variables or methods.
Expression (<%= ... %>) - Displays the result of expressions.
Directive (<%@ ... %>) - Provides special instructions to the JSP engine.
Scriptlet (<% ... %>) - Allows writing Java code directly in the JSP page.
Action (<jsp:action />) - Executes actions like including pages or handling
JavaBeans.
These tags help in mixing Java code with HTML to build dynamic web
pages in JSP.
EJB (Enterprise JavaBeans) is a server-side component architecture for
building scalable, robust, and distributed enterprise-level applications in
Java. EJB simplifies the development of large-scale enterprise applications
by handling complex tasks such as transactions, security, and concurrency,
allowing developers to focus on business logic.
Types of EJBs:
EJB is divided into three main types, each serving different purposes in an
enterprise application:
1. Session Beans:
o Purpose: Session beans are used to manage interactions with clients.
They perform specific tasks or services and may be stateful or
stateless.
o Types:
Stateless Session Bean: Does not retain client data between
method calls. Each request is independent.
Stateful Session Bean: Maintains the client state across
multiple method calls. Useful when you need to preserve user
data during a session.
Singleton Session Bean: A single instance that exists for the
lifetime of the application. Used for application-wide tasks like
caching or logging.
o Example Use Case: Stateless session beans can be used for simple
services like a currency converter, while stateful beans can handle
shopping cart data in an e-commerce site.
2. Entity Beans (Deprecated):
o Purpose: Entity beans were used to represent persistent data stored in
a database. However, they have been replaced by Java Persistence
API (JPA), which is more efficient and easier to use.
o Example Use Case: Handling database interactions, such as
retrieving or updating customer data.
3. Message-Driven Beans (MDB):
o Purpose: These beans are used to handle asynchronous messages
(typically using Java Message Service or JMS). MDBs allow the
application to process messages from a queue or a topic, enabling
decoupled and asynchronous communication between systems.
o Example Use Case: Processing orders asynchronously from a
message queue in a large system with multiple components.
Key Features of EJB:
1. Transaction Management: EJB provides automatic transaction
management. It allows developers to manage database transactions without
writing complex code to begin, commit, or roll back transactions.
2. Security: EJB offers built-in security features that allow developers to
specify access control for different methods or components of the
application.
3. Concurrency: EJB ensures that concurrent access to resources or
components is handled properly, avoiding issues like race conditions.
4. Messaging: Message-driven beans can handle asynchronous processing
using JMS, enabling communication between distributed systems.
5. Dependency Injection: EJB supports dependency injection, where the
container injects resources, services, or other beans required by an EJB,
allowing for more modular and testable code.
6. Remote Method Invocation (RMI): EJB allows distributed components to
interact with each other, even when they are deployed on different servers or
locations, using remote interfaces.
Example of a Stateless Session Bean:
java
Copy code
import javax.ejb.Stateless;
@Stateless
public class CalculatorBean {
public int add(int a, int b) {
return a + b;
}
public int subtract(int a, int b) {
return a - b;
}
}
In this example:
@Stateless: This annotation marks the class as a stateless session bean.
add and subtract: These methods provide business logic for adding and
subtracting numbers. Since it's stateless, the bean does not retain data
between method calls.
How EJB Works:
1. Client Request: A client (e.g., a web application) sends a request to an EJB.
2. Container: The EJB container (provided by an application server like JBoss,
GlassFish, or WebLogic) manages the lifecycle of EJBs, injects
dependencies, and ensures that resources (e.g., database connections,
security) are handled properly.
3. EJB Execution: The EJB executes the business logic and interacts with
external systems, such as databases or messaging services.
4. Response: The result is sent back to the client.
When to Use EJB:
When your application requires distributed computing with remote method
invocation (RMI).
When you need transaction management or security at the enterprise
level.
When handling concurrent access to business logic and resources.
When you need to process asynchronous messages (using Message-Driven
Beans).
In Summary:
EJB is a powerful tool for building distributed, enterprise-level applications
that require scalability, transaction management, security, and messaging.
It abstracts many complexities of enterprise development (e.g., transactions,
concurrency) and allows developers to focus on business logic.
Although other technologies like Spring have gained popularity due to their
simplicity and flexibility, EJB is still widely used in enterprise-level
applications where robust transaction and security management is required.