How do I define a servlet with @WebServlet annotation?

Annotations is one new feature introduces in the Servlet 3.0 Specification. Previously to declare servlets, listeners or filters we must do it in the web.xml file. Now, with the new annotations feature we can just annotate servlet classes using the @WebServlet annotation.

package org.kodejava.example.servlet;

import javax.servlet.ServletException;
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;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(
        name = "HelloAnnotationServlet",
        urlPatterns = {"/hello", "/helloanno"},
        asyncSupported = false,
        initParams = {
                @WebInitParam(name = "name", value = "admin"),
                @WebInitParam(name = "param1", value = "value1"),
                @WebInitParam(name = "param2", value = "value2")
        }
)
public class HelloAnnotationServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html");

        PrintWriter out = response.getWriter();
        out.write("<html><head><title>WebServlet Annotation</title></head>");
        out.write("<body>");
        out.write("<h1>Servlet Hello Annotation</h1>");
        out.write("<hr/>");
        out.write("Welcome " + getServletConfig().getInitParameter("name"));
        out.write("</body></html>");
        out.close();
    }
}

After you’ve deploy the servlet you’ll be able to access it either using the /hello or /helloanno url.

The table below give a brief information about the attributes accepted by the @WebServlet annotation and their purposes.

ATTRIBUTE DESCRIPTION
name The servlet name, this attribute is optional.
description The servlet description and it is an optional attribute.
displayName The servlet display name, this attribute is optional.
urlPatterns An array of url patterns use for accessing the servlet, this attribute is required and should at least register one url pattern.
asyncSupported Specifies whether the servlet supports asynchronous processing or not, the value can be true or false.
initParams An array of @WebInitParam, that can be used to pass servlet configuration parameters. This attribute is optional.
loadOnStartup An integer value that indicates servlet initialization order, this attribute is optional.
smallIcon A small icon image for the servlet, this attribute is optional.
largeIcon A large icon image for the servlet, this attribute is optional.

How do I use @Select annotation in MyBatis?

In the previous example How do I create MyBatis mapper? you’ve seen how to use a mapper to get a record from the database. In that example the select query is defined in the mapper xml file. For the same functionality MyBatis also offer a solution to use an annotation for the select query.

In this example we will use the @Select annotation to define the query. To map the query result we can use the @ResultMap annotation where the value passed to this annotation is the result map id that we’ve defined in the mapper xml file.
Let see an example of a mapper interface definition that use an annotation to get a record from database:

package org.kodejava.example.mybatis.annotation;

import org.apache.ibatis.annotations.ResultMap;
import org.apache.ibatis.annotations.Select;
import org.kodejava.example.mybatis.domain.Record;

public interface RecordMapper {
    /**
     * Get a single Record from the database based on the record
     * identified.
     *
     * @param id record identifier.
     * @return a record object.
     */
    @Select("SELECT * FROM records WHERE id = #{id}")
    @ResultMap("recordResultMap")
    Record getRecord(int id);
}

Maven Dependencies

<dependencies>
    <!--https://search.maven.org/remotecontent?filepath=org/mybatis/mybatis/3.5.0/mybatis-3.5.0.jar-->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.0</version>
    </dependency>
</dependencies>

Maven Central

How do I get all annotations?

To obtains all annotations for classes, methods, constructors, or fields we use the getAnnotations()method. This method returns an array of Annotation

In the following example we tried to read all annotations from the sayHi() method. First we need to obtain the method object it self. Because the sayHi() method has parameters, we need to pass not only the method name to the getMethod() method, but we also need to pass the parameter’s type.

The getAnnotations() method returns only annotation that has a RetentionPolicy.RUNTIME. Because other retention policy doesn’t allow the annotation to available at runtime.

package org.kodejava.example.lang.annotation;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class GetAllAnnotation {
    private Map<String, String> data = new HashMap<>();

    @SuppressWarnings("unchecked")
    public static void main(String args[]) {
        GetAllAnnotation demo = new GetAllAnnotation();
        demo.sayHi("001", "Alice");
        demo.sayHi("004", "Malory");

        try {
            Class clazz = demo.getClass();

            // To get the sayHi() method we need to pass not only the method
            // name but also its parameters type so the the getMethod() method
            // return the correct method for us to use.
            Method method = clazz.getMethod("sayHi", String.class, String.class);

            // Get all annotations from the sayHi() method. But this actually
            // will only return one annotation. Because only the HelloAnnotation
            // annotation that has RUNTIME retention policy, which means that
            // the other annotations associated with sayHi() method is not
            // available at runtime.
            Annotation[] annotations = method.getAnnotations();
            for (Annotation anno : annotations) {
                System.out.println("Type: " + anno.annotationType());
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }

    @SuppressWarnings("unchecked")
    @MyAnnotation("Hi")
    @HelloAnnotation(value = "Hello", greetTo = "Everyone")
    public void sayHi(String dataId, String name) {
        Map data = getData();
        if (data.containsKey(dataId)) {
            System.out.println("Hello " + data.get(dataId));
        } else {
            data.put(dataId, name);
        }
    }

    private Map<String, String> getData() {
        data.put("001", "Alice");
        data.put("002", "Bob");
        data.put("003", "Carol");
        return data;
    }
}
package org.kodejava.example.lang.annotation;

public @interface MyAnnotation {
    String value();
}

Check the HelloAnnotation on the following link How do I create a simple annotation?.

The result of this code snippet:

Hello Alice
Type: interface org.kodejava.example.lang.annotation.HelloAnnotation

How do I obtain annotations at runtime using reflection?

This example demonstrate how to obtain annotations of a class and methods. We use the reflection API to get class and method information from where we can read information about annotation attached to the class or the method.

package org.kodejava.example.lang.annotation;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

@HelloAnnotation(value = "Hello", greetTo = "Universe")
public class GettingAnnotation {
    public static void main(String[] args) {
        GettingAnnotation demo = new GettingAnnotation();

        Class clazz = demo.getClass();
        Annotation[] annotations = clazz.getAnnotations();
        for (Annotation anno : annotations) {
            System.out.println("Annotation Type: " + anno.annotationType());
        }

        HelloAnnotation anno = (HelloAnnotation) clazz.getAnnotation(HelloAnnotation.class);
        System.out.println("Anno Value  : " + anno.value());
        System.out.println("Anno GreetTo: " + anno.greetTo());

        try {
            Method m = clazz.getMethod("sayHi");

            anno = m.getAnnotation(HelloAnnotation.class);
            System.out.println("Anno Value  : " + anno.value());
            System.out.println("Anno GreetTo: " + anno.greetTo());
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }

        demo.sayHello();
    }

    @HelloAnnotation(value = "Hi", greetTo = "Alice")
    public void sayHi() {
    }

    @HelloAnnotation(value = "Hello", greetTo = "Bob")
    public void sayHello() {
        try {
            Method m = getClass().getMethod("sayHello");
            HelloAnnotation anno = m.getAnnotation(HelloAnnotation.class);

            System.out.println(anno.value() + " " + anno.greetTo());
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }
}

You can find the HelloAnnotation annotation that we use above on the following example: How do I create a simple annotation?.

The result of our program is:

Annotation Type: interface org.kodejava.example.lang.annotation.HelloAnnotation
Anno Value  : Hello
Anno GreetTo: Universe
Anno Value  : Hi
Anno GreetTo: Alice
Hello Bob

How do I annotate a class or method?

This example show you how to use the HelloAnnotation annotation on the previous example code, How do I create a simple annotation?. We add the HelloAnnotation annotation to our class and its methods.

package org.kodejava.example.lang.annotation;

@HelloAnnotation(value = "Good Morning", greetTo = "Universe")
public class HelloAnnotationExample {
    public static void main(String[] args) {
        HelloAnnotationExample anno = new HelloAnnotationExample();
        anno.sayHi();
        anno.sayHello();
    }

    @HelloAnnotation(value = "Hi there", greetTo = "Alice")
    private void sayHi() {
    }

    @HelloAnnotation(value = "Hello there", greetTo = "Bob")
    private void sayHello() {
    }
}

How do I create a simple annotation?

Metadata is a way to add some supplement information to the source code. This information is called annotation will not change how the program runs. This metadata can be used by other tools such as source code generator for instance to generate additional code at the runtime. Or it will be used by a dependency injection framework such as the Spring Framework.

The annotation can be attached to Classes, Methods, etc. To create an annotation we use the interface keyword and add an @ symbol infront of it. The @ symbol will tell the compiler that it doing some business with an annotation.

So now let us see the code for a simple annotation, a HelloAnnotation.

package org.kodejava.example.lang.annotation;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
public @interface HelloAnnotation {
    String value();
    String greetTo();
}

All annotations extend the java.lang.annotation.Annotation interface, which means that java.lang.annotation.Annotation is the super-interface of all annotations

An annotation need to have a RetentionPolicy that will be the scope of the annotation where at this point the annotation will be ignored or discarded. The values are RetentionPolicy.SOURCE, RetentionPolicy.CLASS and RetentionPolicy.RUNTIME. When no retention policy defined it will use the default retention policy which is the RetentionPolicy.CLASS.

Annotation with RetentionPolicy.SOURCE retention policy will be retained only in the source code, it available to the compiler when it compiles the class and will be discarded after that. The RetentionPolicy.CLASS retention policy will make the annotation stored in the class file during compilation, but will not available during the runtime. And the RetentionPolicy.RUNTIME retention policy will stored the annotation in the class file during compilation and it also available to JVM at runtime.

In the example above you also see that the HelloAnnotation have two members value() and greetTo(). Annotations only have a methods declaration in it with no implementation body.

What is SuppressWarnings annotation?

The @SuppressWarnings annotation tells the compiler to suppress the warning messages it normally show during compilation time. It has some level of suppression to be added to the code, these level including: all, deprecation, fallthrough, finally, path, serial and unchecked.

package org.kodejava.example.annotation;

import java.util.Date;

public class SuppressWarningsExample {
    @SuppressWarnings(value={"deprecation"})
    public static void main(String[] args) {
        Date date = new Date(2008, 9, 30);

        System.out.println("date = " + date);
    }
}

In the example above if we don’t use @SuppressWarnings annotation the compiler will report that the constructor of the Date class called above has been deprecated.

How do I use Override annotation?

We use the @Override annotation as part of method declaration. The @Override annotation is used when we want to override methods and want to make sure have overridden the correct methods.

As the annotation name we know that there should be the same method signature in the parent class to override. That means using this annotation let us know earlier when we are mistakenly override method that doesn’t exist in the base class.

package org.kodejava.example.annotation;

public class OverrideExample {
    private String field;
    private String attribute;

    @Override
    public int hashCode() {
        return field.hashCode() + attribute.hashCode();
    }

    @Override
    public String toString() {
        return field + " " + attribute;
    }
}

How do I mark method as deprecated?

To mark a method as deprecated we can use the JavaDoc @deprecated tag. This is what we did since the beginning of Java. But when a new metadata support introduced to the Java language we can also use annotation. The annotation for marking method as deprecated is @Depreated.

The difference between these two that the @deprecated is place in the JavaDoc comment block while the @Deprecated is placed as a source code element.

package org.kodejava.example.annotation;

import java.util.Date;
import java.util.Calendar;

public class DeprecatedExample {
    public static void main(String[] args) {
        DeprecatedExample de = new DeprecatedExample();
        de.getDate();
        de.getMonthFromDate();
    }

    /**
     * Get current system date.
     *
     * @return current system date.
     * @deprecated This method will removed in the near future.
     */
    @Deprecated
    public Date getDate() {
        return new Date();
    }

    public int getMonthFromDate() {
        return Calendar.getInstance().get(Calendar.MONTH);
    }
}