Category: Servlet Updated: Jul 07, 2026

Complete Guide to @WebServlet in Java: Easy Servlet Mapping for Beginners

Java @WebServlet Annotation Tutorial for Beginners: How to Create Servlets
Java @WebServlet Annotation Tutorial for Beginners: How to Create Servlets

Learn Through a Conversation Between a Teacher and a Student

Student

"When I create a Servlet in Java, how do I connect it to a URL?"

Teacher

"In modern Java web development, you can use the @WebServlet annotation to map a URL to a Servlet."

Student

"So I don’t need to edit web.xml anymore?"

Teacher

"Exactly. @WebServlet makes configuration easier and cleaner for Java beginners."

Student

"I want to understand how to use it in real projects."

Teacher

"Let’s go step by step and learn how to use it!"

1. What Is @WebServlet?

Key Takeaway: Let's dive into the core concepts of "1. What Is @WebServlet?" cleanly and effectively.

1. What Is @WebServlet?
1. What Is @WebServlet?

In Java web development, the @WebServlet annotation is used to define a Servlet and map it to a specific URL pattern. This is part of Java programming basics and is widely used in modern Servlet applications.

Before annotations were introduced, developers had to configure Servlets in the web.xml file. This approach was more complex and harder to manage. With @WebServlet, everything can be done directly in Java code.

For Java beginners, learning this annotation is an important step in understanding how Java Servlets work in real-world web applications.

2. Basic Usage of @WebServlet

2. Basic Usage of @WebServlet
2. Basic Usage of @WebServlet

The most basic way to use @WebServlet is to define a URL pattern that the Servlet will handle.


import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
import java.io.IOException;

@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.getWriter().println("Hello from Servlet!");
    }
}

Hello from Servlet!

In this example, accessing /hello in the browser will execute the Servlet.

3. Multiple URL Patterns

3. Multiple URL Patterns
3. Multiple URL Patterns

You can assign multiple URL patterns to a single Servlet. This is useful when you want different URLs to trigger the same logic.


@WebServlet({"/home", "/index", "/start"})
public class MultiUrlServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.getWriter().println("Multiple URL mapping example");
    }
}

This allows users to access the same page using different URLs, improving flexibility in web application design.

4. Using doGet and doPost

Key Takeaway: Let's dive into the core concepts of "4. Using doGet and doPost" cleanly and effectively.

4. Using doGet and doPost
4. Using doGet and doPost

Servlets usually handle HTTP requests using methods like doGet and doPost. These methods are triggered depending on the type of request.


@WebServlet("/form")
public class FormServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.getWriter().println("This is a GET request.");
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String name = request.getParameter("name");
        response.getWriter().println("Hello, " + name);
    }
}

Understanding how these methods work is essential for handling user input in Java web applications.

5. Important Attributes of @WebServlet

5. Important Attributes of @WebServlet
5. Important Attributes of @WebServlet

The @WebServlet annotation supports several attributes that allow you to configure your Servlet more precisely.

  • name: Specifies the Servlet name
  • urlPatterns: Defines URL mappings
  • loadOnStartup: Controls when the Servlet is loaded

@WebServlet(
    name = "MyServlet",
    urlPatterns = {"/test"},
    loadOnStartup = 1
)
public class MyServlet extends HttpServlet {
}

These attributes help you customize the behavior of your Servlet depending on your application needs.

6. How @WebServlet Improves Development

6. How @WebServlet Improves Development
6. How @WebServlet Improves Development

Using annotations like @WebServlet simplifies development by reducing the need for XML configuration. This makes your code easier to read and maintain.

For beginners, this means you can focus more on learning Java programming basics instead of dealing with complex configuration files.

It also aligns with modern frameworks like Spring Boot, where annotation-based configuration is the standard approach.

7. Common Mistakes and Tips

Key Takeaway: Let's dive into the core concepts of "7. Common Mistakes and Tips" cleanly and effectively.

7. Common Mistakes and Tips
7. Common Mistakes and Tips

When using @WebServlet, beginners often make a few common mistakes.

  • Forgetting to import the annotation package
  • Using incorrect URL patterns
  • Not matching the HTTP method properly

Always double-check your URL mapping and ensure your Servlet is deployed correctly.

8. Real Example with HTML Form

8. Real Example with HTML Form
8. Real Example with HTML Form

Let’s combine HTML and Servlet to see how @WebServlet works in a real scenario.


<!DOCTYPE html>
<html>
<head>
    <title>Form Example</title>
</head>
<body>
    <form action="form" method="post">
        <input type="text" name="name">
        <button type="submit">Send</button>
    </form>
</body>
</html>

@WebServlet("/form")
public class FormServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String name = request.getParameter("name");
        response.getWriter().println("Hello, " + name);
    }
}

Hello, John

This example shows how user input is sent to the Servlet and processed using @WebServlet.

Summary

Summary
Summary

Key Points About @WebServlet in Java

In this Java tutorial for beginners, we explored the @WebServlet annotation, which is one of the most important features in modern Java web development. Understanding how to use this annotation is essential for building clean and maintainable Java Servlet applications.

First, we learned that @WebServlet allows developers to map a URL directly to a Servlet class. This eliminates the need for complex configuration in web.xml, making development much simpler and more efficient. For Java beginners, this is a huge advantage because it reduces the amount of setup required and helps you focus on core Java programming basics.

We also saw how easy it is to define a basic Servlet using a simple annotation like @WebServlet("/hello"). This mapping allows the web application to respond to user requests when they access a specific URL. This concept is fundamental in Java web applications and is used in almost every project.

Another important point is that @WebServlet supports multiple URL patterns. This means a single Servlet can handle different paths, making your application more flexible and easier to manage. This is especially useful when building larger applications where multiple entry points may lead to the same functionality.

We also reviewed how Servlets handle HTTP requests using methods such as doGet and doPost. These methods allow your application to process different types of requests, such as retrieving data or handling form submissions. Understanding how these methods work together with @WebServlet is essential for handling real user interactions.

Additionally, we discussed important attributes like name, urlPatterns, and loadOnStartup. These attributes give you more control over how your Servlet behaves and when it is loaded. Learning how to use these options will help you build more advanced and optimized applications.

One of the biggest benefits of using @WebServlet is improved readability and maintainability. Since everything is defined in Java code, it becomes easier to understand and manage your application structure. This aligns well with modern frameworks and best practices in Java development.

Finally, we looked at common mistakes such as incorrect URL patterns, missing imports, and misunderstanding request methods. Avoiding these mistakes will save you time and help you debug your applications more efficiently.

Sample Code: Simple URL Mapping Check


import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
import java.io.IOException;

@WebServlet("/check")
public class CheckServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.getWriter().println("Servlet is working correctly.");
    }
}

Servlet is working correctly.

This example shows how a simple URL mapping works using @WebServlet. When accessing the specified URL, the Servlet responds immediately.

Sample Code: Handling Multiple Requests


@WebServlet({"/page1", "/page2"})
public class MultiPageServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String uri = request.getRequestURI();
        response.getWriter().println("Accessed: " + uri);
    }
}

This demonstrates how one Servlet can handle multiple URLs, which is useful for simplifying your application structure.

Why Learning @WebServlet Matters

For anyone learning Java programming basics, mastering @WebServlet is a key step toward becoming a Java web developer. It helps you understand how requests are routed, how applications respond to users, and how modern Java applications are structured.

This knowledge is not only useful for Servlet-based applications but also prepares you for frameworks like Spring Boot, where annotations are heavily used.

By practicing these concepts, you will gain a deeper understanding of how web applications work and how to build scalable, maintainable systems using Java.

Review Conversation Between the Teacher and Student

Student

"So @WebServlet connects a URL directly to a Java class?"

Teacher

"Yes, it maps a URL pattern to a Servlet, making it easy to handle web requests."

Student

"And I don’t need web.xml anymore?"

Teacher

"That’s right. Modern Java development uses annotations like this to simplify configuration."

Student

"Can I use one Servlet for multiple URLs?"

Teacher

"Yes, you can define multiple URL patterns in the annotation."

Student

"I think I understand how routing works now."

Teacher

"Great! Keep practicing, and you’ll become more confident with Java web development."

Back to Category
Latest Articles
New1
Spring
Spring Boot and Java Version Compatibility Guide: Spring Boot 3.5 3.4 3.3 with Java 21 and Java 17
New
New2
Spring
Complete Guide to Spring Data JPA getReferenceById for Beginners
New
New3
Spring
Complete Guide to Spring Data JPA findAll for Beginners
New
New4
Spring
Spring Data JPA JpaRepository Tutorial for Beginners: Complete Guide to Database Access in Spring Boot
New
Popular Articles
No.1
Java&Spring記事人気No1
Spring
Complete Guide to Spring @GeneratedValue for Java Beginners – Understand Primary Key Generation in JPA
No.2
Java&Spring記事人気No2
Spring
Complete Guide to Spring @PreAuthorize for Java Beginners – Secure Your Application with Method-Level Security
No.3
Java&Spring記事人気No3
Spring
Spring Boot GetMapping Tutorial: Complete Guide to GetMapping in Java for Beginners
No.4
Java&Spring記事人気No4
Spring
Spring @Valid Annotation Tutorial for Beginners: Input Validation in Spring Boot
No.5
Java&Spring記事人気No5
Spring
Mastering the @PostMapping Annotation in Java Spring: A Complete Guide for Beginners
No.6
Java&Spring記事人気No6
Spring
Spring Data JPA Like Query Guide: findByFirstnameLike for Java Beginners
No.7
Java&Spring記事人気No7
Spring
Mastering the @Repository Annotation in Java Spring: A Complete Guide for Beginners
No.8
Java&Spring記事人気No8
Spring
Mastering the @Entity Annotation in Java Spring: A Complete Guide for Beginners