Creating Your First Servlet Program: A Step-by-Step Guide
his guide walks you through creating your first Java Servlet: a simple “Hello World” program. You’ll also learn how to deploy the servlet on Apache Tomcat and access it through a web browser.
Step 1: Create a Simple "Hello World" Servlet
1. Write the Servlet Code
- Open your IDE (Eclipse or IntelliJ IDEA).
- Create a new Dynamic Web Project (name it
HelloWorldServletApp
). - Inside the
src
folder, create a new servlet class:
Code Example:
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
// Annotation-based servlet mapping
@WebServlet("/hello")
public class HelloWorldServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
response.getWriter().println("<h1>Hello, World! Welcome to Servlets.</h1>");
}
}
Step 2: Deployment Process in Tomcat
. Export Your Project to a WAR File
- In Eclipse:
- Right-click your project →
Export
→WAR file
. - Specify a destination folder and name the file (e.g.,
HelloWorldServletApp.war
).
- Right-click your project →
2. Copy the WAR File to the Tomcat webapps
Directory
- Locate your Apache Tomcat installation directory (e.g.,
C:\Apache\Tomcat
). - Copy the WAR file to the
webapps
folder.
3. Start the Tomcat Server
- Navigate to the Tomcat
bin
folder and run:startup.bat
(Windows)./startup.sh
(Linux/Mac).
4. Verify Deployment
- Tomcat will automatically deploy the WAR file.
- Check the
webapps
folder for an extracted directory namedHelloWorldServletApp
.
Step 3: Accessing the Servlet via a Web Browser
Open Your Browser
Type the following URL in your browser:
http://localhost:8080/HelloWorldServletApp/hello
View the Output
You should see the following output on your browser
Hello, World! Welcome to Servlets.
Best Practices for a First Servlet Program
Annotation vs.
web.xml
:- Use
@WebServlet
annotations for simple projects. - Use
web.xml
for advanced configurations like filters or listeners.
- Use
Code Readability: Keep your servlet logic simple and clean, especially for beginners.
Proper Deployment: Always check Tomcat logs (
logs/catalina.out
) for errors if your servlet doesn’t load.Testing URL: Always double-check the URL structure:
http://<hostname>:<port>/<project-name>/<servlet-mapping>