🛠️ Steps to Create a Servlet (Classic web.xml Approach)
✅ 1. Create a Java Class That Extends HttpServlet
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
response.getWriter().write("<h1>Hello, Stanley!</h1>");
}
}
✅ 2. Compile the Servlet
Make sure to include the servlet API jar in your classpath:
javac -classpath /path/to/servlet-api.jar HelloServlet.java
✅ 3. Create a Deployment Structure (WAR-like)
Your project structure should look like:
/MyApp
├── WEB-INF/
│ ├── web.xml
│ └── classes/
│ └── HelloServlet.class
✅ 4. Define the Servlet in web.xml
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" version="3.1">
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
✅ 5. Deploy to a Servlet Container (e.g., Tomcat)
- Package everything in a
.warfile:
jar -cvf MyApp.war *
Place it in:
/path/to/tomcat/webapps/
Start Tomcat:
catalina.sh run
Open in browser:
http://localhost:8080/MyApp/hello
Boom 💥! You’ve built a working servlet.
🧪 Modern Approach with Annotations (No web.xml Required)
import javax.servlet.annotation.WebServlet;
@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
res.getWriter().write("Hello from annotated servlet!");
}
}
Just compile & deploy — servlet container reads the annotation.
🔁 Summary of Steps
| Step | Description |
|---|---|
| 1. Create Servlet Class | Extend HttpServlet, override methods |
| 2. Compile It | Include servlet-api.jar |
| 3. Create Web App Structure | Place .class in WEB-INF/classes |
4. Configure (web.xml) | Or use @WebServlet annotation |
| 5. Deploy to Container | Like Tomcat or Jetty |
| 6. Access via Browser | Based on mapped URL pattern |