Building a Simple Web Form with Jetty and Servlets

In this article, we will learn how to create a small web application using Java, Jetty, Thymeleaf, and Servlets.

We will not use frameworks like Spring Boot because our goal is to understand how a web application works.

Before beginning, we need the following requirements:
  • Understanding how a web application works

  • Fundamentals of programming

  • Java 11 or higher

  • Knowledge of how Maven works

  • An IDE of your choice


In my case, I will use NetBeans.

In NetBeans, I will create a Maven Project → Java Application.

We need to edit the pom.xml file because it contains the following dependencies:

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.egga</groupId>
    <artifactId>JettyProject</artifactId>
    <version>version-0.1</version>
    <packaging>jar</packaging>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
        <exec.mainClass>com.egga.jettyproject.JettyProject</exec.mainClass>
    </properties>
    
<dependencies>
    <!-- Dependencia principal para el servidor Jetty -->
<dependency>
        <groupId>org.eclipse.jetty</groupId>
        <artifactId>jetty-server</artifactId>
        <version>11.0.23</version>
</dependency>

    <!-- Dependencia para la API Jakarta Servlet -->
<dependency>
        <groupId>jakarta.servlet</groupId>
        <artifactId>jakarta.servlet-api</artifactId>
        <version>6.1.0</version>
        <scope>provided</scope>
</dependency>
<dependency>
        <groupId>org.eclipse.jetty</groupId>
        <artifactId>jetty-webapp</artifactId>
        <version>11.0.23</version>
</dependency>

<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf</artifactId>
    <version>3.1.3.RELEASE</version>
</dependency>

</dependencies>
    
    
    
</project>

We need to create two pages: one page shows the form and the other shows the result.


simpleform.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Simple Form</title>
</head>
<body>

    <h1>Simple Form</h1>

    <form action="formexample" method="POST">
        <label for="name">Name:</label>
        <input type="text" id="name" name="name" required>
        <br><br>

        <label for="email">Email:</label>
        <input type="email" id="email" name="email" required>
        <br><br>

        <label for="message">Message:</label>
        <textarea id="message" name="message" rows="4" required></textarea>
        <br><br>

        <input type="submit" value="Submit">
    </form>

</body>
</html>

result.html:

<!DOCTYPE html>
<html>
<head>
    <title>Form Result</title>
</head>
<body>
    <h1>Your Form Data</h1>
    <p>Name: <span th:text="${name}"></span></p>
    <p>Email: <span th:text="${email}"></span></p>
    <p>Message: <span th:text="${message}"></span></p>
</body>
</html>

Configuring Thymeleaf in Your Application

In order to integrate Thymeleaf with Jetty, we need to create a class that configures the TemplateEngine. This class will initialize Thymeleaf and make it available for use in our servlets.

Here is how you can create the ThymeleafConfig class:


/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
 */
package com.egga.jettyproject.includes;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;

public class ThymeleafConfig {

    public TemplateEngine createTemplateEngine() {
        // Configurar Thymeleaf TemplateResolver
        ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
        templateResolver.setPrefix("/templates/");  // Carpeta de plantillas
        templateResolver.setSuffix(".html");        // Extensión de archivo
        templateResolver.setTemplateMode("HTML");
        // Crear TemplateEngine
        TemplateEngine templateEngine = new TemplateEngine();
        templateEngine.setTemplateResolver(templateResolver);

        return templateEngine;
    }
}


Now that the two pages are created, we will create the following servlet.

/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
 */
package com.egga.jettyproject.web;

import com.egga.jettyproject.includes.ThymeleafConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;


public class FormExample extends HttpServlet {
   private TemplateEngine templateEngine;

   

    @Override
    public void init() {
        // Inicialización del TemplateEngine usando ThymeleafConfig
        ThymeleafConfig thymeleafConfig = new ThymeleafConfig();
        templateEngine = thymeleafConfig.createTemplateEngine();
    }
        
    
    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
        Context context = new Context();
        String contenido = templateEngine.process("simpleform", context);
        response.setContentType("text/html");
        response.getWriter().write(contenido);
        
    
    
    
    
    }


    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        Context context = new Context();
     
       String name = request.getParameter("name");
       String email = request.getParameter("email");
       String message = request.getParameter("message");
                     
       context.setVariable("name",name ); 
       context.setVariable("email",email ); 
       context.setVariable("message",message);
       
       String contenido = templateEngine.process("result", context);   
       response.setContentType("text/html");
       response.getWriter().write(contenido);
        


    }

}








Afterwards, we will create the main class that runs the application.


package com.egga.jettyproject;

import com.egga.jettyproject.web.FormExample;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.webapp.WebAppContext;

/**
 *
 * @author esteban
 */
public class JettyProject {

    public static void main(String[] args) {
        
        
        try {
            Server server = new Server(8080);
            // Configurar el contexto web para JSP y recursos REST
            
            WebAppContext context = new WebAppContext();
            context.setContextPath("/jettyexample");
            context.setInitParameter("org.eclipse.jetty.servlet.Default.dirAllowed", "true");
            context.setResourceBase("src/main/resources/static"); // Ruta de los recursos estáticos

            ServletHolder formexample = new ServletHolder(new FormExample());
            context.addServlet(formexample, "/formexample");
            
            
            
            // Configurar el servidor para manejar JSP y recursos REST
            server.setHandler(context);
            
            // Iniciar el servidor
            server.start();
            server.join();
        } catch (Exception ex) {
            Logger.getLogger(JettyProject.class.getName()).log(Level.SEVERE, null, ex);
        }
     

    
    }
}




Finally, compile, run, and type the following address.

http://localhost:8080/jettyexample/formexample

Here is the complete project for download.

Comments

Popular posts from this blog

Replacing Tomcat: Configure Jetty with Spring Boot