Servlet 3 Annotation Example Configuration

A servlet is a Java class that extends the javax.servlet.Servlet interface. To handle HTTP request you need to extend the javax.servlet.http.HttpServlet abstraction. Servlets interact with Web clients via a request/response paradigm implemented by the servlet container. In the following tutorial we will show you how to create a servlet 3 annotation example configuration.

Project structure

Note: since we are using servlet 3 annotation configuration we are not required to add a web.xml servlet descriptor.
|   +--main
|       +--java
|           +--com
|               +--memorynotfound
|                   |
|       |--resources
|       |--webapp

Maven Dependency

Every Servlet Container/Application Server has built in servlet support so you need to set the dependency on provided. So Maven does not include the library in the final built artifact.


Servlet 3 Annotation Configuration

The @WebServlet annotation is used to define a Servlet Component in a web application. This annotation is specified on a class and contains metadata about the Servlet being declared. The value or urlPattern attribute is required and maps the servlet to an url pattern. It is illegal to use both value and urlPattern attribute together.

package com.memorynotfound;

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

public class AnnotationServlet extends HttpServlet{

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter out = resp.getWriter();
        out.write("Example servlet 3 annotation example configuration");



URL: http://localhost:8080/servlet-annotation/example Servlet 3 Annotation Configuration Example



You may also like...