Nearby lessons

5 of 34

Servlet - Annotation-Based Servlets (3.0)

📌 What You Will Learn
  • Understand annotations in Servlet 3.0
  • Use @WebServlet to define URL patterns
  • Compare Servlet 2.x vs 3.x folder structures

Servlet 3.0 introduced annotations, allowing you to replace web.xml configuration with Java annotations. This lesson covers annotation-based servlet development with complete code examples.

Annotations in Servlet 3.0

Annotations (MetaData — data about data) provide extra information about components. All servlet-related annotations are available in:

javax.servlet.annotation

When using annotations, import the package:

import javax.servlet.annotation.*;

Annotations can replace web.xml configurations up to a certain level. Sometimes you can remove web.xml entirely.

Defining URL patterns with annotations:

  • Single URL: @WebServlet("/test")
  • Multiple URLs: @WebServlet({"/test", "/demo", "/hello"})

FirstServlet.java with @WebServlet

Access the servlet at: http://localhost:7777/advapps1A3X/test

Example02
JCode Cell
1 
2import javax.servlet.*;
3import java.io.*;
4import java.util.*;
5import javax.servlet.annotation.*;
6@WebServlet("/test")
7public class FirstSevlet implements Servlet
8{
9static
10{
11System.out.println("servlet class loading..");
12}
13public FirstSevlet()
14{
15System.out.println("Servlet class Instantiation...");
16}
17public void init(ServletConfig conf) throws ServletException
18{
19System.out.println("Init Method called");
20}
21public void service(ServletRequest req , ServletResponse resp) throws ServletException,IOException
22{
23System.out.println("Service Method called");
24resp.setContentType("text/html");
25PrintWriter out = resp.getWriter();
26out.println("<html><body bgcolor=green text=white><h1>Welcome Innocent Adv.Java Students<br/>");
27out.println("The Server Time is :"+new Date()+"</h1></body></html>");
28}
29public void destroy()
30{
31System.out.println("Destroy Method called");
32}
33public ServletConfig getServletConfig()
34{
35return null;
36}
37public String getServletInfo()
38{
39return "written by durga";
40}
41}
42

Servlet 2.x vs 3.x Folder Structure

In Servlet 3.x, web.xml is optional — the @WebServlet annotation handles mapping. The folder structure is simplified:

Servlet 2.xServlet 3.x
advapps1A/advapps1A/
  WEB-INF/  WEB-INF/
    web.xml    classes/
    classes/      FirstServlet.class
      FirstServlet.class      (no web.xml needed)
📝 Key Takeaways
  • @WebServlet annotation replaces web.xml mapping
  • Multiple URL patterns supported
  • Simplified folder structure without web.xml
  • Exam-style questions at the end

🧠 Test Your Knowledge

3 Questions
Progress: 0 / 3