Showing posts with label WebServlet Annotation. Show all posts
Showing posts with label WebServlet Annotation. Show all posts

Friday, 6 June 2014

Servlet with Annotation

Master Core Java & Servlets!

Subscribe to Ram N Java for beginner-friendly coding walkthroughs, modern Java web development, and hands-on tutorials!

🔔 Subscribe to Ram N Java

The Evolution of Servlet Configuration

Traditionally, configuring Java servlets required declaring every servlet mapping and initialization parameter in the XML-based deployment descriptor (web.xml). While this approach centralized application configuration, large enterprise applications often resulted in verbose, difficult-to-maintain XML files.

Starting with Servlet 3.0, Java EE introduced annotations to streamline web component registration directly within Java source code. By leveraging annotations such as @WebServlet, developers can declare URL mappings, initialization parameters, and startup behavior directly on the class definition, eliminating the need for bulky XML declarations.

Configuring Servlets with @WebServlet

The @WebServlet annotation (from the javax.servlet.annotation package) provides a clean, declarative syntax. It supports a variety of attributes that mirror traditional web.xml tags:

  • urlPatterns (or value): Specifies the URL path or patterns that trigger the servlet.
  • name: Defines the logical name of the servlet component.
  • loadOnStartup: Controls whether the container initializes the servlet eagerly at application deployment or lazily on first request.
  • initParams: Allows defining key-value initialization parameters using nested @WebInitParam annotations.
@WebServlet(
    name = "UserServlet",
    urlPatterns = {"/users", "/profile"},
    loadOnStartup = 1,
    initParams = {
        @WebInitParam(name = "defaultRole", value = "Guest")
    }
)
public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        resp.getWriter().println("Servlet configured cleanly with annotations!");
    }
}

Key Advantages of Annotation-Based Servlets

  • Reduced Boilerplate: No need to write duplicate servlet declarations and servlet-mapping blocks in web.xml.
  • High Cohesion: Configuration settings live right alongside the servlet's implementation code, making refactoring and maintenance straightforward.
  • Flexible Override: Deployment descriptors can still override annotations when environment-specific customization is needed.

Recommended Related Tutorials

Continue exploring servlet fundamentals and architecture with these tutorials from Ram N Java:


Click here to watch in Youtube : https://www.youtube.com/watch?v=9BkjzpuJK4w

Click the below Image to Enlarge
Servlet with Annotation
AnnotationServletDemo Project Dir Structure
Servlet with Annotation

HelloServlet.java
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/hello")
public class HelloServlet extends HttpServlet
{
    private static final long serialVersionUID = 1L;

    public void init() throws ServletException
    {
        System.out.println("-----------------------------------------");
        System.out.println(" Init method is called in "
                + this.getClass().getName());
        System.out.println("--------------------------------------");
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        out.print("<html><body>");
        out.print("<h3>Hello Servlet</h3>");
        out.print("</body></html>");

    }

    public void destroy()
    {
        System.out.println("-----------------------------------------");
        System.out.println(" destroy method is called in "
                + this.getClass().getName());
        System.out.println("-----------------------------------------");
    }

}

index.html
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ServletContextAttributeDemo</title>
</head>
<body>
    <form action="hello" method="GET">
        <input type="submit" value="Submit" />
    </form>
</body>
</html>

Environment Used 

JDK version :1.7.0_51
Tomcat version : 7.0.50 

To Download AnnotationServletDemoApp Project Click the below link

https://sites.google.com/site/javaee4321/servlets/AnnotationServletDemoApp.zip?attredirects=0&d=1

See also:

  • Servlets Tutorial
  • All Design Patterns Links
  • Tutorials