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


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

Simple HTML Form - index.html


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

Servlet Class with annotation


import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.*;
@WebServlet(urlPatterns={"/hello"})
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>");
       
        pw.close();
    }
}

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,
@WebServlet(urlPatterns={"/hello","/welcome"})
Here either /hello or /welcome, this MySer will be executed.


Posted by at on

Tags: Servlets,