Servlet Annotation

Annotations are used to provide the information about the program. In servlets if we don’t want to deploy servlet class configurations in web.xml file then we can use annotations.

We can say that annotation removes the requirement of web.xml file. Thus, it makes our servlet program reliable and efficient. 

Java provides @WebServlet annotation in javax.servlet.annotation package. We just required to pass path name as url pattern with this annotation.

Syntax:

@WebServlet(“/pathname”)

Servlet Annotation Example

Let's understand servlet annotation with the help of an example.

AnnotationExample.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
@WebServlet("/AnnotationExample")
public class AnnotationExample extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException
{
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
pw.println("");
pw.println("
Servlet Annotation
");
pw.println("");
}
}

Output