
What is a Java Servlet?
A Java Servlet is a Java class that handles requests and responses in a web application. Servlets run on a server (usually inside a servlet container like Apache Tomcat) and are capable of handling dynamic web content, such as processing form data, managing sessions, and generating HTML output.
In short, servlets act as the backbone of Java-based server-side programming.
Why Use Java Servlets?
Here are a few reasons why servlets are widely used:
Platform-independent: Servlets are written in Java, making them portable across different servers and platforms.
Efficient: They are lightweight and efficient for handling multiple client requests using threads instead of processes.
Scalable: Ideal for building scalable enterprise-level web applications.
Extensible: Can be integrated with other Java technologies like JSP, JDBC, and frameworks like Spring.
How Do Java Servlets Work?
The servlet lifecycle is managed by the servlet container (e.g., Tomcat). The lifecycle has three main methods:
init()
– Called once when the servlet is first loaded.service()
– Called every time the servlet receives a request.destroy()
– Called once when the servlet is taken out of service.
Here's how it typically works:
A user sends a request via a browser (e.g., by submitting a form).
The web server forwards this request to the servlet container.
The container finds the appropriate servlet and calls its
service()
method.The servlet processes the request and returns a response, usually HTML or JSON.
The response is sent back to the browser.
Setting Up Your Environment
Before creating your first servlet, you'll need:
JDK (Java Development Kit)
Apache Tomcat (or any servlet container)
Eclipse or IntelliJ IDEA (or any IDE of your choice)
Once your environment is ready, you can start building a simple servlet application.
Creating Your First Java Servlet
Here’s a basic example of a Java servlet:
import java.io.*;import javax.servlet.*;import javax.servlet.http.*;public class HelloWorldServlet extends HttpServlet { public 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>"); }}
Key Points:
The servlet extends
HttpServlet
.The
doGet()
method handles GET requests.HttpServletRequest
andHttpServletResponse
are used to read client input and write server output.
Deploying the Servlet
To run this servlet:
Package it as a WAR file or place the
.class
file inside the/WEB-INF/classes
directory of your web application.Create a
web.xml
deployment descriptor like this:
<web-app> <servlet> <servlet-name>HelloServlet</servlet-name> <servlet-class>HelloWorldServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>HelloServlet</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping></web-app>
Deploy your application to Apache Tomcat.
Access the servlet at:
http://localhost:8080/yourAppName/hello
Handling Form Data
Servlets can process form inputs using the doPost()
method:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = request.getParameter("username"); response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<h2>Welcome, " + name + "!</h2>");}
This is how you build dynamic, data-driven web pages using Java.
Working with Sessions
Servlets also provide built-in session management:
HttpSession session = request.getSession();session.setAttribute("user", "JohnDoe");
You can retrieve it later with:
String user = (String) session.getAttribute("user");
This allows for features like user login, cart handling, and personalized content.
Connecting to a Database
You can connect to a database using JDBC in your servlet:
Connection con = DriverManager.getConnection( "jdbc:mysql://localhost:3306/mydb", "user", "password");PreparedStatement stmt = con.prepareStatement("SELECT * FROM users WHERE id=?");stmt.setInt(1, 1);ResultSet rs = stmt.executeQuery();
Make sure to close connections and handle exceptions properly to avoid resource leaks.
Servlet vs JSP
While JSP (JavaServer Pages) is better suited for view logic, Servlets are ideal for handling backend processing. In modern applications, developers often use both:
Servlet for processing data and controlling flow.
JSP for generating the HTML view.
This separation helps keep code clean and manageable.
Best Practices
Always close database connections.
Avoid writing large HTML content in servlets — use JSP for views.
Use frameworks (like Spring MVC) for more advanced needs.
Keep your servlets modular and focused on specific tasks.
Conclusion
Mastering Java Servlets opens the door to building robust and scalable web applications in Java. Whether you're building login systems, dashboards, or enterprise-level tools, servlets provide a solid foundation.
By understanding how servlets work, how to handle requests and responses, manage sessions, and connect to databases, you’re well on your way to becoming a skilled Java web developer.