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.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 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.

Maven dependencies

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
</dependency>

Maven Central

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.mybatis;

import org.apache.ibatis.annotations.ResultMap;
import org.apache.ibatis.annotations.Select;
import org.kodejava.mybatis.support.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>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.13</version>
    </dependency>
    <dependency>
        <groupId>com.mysql</groupId>
        <artifactId>mysql-connector-j</artifactId>
        <version>8.1.0</version>
    </dependency>
</dependencies>

Maven Central 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 itself. 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.lang.annotation;

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

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

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

        try {
            Class<? extends GetAllAnnotation> clazz = demo.getClass();

            // To get the sayHi() method we need to pass not only the method
            // name but also its parameters type so 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 annotation : annotations) {
                System.out.println("Type: " + annotation.annotationType());
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }

    @MyAnnotation("Hi")
    @HelloAnnotation(value = "Hello", greetTo = "Everyone")
    public void sayHi(String dataId, String name) {
        Map<String, String> 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.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.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.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<? extends GettingAnnotation> clazz = demo.getClass();
        Annotation[] annotations = clazz.getAnnotations();
        for (Annotation annotation : annotations) {
            System.out.println("Annotation Type: " + annotation.annotationType());
        }

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

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

            annotation = m.getAnnotation(HelloAnnotation.class);
            System.out.println("Value  : " + annotation.value());
            System.out.println("GreetTo: " + annotation.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 method = getClass().getMethod("sayHello");
            HelloAnnotation annotation = method.getAnnotation(HelloAnnotation.class);

            System.out.println(annotation.value() + " " + annotation.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.lang.annotation.HelloAnnotation
Value  : Hello
GreetTo: Universe
Value  : Hi
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.lang.annotation;

@HelloAnnotation(value = "Good Morning", greetTo = "Universe")
public class HelloAnnotationExample {
    public static void main(String[] args) {
        HelloAnnotationExample hello = new HelloAnnotationExample();
        hello.sayHi();
        hello.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 in front of it. The @ symbol will tell the compiler that it is an annotation.

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

package org.kodejava.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 is 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 store the annotation in the class file during compilation, and it is 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 method declaration in it with no implementation body.

What is @SuppressWarnings annotation?

The @SuppressWarnings annotation tells the compiler to suppress the warning messages it normally shows 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.basic;

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

public class SuppressWarningsExample {
    @SuppressWarnings(value={"deprecation"})
    public static void main(String[] args) {
        Date date = new Date(2021, Calendar.OCTOBER, 3);

        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.basic;

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.basic;

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

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

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

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