JDBC Architecture
The JDBC API provides the standard interfaces, while the JDBC driver implements the database-specific communication required to interact with the database.
Components of JDBC:
1. Application: It can be a Java application or servlet that communicates with a data source.
2. JDBC API: It allows Java programs to execute SQL queries and get results from the database. Some key components of JDBC API include
- Interfaces like Driver, ResultSet, RowSet, PreparedStatement, and Connection that help manage different database tasks.
- Classes like DriverManager, Types, Blob, and Clob that help manage database connections.
3. DriverManager: It uses database-specific drivers to establish connections between Java applications and databases.
4. JDBC drivers: JDBC drivers are adapters that convert requests from Java programs into a protocol that the DBMS can understand.
JDBC Processing Models
The JDBC architecture consists of two-tier and three-tier processing models to access a database. They are as described below:
1. Two-Tier Architecture
A Java Application communicates directly with the database using a JDBC driver. It sends queries to the database and then the result is sent back to the application. For example, in a client/server setup, the user's system acts as a client that communicates with a remote database server.
Structure:
Client Application (Java) -> JDBC Driver -> Database
2. Three-Tier Architecture
In this, user queries are sent to a middle-tier services, which interacts with the database. The database results are processed by the middle tier and then sent back to the user.
Structure:
Client Application -> Application Server -> JDBC Driver -> Database
Basic JDBC Workflow
A typical JDBC program follows these steps:
- Add the JDBC driver dependency for the database.
- Establish a database connection.
- Create a Statement or PreparedStatement.
- Execute the SQL query.
- Process the ResultSet for queries that return data.
- Commit or roll back the transaction when required.
- Close the JDBC resources.
For Connection establishment:try (Connection con = DriverManager.getConnection(url, user, password);
PreparedStatement ps = con.prepareStatement(
"SELECT * FROM employee WHERE id = ?")) {
ps.setInt(1, 101);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
System.out.println(rs.getString("name"));
}
}
}
Introduction to Java Servlets
Java Servlet is a Java program that runs on a Java-enabled web server or application server. It handles client requests, processes them and generates responses dynamically. Servlets are the backbone of many server-side Java applications due to their efficiency and scalability.
- Work on the server-side to manage request-response lifecycle.
- Capable of handling multiple client requests efficiently.
- Suitable for building robust and scalable enterprise applications.
Servlets Architecture
Servlet architecture defines how client requests are processed by the server using servlets. It follows a request-response model where the web container manages execution.
Servlet Architecture Workflow
Execution of Servlets basically involves Six basic steps:
- The client sends an HTTP request.
- The web server or Servlet container receives the request.
- The container identifies the servlet mapped to the requested URL.
- The container invokes the appropriate servlet method, such as doGet() or doPost().
- The servlet processes the request and generates a response.
- The container sends the response back to the client.
Need of Server-Side Extensions
Server-side technologies are used when a web application needs to process requests on the server and generate dynamic responses.
- They allow applications to process user requests.
- They can interact with databases and other services.
- They can generate dynamic HTML or other HTTP responses.
- They allow business logic to be executed on the server.
- Java Servlets provide a standard server-side API for Java web applications.
Servlet Container
A Servlet container, also called a Servlet engine, provides the runtime environment for servlets. It manages servlet lifecycle, request processing, response generation, sessions, security, and other web application services.
Apache Tomcat is a commonly used Servlet container.
Services Provided by a Servlet Container
- Servlet lifecycle management: Loads, initializes, executes, and destroys servlets.
- Request and response handling: Creates request and response objects and passes them to the servlet.
- URL mapping: Maps incoming URLs to the appropriate servlet.
- Session management: Provides APIs for maintaining client sessions, commonly through
HttpSession. - Security: Supports authentication, authorization, and security constraints.
- Resource management: Manages web application resources and servlet components.
- Concurrency management: Handles multiple requests and invokes servlets as required.
Steps for the implementation of creating a basic servlet program
Step 1: Create a Dynamic Web Project (in Eclipse)
- Open Eclipse -> File ->New ->Dynamic Web Project
- Name the project (e.g., HelloWorldServlet)
- Target runtime -> Select Apache Tomcat
- Click Finish
Step 2: Create Servlet class
- Right-click on src -> New-> Servlet
- Name it HelloWorldServlet and click Finish
HelloWorldServlet.java
import java.io.*;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
public class HelloWorldServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body><h1>Hello, World!</h1></body></html>");
}
}
This servlet handles a GET request and sends an HTML response to the client. It sets the response type to text/html, gets the PrintWriter, and prints a simple “Hello, World!” message inside HTML tags.
Step 3: Run the Application
Start the Tomcat server and open:
http://localhost:8080/HelloWorldServlet/hello
Configuring a Servlet
To deploy a servlet, you need to configure it in the web.xml file. This file maps URLs to servlets. For example,
XML-Based Configuration (web.xml):
<web-app xmlns="http://www.oracle.com/webfolder/technetwork/jsc/xml/ns/javaee/index.html"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.oracle.com/webfolder/technetwork/jsc/xml/ns/javaee/index.html
http://www.oracle.com/webfolder/technetwork/jsc/xml/ns/javaee/index.html/web-app_3_0.xsd"
version="3.0">
<servlet>
<servlet-name>HelloWorldServlet</servlet-name>
<servlet-class>HelloWorldServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorldServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
This is a web.xml file used for mapping URLs to servlets. So, when you visit http://localhost:8080/yourApp/hello, the servlet runs and shows "Hello, World!" in the browser.
Life Cycle of a Servlet
A Servlet is a server-side Java program that handles client requests and generates dynamic responses. Its life cycle is managed by the Servlet container using the jakarta.servlet API.
- Managed by the Servlet container through defined life cycle methods
- Helps build efficient and scalable web applications
States of the Servlet Life Cycle
The Servlet life cycle consists of four main stages:
- Loading a Servlet
- Initializing a Servlet
- Handling Client Requests
- Destroying a Servlet
1. Loading a Servlet
The first stage of the Servlet life cycle is loading the Servlet class into memory and creating its instance. The Servlet container performs the following operations:
- Loading: The Servlet container loads the Servlet class into memory.
- Instantiation: The container creates an instance of the Servlet using the no-argument constructor.
When is a Servlet loaded?
- During application startup (if configured in deployment descriptor).
- On first client request (lazy loading).
2. Initializing a Servlet
After instantiation, the container initializes the Servlet using the init() method.
- init(ServletConfig config) method is called once in the Servlet’s lifetime.
- It prepares the Servlet to handle requests (e.g., database connection setup).
- Called only once, unlike service() which is called per request.
3. Handling request
Once initialized, the Servlet is ready to handle client requests.
1 Request and Response Objects
- ServletRequest and ServletResponse objects are created by the container for every client request and response cycle
- For HTTP, HttpServletRequest and HttpServletResponse objects are used.
2 The service() Method
- The container calls service(ServletRequest req, ServletResponse res) for each request.
- Determines the HTTP request type (GET, POST, PUT, DELETE).
- Delegates the request to appropriate methods: doGet(), doPost(), etc.
4. Destroying a Servlet
When the Servlet container decides to remove the Servlet, it performs the following steps:
- Allow Active Threads to Complete: The container ensures that all threads executing the service() method complete their tasks.
- Invoke the destroy() Method: The container calls the destroy() method to allow the Servlet to release resources (e.g., closing database connections, freeing memory).
- Release Servlet Instance: After the destroy() method is executed, the Servlet container releases all references to the Servlet instance, making it eligible for garbage collection.
Servlet Life Cycle Methods
There are three life cycle methods of a Servlet:
1. init() Method
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import java.io.*;
public class AdvanceJavaConcepts extends HttpServlet {
private String output; // Immutable (thread-safe)
@Override
public void init() throws ServletException {
output = "Advance Java Concepts";
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/html");
try (PrintWriter out = resp.getWriter()) {
out.println(output); // Thread-safe
}
}
@Override
public void destroy() {
System.out.println("Servlet destroyed");
}
}
Comments
Post a Comment