Servlet Web Application without web.xml

Here is how we can simply write a tomcat servlet web application without web.xml. Yes, you heard it right and I am going to show you for what you are here. I have just learned it today with the help of my professor. (Thanks to him).
We can achieve this by using annotations which you might have heard in core Java. It is data about data.
In a single line, we will be doing the servlet mapping to url pattern. Here is how:
This doesn't work in versions of tomcat that are < 7. So make sure that you have at least Tomcat 7.

Project structure

      |__ index.html
      |__ WEB-INF
                         |__ classes
                                        |__ MySer.class

Simple HTML Form - index.html

        <form action="./hello">
            <input type="text" name="username"></input>
            <input type="submit"/>

Servlet Class with annotation

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
public class MySer extends HttpServlet
    public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException
        PrintWriter pw=res.getWriter();
        pw.println("<h1>Welcome "+req.getParameter("username")+"</h1>");

Here, at run time, the above servlet class is the one that will be executed for the url pattern /hello. So, whenever there is a request to the /hello then this class doGet() is activated. Isn't this great and simple? Here you can also include multiple url-patterns for the same class as urlPatterns takes a String[]. For example,
Here either /hello or /welcome, this MySer will be executed.

Posted by at on

Tags: Servlets,