Java Servlet 3.0 – @WebServlet

Servlet 3.0 introduced a new annotation @WebServlet that can be used to define a Servlet in a web application.

java-logo

Objective:

  • How to replace servlet xml configuration with @WebServlet annotation?

Environment & Tool:

  • Maven
  • Jetty 9.x (or any other server supporting servlet 3.0)

Library:

  • javaee-api-7.0-b82
<dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>7.0-b82</version>
            <scope>provided</scope>
        </dependency>

( 1 ) Servlet Class

  • /src/main/java/com/hmkcode/MyServlet.java

This is a simple servlet that responses to any GET request with “Hello @WebServlet” message.

package com.hmkcode;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyServlet extends HttpServlet {

	@Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("text/html;charset=UTF-8");
		try{
        	PrintWriter out = response.getWriter();
		out.println("<h2>@WebServlet(urlPatterns = {\"/servlet\"})</h2>");
        } catch (IOException ioe) {

        }
    }
}

( 2 ) Defining Servlet using XML

The traditional place to define a servlet is web.xml

  • /src/main/webapp/WEB-INF/web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
	      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	      xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 

http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"

	      version="3.0">

  <display-name>webservlet-annotation</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>

  <servlet>
  	<servlet-name>MyServlet</servlet-name>
  	<servlet-class>com.hmkcode.MyServlet</servlet-class>
  </servlet>

  <servlet-mapping>
  	<servlet-name>MyServlet</servlet-name>
  	<url-pattern>/servlet</url-pattern>
  </servlet-mapping>
</web-app>

( 3 ) Defining Servlet using @WebServlet

We can define a servlet using @WebServlet and optionally “in this sample” eliminate the whole web.xml.

  • /src/main/java/com/hmkcode/MyServlet.java
package com.hmkcode;
import ....

@WebServlet(urlPatterns = {"/servlet"})
public class MyServlet extends HttpServlet {

	@Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) {
        .......
    }
}

( 4 ) Project Structure

( 5 ) Run it!

  • This sample code is developed to run using the below Maven command
./webservlet-annotation>mvn jetty:run
  • Ope web browser and type: http://localhost:8080/

  • Click on MyAnnotatedServlet

Source Code @ GitHub