0% found this document useful (0 votes)
10 views20 pages

Java Servlets: A Comprehensive Guide

this is java notes

Uploaded by

kawadbandar
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)
10 views20 pages

Java Servlets: A Comprehensive Guide

this is java notes

Uploaded by

kawadbandar
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

UNIT-5

Java Servlets
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.

Key Features:
•Servlets work on the server side.
•Servlets are capable of handling complex requests obtained from the web server.
•Generate dynamic responses efficiently.

Creating a Basic Servlet

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
Example: [Link]

import [Link].*;
import [Link].*;
import [Link].*;

public class HelloWorldServlet extends HttpServlet {


protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();
[Link]("<html><body><h1>Hello, World!</h1></body></html>");
}
}
Configuring a Servlet
To deploy a servlet, you need to configure it in the [Link] file. This file maps URLs to servlets.
For example,

<web-app xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link]
[Link]
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>
Modern Servlet Configuration (Annotation-Based)

From Servlet 3.0, servlet configuration can also be done using annotations. Instead of using
[Link], we can configure the servlet using the @WebServlet annotations.

@WebServlet("/hello")
public class HelloWorldServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
[Link]("text/html");
PrintWriter out = [Link]();
[Link]("<html><body><h1>Hello, World!</h1></body></html>");
}
}

Key Features
[Link]-independent (written in Java).
[Link] efficient than CGI (Common Gateway Interface).
[Link] handle multiple requests concurrently (multi-threaded).
[Link] with protocols like HTTP, HTTPS.
[Link] inside a Servlet Container (like Tomcat, Jetty).
Servlet Lifecycle
The lifecycle of a servlet is managed by the servlet container and consists of 5 main stages:
1. Loading and Instantiation
•The servlet container loads the servlet class.
•Creates an instance of the servlet using new.

2. Initialization (init() method)


•The container calls init(ServletConfig config) once after instantiation.
•Used for one-time setup (e.g., database connections, resource loading).

3. Request Handling (service() method)


•For every client request, the container calls the service() method.
•The service() method dispatches the request to:
•doGet() → for HTTP GET requests.
•doPost() → for HTTP POST requests.
•and other methods like doPut(), doDelete(), etc.

4. Destruction (destroy() method)


•Called once when the servlet is taken out of service (e.g., server shutdown).
•Used to release resources (e.g., close DB connections, cleanup).

5. Garbage Collection
•After destroy(), the servlet object is eligible for garbage collection by JVM.
Example: A Simple Servlet
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class HelloWorldServlet extends HttpServlet {

// Initialization (called once when servlet is loaded)


@Override
public void init() throws ServletException {
[Link]("Servlet Initialized");
}

// Handles HTTP GET request


@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

// Set response content type


[Link]("text/html");
// Write output to browser
PrintWriter out = [Link]();
[Link]("<h2>Hello, Welcome to Servlets!</h2>");
[Link]("<p>This is a response from doGet() method.</p>");
}

// Handles HTTP POST request


@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

[Link]("text/html");
PrintWriter out = [Link]();
[Link]("<h2>POST Request received!</h2>");
}

// Cleanup (called once before servlet is destroyed)


@Override
public void destroy() {
[Link]("Servlet Destroyed");
}
}
Servlets APIs and Packages

Servlets are built from two packages:


•[Link](Basic): Provides basic Servlet classes and interfaces.
•[Link](Advance): Advanced classes for handling HTTP-specific requests.

Key Classes and Interfaces


Various classes and interfaces present in these packages are:
Component Type Package
Servlet Interface [Link].*
ServletRequest Interface [Link].*
ServletResponse Interface [Link].*
GenericServlet Class [Link].*
HttpServlet Class [Link].*
HttpServletRequest Interface [Link].*
HttpServletResponse Interface [Link].*
Filter Interface [Link].*
ServletConfig Interface [Link].*
Benefits of Java Servlets:
•Faster execution as Servlets do not create new processes for each request.
•Write-once, run-anywhere feature of Java.
•Single instance handles multiple requests.
•Easily integrates with databases using JDBC.
•It inherits robust security features from web servers.
•Many web servers like Apache Tomcat are free to use with Java Servlets.

Execution of Java Servlets


Execution of Servlets basically involves Six basic 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.
Retrieving Information in Servlets
When a client (browser) sends a request to a servlet, information can be retrieved using the
HttpServletRequest object.

1. Retrieving Form Data (Parameters)


•If a user submits a form, we can retrieve data using [Link]().

Example (HTML form): Servlet code:

<form action="login" method="post">


Username: <input type="text" name="user"><br> String username = [Link]("user");
Password: <input type="password" name="pass"><br> String password = [Link]("pass");
<input type="submit" value="Login">
</form>
2. Retrieving Multiple Values
•For checkboxes, list selections, etc.

Example (HTML form): Servlet code:

<form action="hobbies" method="post"> String[] hobbies = [Link]("hobby");


<input type="checkbox" name="hobby" value="Reading"> for(String h : hobbies){
Reading [Link](h + "<br>");
<input type="checkbox" name="hobby" value="Sports"> }
Sports
<input type="checkbox" name="hobby" value="Music">
Music
<input type="submit">
</form>
3. Retrieving Attributes
Servlets can share data using [Link]() and [Link]().
This is often used for forwarding data to JSP.

Servlet code:

[Link]("username", "John");
RequestDispatcher rd = [Link]("[Link]");
[Link](request, response);

// In JSP: ${username}

Summary :
•getParameter(name) → Single form field value.
•getParameterValues(name) → Multiple values (e.g., checkboxes).
•getHeader(name) → Request headers.
•getMethod(), getRequestURI(), getQueryString() → Request info.
•getAttribute(name) → Server-side attributes (shared between servlets/JSP).
Sending HTML Information
In Servlets, we generate the response in HTML and send it to the client (browser) via the
HttpServletResponse object. The key points are:
[Link] content type → [Link]("text/html");
[Link] writer → PrintWriter out = [Link]();
[Link] HTML code → using [Link](...)

import [Link].*;
import [Link].*;
import [Link].*;

public class SimpleHtmlServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

// Tell browser the response is HTML


[Link]("text/html");

// Get writer
PrintWriter out = [Link]();
// Send simple HTML
[Link]("<html>");
[Link]("<head><title>Simple Servlet</title></head>");
[Link]("<body>");
[Link]("<h2>Hello, this is a simple HTML response from Servlet!</h2>");
[Link]("</body>");
[Link]("</html>");

[Link]();
}
}
Using [Link]

<web-app xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link]
[Link]
version="5.0">

<servlet> URL:
<servlet-name>SimpleHtmlServlet</servlet-name>
<servlet-class>SimpleHtmlServlet</servlet-class> [Link]
</servlet>

<servlet-mapping>
<servlet-name>SimpleHtmlServlet</servlet-name>
<url-pattern>/simple</url-pattern>
</servlet-mapping>
</web-app>
Session Tracking in Servlets
Servlets are stateless by default — every request is independent.
To maintain user data (like login info, shopping cart), we use HttpSession.

import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;

@WebServlet("/sessionExample")
public class SessionExampleServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

[Link]("text/html");
PrintWriter out = [Link]();

// Get session and visit count


HttpSession session = [Link]();
Integer count = (Integer) [Link]("count");
count = (count == null) ? 1 : count + 1;
[Link]("count", count);
// Display result
[Link]("<html><body>");
[Link]("<h3>Session Tracking Example</h3>");
[Link]("<p>Session ID: " + [Link]() + "</p>");
[Link]("<p>Visit Count: " + count + "</p>");
[Link]("</body></html>");

[Link]();
}
}
Servlet Code
Example :Database Connectivity in import [Link].*;
Servlets (JDBC) import [Link].*;
We use JDBC inside a servlet to fetch/store data import [Link].*;
from DB. import [Link].*;
import [Link].*;
Example: JDBC in Servlet
@WebServlet("/dbExample")
Suppose we have a MySQL table: public class DatabaseExampleServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
CREATE TABLE users (
id INT PRIMARY KEY AUTO_INCREMENT, [Link]("text/html");
name VARCHAR(100), PrintWriter out = [Link]();
email VARCHAR(100)
); // Database connection details
String url = "jdbc:mysql://localhost:3306/testdb"; // your DB name
String user = "root"; // your DB username
String password = "root"; // your DB password
try {
// Load MySQL driver
[Link]("[Link]");

// Connect
Connection con = [Link](url, user, password);
// Query
Statement stmt = [Link]();
ResultSet rs = [Link]("SELECT * FROM users");//
Display results
[Link]("<html><body>");
[Link]("<h3>Users in Database:</h3>");
while ([Link]()) {
[Link]("<p>ID: " + [Link]("id") +
", Name: " + [Link]("name") +
", Email: " + [Link]("email") + "</p>");
}
[Link]("</body></html>");
Summery
// Close •Session Tracking → HttpSession to store data across requests.
[Link](); •Database Connectivity → JDBC (DriverManager →
[Link](); Connection → Statement → ResultSet).
[Link]();
} catch (Exception e) {
[Link]("<p>Error: " + [Link]() + "</p>");
}

[Link]();
} When you hit [Link] it fetches all users and displays them as
} HTML.

You might also like