Week 3 - Introduction To Servlets
Week 3 - Introduction To Servlets
Introduction to Servlets
A Servlet is a special type of Java program that runs on a web server. Its main job is to
handle requests from users (like when someone visits a webpage) and then send back a
response (like showing a webpage or giving data).
The client (like a person using a web browser) asks for something, like a webpage or
information (just like a customer ordering food).
The servlet (the waiter) takes the request, processes it, and then returns something
useful to the client, like a webpage or the result of a form they filled out (just like the
waiter bringing food).
Dynamic Web Pages - Servlets allow web pages to change based on user input. For
example, when you log in to a website, the page changes to show your name and
personalized content. Servlets handle this behind the scenes.
Processing Forms - When you submit a form online (like a login form or a registration
form), a servlet processes the information, checks it, and gives you feedback (like
"Login successful" or "Incorrect password").
Servlets run on a web server (a powerful computer that hosts websites). They are part of
something called the Java Enterprise Edition (Java EE) framework. This framework includes
lots of tools and technologies that help create web applications.
Servlets specifically respond to HTTP requests, which are the requests your web browser
makes when you visit a website or click on a link. The servlet receives these requests and
decides what to do, such as loading a page, processing data, or sending information back to
your browser.
In short, servlets are essential for creating interactive and dynamic web applications,
allowing websites to respond to user actions and requests efficiently.
When you visit an online store and search for a product, the following happens:
1. Your browser sends a request to the server, asking for product information.
2. A Servlet on the server receives that request, looks up the product details in the
database, and sends back a webpage displaying the information you asked for.
1. What is a Servlet?
Servlets handle requests, process business logic, and respond to the client, often
returning HTML pages or JSON/XML data.
2. Servlet Lifecycle
The lifecycle of a servlet is controlled by the servlet container (such as Apache Tomcat). The
container is responsible for loading, initializing, executing, and destroying servlets.
Loading and Instantiation - The servlet class is loaded and instantiated by the server.
Initialization (init()) - The init() method is called once when the servlet is first loaded.
It’s used to initialize resources like database connections.
Service (service()) - The service() method is called each time the servlet responds to
a client request (HTTP request). It determines the type of request (GET, POST) and
forwards it to the appropriate method (doGet(), doPost()).
Destruction (destroy()) - The destroy() method is called before the servlet is removed
from memory. It’s used for cleanup tasks, like closing database connections.
Advantages of Servlets
2. Efficiency - Servlets are loaded once, and multiple requests can be handled by the
same instance, improving performance.
3. Security - Java provides a secure environment for servlets, including features like
secure communication, authentication, and authorization.
4. Integration - Servlets can easily interact with databases, APIs, and other services.
o Open NetBeans.
o Browse to your Tomcat installation folder, and then configure Tomcat with a
username and password (required for management).
o Click Finish.
Now that you have your environment set up, let's create a simple servlet to handle HTTP
requests and respond with a basic HTML page.
o Open NetBeans.
o In the Categories section, choose Java Web and select Web Application.
o Once your servlet is created, NetBeans will generate some basic code. Modify
it to display "Hello, World!" when the user accesses the servlet.
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;
@WebServlet("/hello")
public class HelloWorldServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
// Set the content type to text/html
response.setContentType("text/html");
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
// Handle POST requests here
}
}
o The PrintWriter is used to send text (in this case, HTML) to the client (web
browser).
o NetBeans will start Apache Tomcat, deploy your project, and open a browser
window.
o You should see the output: "Hello, World!" displayed on the web page.
Exercises
Objective: Modify the HelloWorldServlet to display the current date and time along
with the greeting.
Steps:
3. Modify the response to include the current date and time below the "Hello,
World!" message.
Expected Output: The webpage should display "Hello, World!" followed by the
current date and time.
Objective: Create a new servlet that accepts a user's name as a query parameter in
the URL and displays a personalized greeting.
Steps:
2. Use request.getParameter() to retrieve the user's name from the URL query
string (e.g., ?name=John).
3. Respond with "Hello, [name]!" where [name] is the name entered by the
user.
Additional Resources
Recommended Books
Marty Hall and Larry Brown, Core Servlets and JavaServer Pages (JSP), Sun
Microsystems Press.