Create Servlet using @WebServlet

[Updated: Mar 15, 2016, Created: Jan 22, 2016]

@WebServlet annotation is used to define a Servlet component in a web application. Let's consider following web.xml configuration.

<servlet>
    <servlet-name>viewController</servlet-name>
    <servlet-class>com.logicbig.servlet.ViewController</servlet-class>
    <init-param><param-name>renderer-class-name</param-name>
        <param-value>com.logicbig.HtmlRenderer</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

......

<servlet-mapping>
    <servlet-name>viewController</servlet-name>
    <url-pattern>/view/*</url-pattern>
</servlet-mapping>

In following example we will use annotations to do the same mapping.

  1. Prepare project
    • Create web application using maven-archetype-webapp, steps here.
    • Delete web.xml, we don't need it at all.
    • Delete webapp/index.jsp.
    • In pom.xml add dependency of javax.servlet-api:3.0.1
    • In pom.xml also add tomcat7-maven-plugin to run it as embedded server.
  2. Create a servlet class ViewController, annotated with @WebServlet. Also we are going to specify all configurations mentioned in above web.xml example.
    @WebServlet(name = "viewController", urlPatterns = {"/view/*"},
            initParams = @WebInitParam(name = "renderer-class-name"
                    , value = "com.logicbig.HtmlRenderer"),
            loadOnStartup = 1)
    public class ViewController extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest req,
                             HttpServletResponse resp) throws ServletException, IOException {
    
            String renderer = getServletConfig().getInitParameter("renderer-class-name");
            PrintWriter writer = resp.getWriter();
            writer.println("renderer: " + renderer);
    
            String servletName = getServletConfig().getServletName();
            writer.println("servlet name " + servletName);
        }
    }
  3. Our web application is ready to be used now. From command line, go to project root and run
    mvn clean tomcat7:run-war
  4. Put following url in your browser:
    http://localhost:8080/webservlet-example/view


Example Project

Dependencies and Technologies Used :

  • Java Servlet API 3.0.1
  • JDK 1.8
  • Maven 3.0.4

Webservlet Example Select All Download
  • web-servlet-example
    • src
      • main
        • java
          • com.logicbig.servlet
        • webapp

See Also