Java Servlet Annotation.

What is Servlet Annotation?

  • Up to Servlet version 2.5 you had to set the servlet URL and optionally enter a name and/or parameters for a servlet in the web descriptor, web.xml.
    Example of a servlet configuration in web.xml :
    ...
    <servlet>
      <servlet-name>SimpleServlet</servlet-name>
      <servlet-class>app.simple.SimpleServlet</servlet-class>
      <init-param>
        <param-name>param1</param-name>
        <param-value>value1</param-value>
      </init-param>    
      <init-param>
        <param-name>param2</param-name>
        <param-value>value2</param-value>
      </init-param>
    </servlet>
    <servlet-mapping>
      <servlet-name>SimpleServlet</servlet-name>
      <url-pattern>/mySimpleServlet</url-pattern>
    </servlet-mapping>
    ...
  • Java EE 6 came with a new servlet version 3.0 that provides the ability to specify this configuration by using annotation, @WebServlet().
    A servlet URL and optionally enter a name and/or parameters can then be entered in front of a servlet class:
    @WebServlet(name = "SimpleServlet", urlPatterns = {"/mySimpleServlet"},
    initParams = {
      @WebInitParam(name = "param1", value = "value1"),
      @WebInitParam(name = "param2", value = "value2")})
    
    public class SimpleServlet extends HttpServlet {
    ....
    }

Example of Servlet Annotation.

As selected we use Netbeans IDE and Glassfish Server.

You can download this example here (needed tools can be found in the right menu on this page).

If you like to participate in the review of this example you must first create a Web project in Netbeans (the project name is ServletAnnotation).

  • Servlet Annotation example:
    package app.servlet;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    import javax.servlet.ServletConfig;
    import javax.servlet.annotation.WebInitParam;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    /*
    If a web application is configured both through annotations and through
    a web.xml deployment descriptor, settings in web.xml take precedence.
    */
    @WebServlet(name = "SimpleServlet", urlPatterns = {"/mySimpleServlet"},
    initParams = {
      @WebInitParam(name = "param1", value = "value1"),
      @WebInitParam(name = "param2", value = "value2")})
    
    public class SimpleServlet extends HttpServlet {
      @Override
      protected void doGet(HttpServletRequest request, HttpServletResponse response) {
        try {
          response.setContentType("text/html");
          PrintWriter printWriter = response.getWriter();
          printWriter.println("<h2>");
          printWriter.println("If you are reading this, "
                  + "your Servlet works fine!");
          printWriter.println("</h2>");
          ServletConfig servletConfig = getServletConfig();
          String param1Val = servletConfig.getInitParameter("param1");
          String param2Val = servletConfig.getInitParameter("param2");
          printWriter.println("<p>");
          printWriter.println("Value of param1 is " + param1Val);
          printWriter.println("</p>");
          printWriter.println("<p>");
          printWriter.println("Value of param2 is " + param2Val);
          printWriter.println("</p>");
        } catch (IOException ioException) {
          System.out.println(ioException.getMessage());
        }
      }
    }

    For those who participate in the review: create a Servlet in Netbeans and replace generated code for the servlet with that shown above (the servlet name is SimpleServlet).

Creating Deployment descriptor.

  • To run this Servlet you have to deploy it to a web-server or a Application server. To deploy means to install the Servlet with some instruction to a such server.
  • When using annotation instructions are mainly defined in the code. The rest of the instructions should be in the deployment descriptor, web.xml.

    For those who participate in the review: create a Standard web descriptor in Netbeans and create a welcome-file tag as shown below.

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 
    http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
             version="3.1">
      <session-config>
        <session-timeout>
          30
        </session-timeout>
      </session-config>
      <welcome-file-list>
        <welcome-file>mySimpleServlet</welcome-file>
      </welcome-file-list>
    </web-app>
  • This file starts with the normal xml tag for a XML file and the root tag for the deployment descriptor is web-app.
  • If no session-timeout (the server ends the service of the application after this time) is given a standard timeout for the server is used as timeout for the application.
  • The welcome-file tag specifies the startup for our application, which in this case and our application is the servlet with url mySimpleServlet.

Creating Web-server Deployment descriptor.

  • The context-root (in example /ServletAnnotation) for the application will in most cases be specified by a server vendor deployment descriptor.

    For those who participate in the review: create a deployment descriptor in Netbeans.

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE sun-web-app PUBLIC "-//Sun Microsystems, 
    Inc.//DTD GlassFish Application Server 3.0 Servlet 3.0//EN" 
    "http://www.sun.com/software/appserver/dtds/sun-web-app_3_0-0.dtd">
    <sun-web-app error-url="">
      <context-root>/ServletAnnotation</context-root>
      <class-loader delegate="true"/>
      <jsp-config>
        <property name="keepgenerated" value="true">
          <description>
            Keep a copy of the generated servlet class' java code.
          </description>
        </property>
      </jsp-config>
    </sun-web-app>

Run the application.

  • For those who participate in the review: right click the Web-project and select Run.
  • This results in that the application will be deployed to the server and started.
  • The browser will display:

    If you are reading this, your Servlet works fine!

    Value of param1 is value1

    Value of param2 is value2

© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.