servlet-3.0

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


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>

Solution

  • 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>");
           }
        }
    
    }