O'Reilly logo

Java EE 7 Essentials by Arun Gupta

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 2. Servlets

Servlets are defined as JSR 340, and the complete specification can be downloaded.

A servlet is a web component hosted in a servlet container and generates dynamic content. The web clients interact with a servlet using a request/response pattern. The servlet container is responsible for the life cycle of the servlet, receives requests and sends responses, and performs any other encoding/decoding required as part of that.

WebServlet

A servlet is defined using the @WebServlet annotation on a POJO, and must extend the javax.servlet.http.HttpServlet class.

Here is a sample servlet definition:

@WebServlet("/account")
public class AccountServlet extends javax.servlet.http.HttpServlet {
  //. . .
}

The fully qualified class name is the default servlet name, and may be overridden using the name attribute of the annotation. The servlet may be deployed at multiple URLs:

@WebServlet(urlPatterns={"/account", "/accountServlet"})
public class AccountServlet extends javax.servlet.http.HttpServlet {
  //. . .
}

The @WebInitParam can be used to specify an initialization parameter:

@WebServlet(urlPatterns="/account",
            initParams={
               @WebInitParam(name="type", value="checking")
                       }
           )
public class AccountServlet extends javax.servlet.http.HttpServlet {
  //. . .
}

The HttpServlet interface has one doXXX method to handle each of HTTP GET, POST, PUT, DELETE, HEAD, OPTIONS, and TRACE requests. Typically the developer is concerned with overriding the doGet and doPost methods. The following code shows a ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required