Pin It

Using @WebServlet annotation to register Servlets without using web.xml

With the introduction of Annotations in Java, now its easy to remove xml configuration files with annotations. Registering each and every servlet in web.xml is quite hectic task. In order to avoid this, @WebServlet annotation is used. This post creates a simple Servlet named as HelloWorldServlet without making any registry in web.xml file.
@WebServlet annotation is used over the class level.  

package com.hubberspot.javaee;

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(name = "HelloWorldServlet" , urlPatterns = { "/HelloWorldServlet" })
public class HelloWorldServlet extends HttpServlet {

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

  response.setContentType("text/html");

  PrintWriter out = response.getWriter();

  try {
   out.println("<html>");
   out.println("<body>");
   out.println("<h2>Hello World !!!</h2>");
   out.println("</body>");
   out.println("</html>");
  } finally {
   out.close();
  }

 }

}



Here in above HelloWorldServlet @WebServlet(name = "HelloWorldServlet" , urlPatterns = { "/HelloWorldServlet" }) is equivalent to
<servlet>
    <servlet-name>HelloWorldServlet</servlet-name>
    <servlet-class>com.hubberspot.javaee.HelloWorldServlet</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>HelloWorldServlet</servlet-name>
    <url-pattern>/HelloWorldServlet</url-pattern>
</servlet-mapping>



Output of the program : 


 
Please Give Us Your 1 Minute In Sharing This Post!
SOCIALIZE IT →
FOLLOW US →
SHARE IT →
Related Posts Plugin for WordPress, Blogger...

Post your related queries below ...

comments powered by Disqus
Powered by Blogger.
 
© 2012 Learn Java by Examples Template by Hubber Spot