Java Notes
Complete introduction to Java Servlets covering web development basics, HTTP protocol, servlet architecture, deployment descriptors, and how servlets work in Java EE web applications.
What is a Servlet?
A Servlet is a Java class that runs on a web server (like Apache Tomcat) and handles client requests (usually HTTP requests from browsers). It generates dynamic web content by processing input data, interacting with databases, and producing HTML, JSON, or other response formats.
Servlets are the foundation of Java web development and form the backbone of frameworks like Spring MVC.
Why Servlets Over Static HTML?
| Feature | Static HTML | Servlets |
|---|---|---|
| Content | Fixed | Dynamic |
| Database interaction | Not possible | Yes |
| User-specific content | No | Yes |
| Form processing | Limited | Full support |
| Session management | No | Built-in |
Servlet Architecture
Key Components
- Web Server — Handles HTTP connections (e.g., Apache HTTP Server)
- Servlet Container — Manages servlet lifecycle (e.g., Apache Tomcat, Jetty)
- Servlet — Java class that processes requests
- Deployment Descriptor (web.xml) — Configuration file for URL mapping
How a Servlet Container Works
| Client Request | Web Server → Servlet Container |
| │ | doGet() / doPost() │ |
| Response | Client |
Setting Up Your First Servlet
Prerequisites
- JDK 11+ installed
- Apache Tomcat 10+ (for Jakarta Servlet API)
- IDE: IntelliJ IDEA or Eclipse
Project Structure
Maven Dependency
<dependencies>
<dependency>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
<version>6.0.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.3.2</version>
</plugin>
</plugins>
</build>Your First Servlet
package com.example;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;
import java.io.*;
@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Set response content type
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
// Get writer to send response
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head><title>Hello Servlet</title></head>");
out.println("<body>");
out.println("<h1>Hello from Java Servlet!</h1>");
out.println("<p>Server Time: " + new java.util.Date() + "</p>");
out.println("</body>");
out.println("</html>");
}
}Deployment Descriptor (web.xml)
The web.xml file is the traditional way to configure servlets (before annotations):
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee
https://jakarta.ee/xml/ns/jakartaee/web-app_6_0.xsd"
version="6.0">
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>com.example.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>Annotation-Based Configuration vs web.xml
| Feature | @WebServlet Annotation | web.xml |
|---|---|---|
| Configuration | In Java code | Separate XML file |
| Ease of use | Simpler | More verbose |
| Override capability | Less flexible | Can override annotations |
| Best for | Small projects | Large enterprise apps |
// Annotation approach (modern)
@WebServlet(urlPatterns = {"/hello", "/hi"}, loadOnStartup = 1)
public class HelloServlet extends HttpServlet { }Servlet API Hierarchy
Key Interfaces
- Servlet — Defines lifecycle methods (
init,service,destroy) - ServletConfig — Servlet configuration parameters
- ServletContext — Application-wide shared data
- ServletRequest / ServletResponse — Request and response objects
Servlet vs CGI (Common Gateway Interface)
| Feature | Servlet | CGI |
|---|---|---|
| Language | Java | Any (Perl, C, etc.) |
| Performance | High (thread-based) | Low (process-based) |
| Memory | Shared across requests | New process per request |
| Portability | Platform independent | Platform dependent |
| Scalability | Excellent | Poor |
Common Mistakes to Avoid
- Not setting content type — Always call
response.setContentType()before writing - Writing after response is committed — Cannot set headers after
getWriter()is called - Not handling character encoding — Use UTF-8 for international characters
- Storing state in instance variables — Servlets are shared across threads (not thread-safe)
- Ignoring exception handling — Always handle
ServletExceptionandIOException
Interview Quick Notes
- Servlet is a server-side Java technology for handling HTTP requests
- Servlet container (Tomcat) manages the servlet lifecycle
@WebServletannotation replaces web.xml configuration- Servlets are thread-unsafe by default (one instance, multiple threads)
- The servlet API is now under
jakarta.servletpackage (formerlyjavax.servlet)
Summary
| Concept | Key Point |
|---|---|
| Servlet | Java class that handles HTTP requests on server |
| Container | Manages lifecycle, threading, and request routing |
| web.xml | Deployment descriptor for configuration |
| @WebServlet | Annotation-based URL mapping |
| HTTP | Stateless protocol; servlets add state via sessions |
Key Takeaways for Servlet Introduction
- This topic is fundamental in Java development and is frequently asked in interviews
- Make sure to do hands-on practice for practical implementation
- Understanding its use in real-world projects is important for writing production-ready code
- Keep referring to documentation and official Java docs for the latest updates
- Also develop testing and debugging skills alongside this topic
- Follow industry best practices and actively participate in code reviews
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Servlet Introduction.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Java Master Course topic.
Search Terms
java-master-course, java master course, java, master, course, servlets, jsp, servlet
Related Java Master Course Topics