How to Define a Servlet Using Java Annotations Instead of XML

Posted on Mar 23, 2013 (last modified May 8, 2021)

With Servlet 3.0, it’s now possible to define your servlet using annotations instead of XML in the web deployment descriptor (web.xml). This can simplify maintenance and deployments because it keeps the servlet definition inline with the servlet’s actual code – everything’s conveniently found and managed together in one file. For those of you ready to start evolving into Java EE 6, here’s the essential information you need to know.

Use the @WebServlet annotation to define (declare) your servlet.

@WebServlet( description = "Main dispatcher for the application.", urlPatterns = { "/HelloServlet", "/" }) public class HelloServlet extends HttpServlet { // servlet code... }

Here's another example...

@WebServlet(value="/hello") public class HelloServlet extends GenericServlet { // servlet code... }

Note that I’ve defined URL mappings using urlPatterns in one case and then using value in another. The JavaDoc for the @WebServlet annotation states they are the same. There are other optional elements that can be used with the annotation (e.g. initParams, loadOnStartup, etc.) and those can be found in the JavaDoc also.