Servlet Annotation Example

This example demonstrates the usage of annotations in order to configure Servlets.

In our previous tutorials we used deployment descriptor (web.xml file) to configure our servlets. Since Servlet 3.0 you can use the @WebServlet annotation instead. This annotation allows you to set several attributes to the servlet like name, URL and more.

Annotations vs. Deployment Descriptor

What’s the difference? Well, obviously the deployment descriptor is a separate file where you set configuration values in XML format, where the annotation is directly embedded in your source code. Use annotations if you prefer to have code and configuration at the same place for better readability. Deployment descriptors are the exact opposite – you separate code and configuration. This way you do not need to recompile the entire project if you want to change a single configuration value.

For many Java Enterprise components there are both versions available – annotation or descriptor. But others can be configured either only with annotations or via the deployment descriptor. In case of Servlets you can choose one or the other method.




WebServlet Annotation Attributes

There are several attributes you can choose from to configure your Servlets

Required

  • value or urlPatterns String[] – Specify one or more URL patterns of the servlet. Either of attribute can be used, but not both. Default value for urlPatterns is {} and the default for value is “”

Optional

  • asyncSupported boolean – Declares whether the servlet supports asynchronous operation mode. Default value is false
  • name String – The name of the servlet. Default value is “”
  • description String – The description of the servlet. Default value is “”
  • displayName String – The display name of the servlet. Default value is “”
  • initParams WebInitParam[] – The init parameters of the servlet. Default value is {}
  • largeIcon String – The large-icon of the servlet. Default value is “”
  • smallIcon String – The small-icon of the servlet. Default value is “”
  • loadOnStartup int – The load-on-startup order of the servlet. Default value is -1

 

Maven POM File for Servlets

We will use following pom.xml file to build the examples shown later in this tutorial

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>net.javatutorial.tutorials</groupId>
	<artifactId>ServletAnnotation</artifactId>
	<version>1</version>
	<packaging>war</packaging>

	<name>ServletAnnotation</name>
	<url>https://javatutorial.net</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.1.0</version>
			<scope>provided</scope>
		</dependency>
	</dependencies>
	
	<build>
		<finalName>servletannotation</finalName>
        <sourceDirectory>src/main/java</sourceDirectory>
        
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.3</version>
                <configuration>
                    <warSourceDirectory>src/main/webapp</warSourceDirectory>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

Do we need web.xml when we use annotations?

Short answer – no! You can entirely drop web.xml file if you choose to rely on annotations for all of your Servlet configurations. But I still encourage you to keep that file, or at least have one like shown in the example below. Web.xml is used for many other configurations, so you will need it sooner or later in your projects

<?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">

	<display-name>Servlet with Annotations Application</display-name>

</web-app>

If you prefer to skip web.xml entirely you will need to tell the war plugin in Maven’s pom.xml to stop looking for that file. You can do that by setting the failOnMissingWebXml to false like this:

<plugin>
	<groupId>org.apache.maven.plugins</groupId>
	<artifactId>maven-war-plugin</artifactId>
	<version>2.3</version>
	<configuration>
		<failOnMissingWebXml>false</failOnMissingWebXml>
	</configuration>
</plugin>

 

Servlet annotated with one URL pattern

Following example uses only one attribute to annotate the URL of the servlet. Given you are running your app on localhost and you deploy the app as servletannotation.war, the path to the servlet will be http://localhost:8080/servletannotation/hello

package net.javatutorial.tutorials;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/hello")
public class ServletWithAnnotations extends HttpServlet {

	private static final long serialVersionUID = -3462096228274971485L;

	@Override
	protected void doGet(HttpServletRequest reqest, HttpServletResponse response) 
			throws ServletException, IOException {
		response.getWriter().println("Hello World!");
	}

}

Servlet annotation with multiple attributes

In this example we will set the servlet name, the URL and load-0n-startup load priority. In our Simple Servlet Example we did this in web.xml file like this:

<?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">

	<display-name>Servlet with Annotations Application</display-name>

	<servlet>
		<servlet-name>simpleServlet</servlet-name>
		<servlet-class>net.javatutorial.tutorials.ServletWithAnnotations</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>simpleServlet</servlet-name>
		<url-pattern>/hello</url-pattern>
	</servlet-mapping>

</web-app>

… and now we will use the WebServlet annotation to achieve the same configuration:

package net.javatutorial.tutorials;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name = "simpleServlet", urlPatterns = { "/hello" }, loadOnStartup = 1)
public class ServletWithAnnotations extends HttpServlet {

	private static final long serialVersionUID = -3462096228274971485L;

	@Override
	protected void doGet(HttpServletRequest reqest, HttpServletResponse response) 
			throws ServletException, IOException {
		response.getWriter().println("Hello World!");
	}

}

 

Servlet annotation with multiple url patterns

The urlPatterns attribute accepts an array as value, so you can set multiple URLs pointing to the same servlet:

@WebServlet(urlPatterns = {"/hello", "/wellcome"})
public class ServletWithAnnotations extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest reqest, HttpServletResponse response) 
			throws ServletException, IOException {
		// ... implementation goes here
	}

}

Given you are running your app on localhost and you deploy the app as servletannotation.war, you can access the servlet at http://localhost:8080/servletannotation/hello as well as http://localhost:8080/servletannotation/wellcome

You can find the source code to this example in our GitHub repo here

Share on FacebookTweet about this on TwitterShare on LinkedInShare on Google+Digg thisPin on PinterestShare on RedditShare on StumbleUponPrint this pageEmail this to someone

Leave a Reply