How to use annotations instead of web.xml in the servlet to specify url

Sheel picture Sheel · Jun 21, 2013 · Viewed 25.7k times · Source

How to provide an annotation mapping for web.XML in annotation. I have done with web.XML. I want to try with Annotation mapping, like so:

<web-app> 
  <servlet-mapping> 
  </servlet-mapping> 
</web-app>

Answer

Ramsharan picture Ramsharan · Jul 25, 2013

A simple example is :

@WebServlet(value="/hello")
public class HelloServlet extends HttpServlet {

    @Override
    public void doGet(HttpServletRequest request,HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();

    // then write the data of the response
    String username = request.getParameter("username");
    if (username != null && username.length() > 0) {
        out.println("<h2>Hello, " + username + "!</h2>");
       }
    }

}