ZetCode

Java servlet check box

last modified November 30, 2026

In this tutorial, we create a web application that reads a value from an HTML check box. The form values are validated with a filter class. The views are created with FreeMarker templates. The application uses Jakarta Servlet 6.1 and runs with the Jetty Maven plugin.

Servlet is a Java class which responds to a particular type of network request - most commonly an HTTP request. Servlets are used to implement web applications. They run in a servlet container such as Tomcat or Jetty. In modern-day Java web development programmers use frameworks that are built on top of servlets.

A Java filter is an object that performs filtering tasks on either the request to a resource (a servlet or static content), or on the response from a resource, or both. It is used for tasks such as authentication, auditing, logging, data encryption, or data validation.

FreeMarker is a template engine for the Java programming language. Templates are written in the FreeMarker Template Language (FTL). Templates are used in web applications to create the UI.

Jetty is an open source Java servlet container. The Jetty Maven plugin runs the application in-process, so no separate server installation is needed.

Bootstrap is an HTML, CSS, and JS framework for developing responsive, mobile first projects on the web. It contains HTML and CSS design templates for typography, forms, buttons, navigation and other interface components, as well as optional JavaScript extension.

Application

The following web application has a simple web form that consists of a check box and an input text. The values are send to the web application's controller, which is a Java servlet. Before the request reaches the controller, the values are validated in a Java filter. In the end, the values are shown in a HTML file, which is built with FreeMarker template. FreeMarker joins HTML with data.

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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
https://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <groupId>com.zetcode</groupId>
    <artifactId>FormCheckBox</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>FormCheckBox</name>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.release>25</maven.compiler.release>
    </properties>

    <dependencies>
        <dependency>
            <groupId>jakarta.servlet</groupId>
            <artifactId>jakarta.servlet-api</artifactId>
            <version>6.1.0</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.35</version>
        </dependency>

    </dependencies>

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

            <plugin>
                <groupId>org.eclipse.jetty.ee11</groupId>
                <artifactId>jetty-ee11-maven-plugin</artifactId>
                <version>12.1.15</version>
                <configuration>
                    <webApp>
                        <contextPath>/FormCheckBox</contextPath>
                    </webApp>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

The jakarta.servlet-api dependency contains the Jakarta Servlet API. The freemarker artifact is the FreeMarker template engine. The maven-war-plugin packages the application as a WAR, and jetty-ee11-maven-plugin runs it with mvn jetty:run.

$ tree
.
├── pom.xml
└── src
    └── main
        ├── java
        │   └── com
        │       └── zetcode
        │           ├── filter
        │           │   └── FormFilter.java
        │           └── web
        │               └── MyController.java
        ├── resources
        │   └── templates
        │       ├── show.ftl
        │       └── unknown.ftl
        └── webapp
            └── index.html

With the tree command we show the project directory structure. The templates are classpath resources, and the servlet and filter are registered with annotations, so the project has no web.xml.

index.html
<!DOCTYPE html>
<html>
    <head>
        <title>Check box</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css"
              rel="stylesheet">
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <div class="container mt-3">
            <form action="MyController">

                <input type="hidden" name="action" value="show">

                <div class="mb-3">
                    <label for="name" class="form-label">Name:</label>
                    <input type="text" id="name" name="name"
                           class="form-control">
                </div>

                <div class="form-check mb-3">
                    <input type="checkbox" id="adult" name="adult"
                           class="form-check-input">
                    <label for="adult" class="form-check-label">Adult</label>
                </div>

                <button type="submit" class="btn btn-primary">Submit</button>

            </form>
        </div>
    </body>
</html>

The index.html file is the home page of our application. It contains an HTML form with a text input and a check box. The look of the page is created with the Bootstrap library.

<input type="hidden" name="action" value="show">

This hidden input tag defines an action parameter, which is used in the controller servlet.

com/zetcode/filter/FormFilter.java
package com.zetcode.filter;

import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.annotation.WebFilter;

import java.io.IOException;
import java.util.Map;

@WebFilter(filterName = "FormFilter", servletNames = {"MyController"})
public class FormFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain)
            throws IOException, ServletException {

        Map<String, String[]> params = request.getParameterMap();

        params.forEach((key, values) -> {

            if (values.length > 0 && !values[0].isBlank()) {
                request.setAttribute(key, values[0]);
            }
        });

        chain.doFilter(request, response);
    }
}

The FormFilter processes the request before reaching the MyController servlet. It retrieves all parameters from the request and validates them; we need to ensure that the values are not null or empty.

Map<String, String[]> params = request.getParameterMap();

We get all the parameters from the request with the getParameterMap method.

params.forEach((key, values) -> {

    if (values.length > 0 && !values[0].isBlank()) {
        request.setAttribute(key, values[0]);
    }
});

We turn request parameters into request attributes. An attribute is set only when the parameter has a non-blank value. These attributes are available to the FreeMarker template engine.

chain.doFilter(request, response);

The request continues to the mapped servlet.

com/zetcode/web/MyController.java
package com.zetcode.web;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet(name = "MyController", urlPatterns = {"/MyController"})
public class MyController extends HttpServlet {

    private static final String SHOW_ACTION = "show";
    private Configuration cfg;

    @Override
    public void init() {

        cfg = new Configuration(Configuration.VERSION_2_3_35);
        cfg.setClassLoaderForTemplateLoading(
                MyController.class.getClassLoader(), "templates");
        cfg.setDefaultEncoding("UTF-8");
        cfg.setLogTemplateExceptions(false);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String action = request.getParameter("action");
        String view = SHOW_ACTION.equals(action) ? "show.ftl" : "unknown.ftl";

        Map<String, Object> model = new HashMap<>();
        model.put("name", request.getAttribute("name"));
        model.put("adult", request.getAttribute("adult"));

        response.setContentType("text/html;charset=UTF-8");

        try {
            Template template = cfg.getTemplate(view);
            template.process(model, response.getWriter());
        } catch (TemplateException ex) {
            throw new ServletException("Cannot render template " + view, ex);
        }
    }
}

The MyController servlet will handle a request after it was processed by a filter.

@WebServlet(name = "MyController", urlPatterns = {"/MyController"})

The @WebServlet annotation maps the request with MyController URL pattern to the MyController servlet.

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

The request is a GET request, so we serve it in the doGet method.

response.setContentType("text/html;charset=UTF-8");

With the setContentType method, we set the content type (HTML) and charset.

cfg = new Configuration(Configuration.VERSION_2_3_35);
cfg.setClassLoaderForTemplateLoading(
        MyController.class.getClassLoader(), "templates");
cfg.setDefaultEncoding("UTF-8");

The FreeMarker Configuration is created once in the servlet's init method. It loads the templates from the classpath under the templates package and uses UTF-8 for both templates and output.

Template template = cfg.getTemplate(view);
template.process(model, response.getWriter());

The controller selects the template, processes it with the request attributes as the data model, and writes the generated HTML directly to the response.

templates/show.ftl
<!DOCTYPE html>
<html>
    <head>
        <title>Show page</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
<body>
    
    <#if adult??>
        <p>${(name!"Guest")?html} is adult</p>
    <#else>
        <p>${(name!"Guest")?html} is minor</p>
    </#if>
        
</body>
</html>

This is the show.ftl template. Two values are passed to the template: adult and name. FreeMarker uses the ${} syntax to get a value from the data model.

<#if adult??>

With the #if directive, we check if the adult attribute is set. The ?? tells if the left hand operand's value is missing.

<p>${(name!"Guest")?html} is adult</p>

The ! is used to give a default value when a value is missing. (Remember that we did not set attributes for parameters that were empty or null.) If the name variable is set, it is displayed; otherwise, "Guest" is shown. The ?html built-in escapes HTML characters, so a value entered by the user cannot inject markup into the page.

templates/unknown.ftl
<!DOCTYPE html>
<html>
    <head>
        <title>Unknow action</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
<body>

    <p>Unknown action</p>
        
</body>
</html>

This is the unknown.ftl template file. It is rendered when the action parameter is missing or has an unknown value.

Running the application

Start the application with the Jetty plugin and open http://localhost:8080/FormCheckBox/ in a browser.

$ mvn jetty:run

The following request submits the form with the check box selected. The response contains the rendered FreeMarker view.

$ curl 'localhost:8080/FormCheckBox/MyController?action=show&name=Jane&adult=on'
...
<p>Jane is adult</p>

Without the adult parameter the same request produces Jane is minor. A missing name falls back to Guest, and user input is HTML-escaped by the ?html built-in.

$ curl 'localhost:8080/FormCheckBox/MyController?action=show&name=Jane'
...
<p>Jane is minor</p>

$ curl 'localhost:8080/FormCheckBox/MyController?action=bogus'
...
<p>Unknown action</p>

Source

Jakarta Servlet specification and the FreeMarker documentation.

In this tutorial, we sent data from an HTML form to a Jakarta Servlet. The form contained a text input and a check box. The request parameters were validated in a filter, turned into request attributes, and rendered with a FreeMarker template.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Java tutorials.