Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

The first servlet

A servlet is a Java class that receives an HTTP request and builds a response. It is the lowest web level in Jakarta EE: both Jakarta REST and Faces are built on servlets. Today you rarely write a servlet for every page, but you need to understand them — this is how you see the way a request reaches your code at all.

Creating a servlet

Create the file src/main/java/com/example/blog/HelloServlet.java:

// src/main/java/com/example/blog/HelloServlet.java
package com.example.blog;
 
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
 
@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
 
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        response.setContentType("text/plain; charset=UTF-8");
        response.getWriter().println("Hello from the blog!");
    }
}

The class extends HttpServlet, and the @WebServlet("/hello") annotation binds it to the /hello address inside the application. The doGet method is called for every GET request: it sets the response type and writes text through getWriter().

Trying it out

If the server was started with liberty:dev, it picks up the new class by itself. Open the address in a browser or call it with curl:

curl -i http://localhost:8080/blog/hello
HTTP/1.1 200 OK
Content-Type: text/plain; charset=UTF-8
Content-Length: 22

Hello from the blog!

The full address has three parts: the server localhost:8080, the application root /blog from server.xml and the servlet path /hello.

HTTP methods

HttpServlet has a handler method for each HTTP method:

HTTP methodServlet method
GETdoGet
POSTdoPost
PUTdoPut
DELETEdoDelete

Override only the ones you need. The server answers the rest by itself.

URL patterns

PatternMatching addresses
/helloOnly /hello
/posts/*/posts, /posts/1, /posts/1/edit
*.txtAny address ending in .txt

Several addresses go in curly braces: @WebServlet({"/hello", "/hi"}).

Life cycle

The server creates one servlet object for the whole application and calls it from different threads — one thread per request. So you must not keep data of a particular request in servlet fields: two visitors at the same time would overwrite each other's values. Keep everything that belongs to a request in local variables of the method.

Common mistake

Sending a request with a method the servlet does not handle. HelloServlet has only doGet, so a POST request gets 405 Method Not Allowed:

curl -i -X POST http://localhost:8080/blog/hello
HTTP/1.1 405 Method Not Allowed

If a form or a client sends POST, add a doPost method to the servlet.

Thanks for reading!

Donate to the site — we work hard for you.