Thursday, 1 October 2015

Servlet with Annotation (feature of servlet3)

Servlet with Annotation (feature of servlet3)

Annotation represents the metadata. If you use annotation, deployment descriptor (web.xml file) is not required. But you should have tomcat7 as it will not run in the previous versions of tomcat. @WebServlet annotation is used to map the servlet with the specified name.

Example of simple servlet by annotation

There is given the simple example of servlet with annotation.

Simple.java

  1. import java.io.IOException;  
  2. import java.io.PrintWriter;  
  3.   
  4. import javax.servlet.ServletException;  
  5. import javax.servlet.annotation.WebServlet;  
  6. import javax.servlet.http.HttpServlet;  
  7. import javax.servlet.http.HttpServletRequest;  
  8. import javax.servlet.http.HttpServletResponse;  
  9.   
  10. @WebServlet("/Simple")  
  11. public class Simple extends HttpServlet {  
  12.     private static final long serialVersionUID = 1L;  
  13.   
  14.     protected void doGet(HttpServletRequest request, HttpServletResponse response)  
  15.                             throws ServletException, IOException {  
  16.           
  17.   
  18.         response.setContentType("text/html");  
  19.         PrintWriter out=response.getWriter();  
  20.           
  21.         out.print("<html><body>");  
  22.         out.print("<h3>Hello Servlet</h3>");  
  23.         out.print("</body></html>");  
  24.     }  
  25. }  


example of servlet with annotation

No comments:

Post a Comment