ZetCode

Java Servlet Weld

last modified November 30, 2026

Java Servlet Weld tutorial shows how to use dependency injection in a Java Servlet with Weld. The application uses Jakarta CDI 4.1 and runs on Jetty 12.1 with Jakarta Servlet 6.1.

Dependency injection

Dependency injection (DI) is a technique where one object supplies the dependencies of another object. In case of Java applications, it is a specific library that injects dependencies into the classes. The major benefit of DI is loose coupling and ease of use. DI makes classes more cohesive because they have fewer responsibilities.

Jakarta EE standardized dependency injection by introducing the Context and Dependency Injection (CDI) specification. It is the standard for dependency injection and contextual lifecycle management.

@Inject annotation

The @Inject annotation is used to inject a dependency into a Java class. A class that should be managed by the container is decorated with a bean-defining annotation such as @ApplicationScoped.

Weld

Weld is the reference implementation of CDI for the Jakarta EE platform. Weld is integrated into many application servers such as WildFly and GlassFish. It can also be used in plain servlet containers such as Tomcat and Jetty.

Java Servlet Weld example

In the following web application, we create a servlet that returns a list of city objects in an HTML file. In the application, we use dependency injection with the help of the Weld library.

$ tree
.
├── pom.xml
└── src
    └── main
        ├── java
        │   └── com
        │       └── zetcode
        │           ├── bean
        │           │   └── City.java
        │           ├── dao
        │           │   ├── CityDao.java
        │           │   └── ICityDao.java
        │           ├── service
        │           │   ├── CityService.java
        │           │   └── ICityService.java
        │           └── web
        │               └── GetCities.java
        └── webapp
            ├── index.html
            ├── listCities.jsp
            └── WEB-INF
                ├── beans.xml
                └── web.xml

This is the project structure.

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>JavaServletWeld</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>JavaServletWeld</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>jakarta.servlet.jsp.jstl</groupId>
            <artifactId>jakarta.servlet.jsp.jstl-api</artifactId>
            <version>3.0.2</version>
        </dependency>

        <dependency>
            <groupId>org.glassfish.web</groupId>
            <artifactId>jakarta.servlet.jsp.jstl</artifactId>
            <version>3.0.1</version>
        </dependency>

        <dependency>
            <groupId>org.jboss.weld.servlet</groupId>
            <artifactId>weld-servlet-core</artifactId>
            <version>7.0.0.Final</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>/JavaServletWeld</contextPath>
                    </webApp>
                </configuration>
            </plugin>

        </plugins>
    </build>

</project>

This is the Maven POM file. The jakarta.servlet-api artifact provides the Servlet API. The weld-servlet-core dependency enables Weld to run in a servlet container. The Jakarta JSTL API and implementation add the tags used by the JSP page. The maven-war-plugin packages the application as a WAR, and the jetty-ee11-maven-plugin runs it with mvn jetty:run.

WEB-INF/web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="6.1" xmlns="https://jakarta.ee/xml/ns/jakartaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee
         https://jakarta.ee/xml/ns/jakartaee/web-app_6_1.xsd">

    <listener>
        <listener-class>
            org.jboss.weld.environment.servlet.Listener
        </listener-class>
    </listener>

</web-app>

The web.xml file registers Weld's servlet listener. The listener starts the CDI container when the application starts and stops it when the application shuts down.

com/zetcode/bean/City.java
package com.zetcode.bean;

import java.util.Objects;

public class City {

    private Long id;
    private String name;
    private int population;

    public City(Long id, String name, int population) {
        this.id = id;
        this.name = name;
        this.population = population;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getPopulation() {
        return population;
    }

    public void setPopulation(int population) {
        this.population = population;
    }

    @Override
    public int hashCode() {
        int hash = 3;
        hash = 97 * hash + Objects.hashCode(this.id);
        hash = 97 * hash + Objects.hashCode(this.name);
        hash = 97 * hash + this.population;
        return hash;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final City other = (City) obj;
        if (this.population != other.population) {
            return false;
        }
        if (!Objects.equals(this.name, other.name)) {
            return false;
        }
        return Objects.equals(this.id, other.id);
    }
}

The City bean holds data of a city object. It has three attributes: id, name, and population.

WEB-INF/beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="https://jakarta.ee/xml/ns/jakartaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee
       https://jakarta.ee/xml/ns/jakartaee/beans_4_1.xsd"
       version="4.1" bean-discovery-mode="annotated"/>

The beans.xml file is the CDI deployment descriptor. The bean-discovery-mode="annotated" setting tells Weld to manage only classes that have a bean-defining annotation, such as @ApplicationScoped. The file is required to enable CDI in the web application.

com/zetcode/service/ICityService.java
package com.zetcode.service;

import com.zetcode.bean.City;
import java.util.List;

public interface ICityService {
    
    public List<City> getCities();
}

ICityService contains the getCities contract method.

com/zetcode/service/CityService.java
package com.zetcode.service;

import com.zetcode.bean.City;
import com.zetcode.dao.ICityDao;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.util.List;

@ApplicationScoped
public class CityService implements ICityService {
    
    @Inject
    private ICityDao cityDao;
    
    @Override
    public List<City> getCities() {

        return cityDao.findAll();
    }
}

CityService contains the implementation of the ICityService interface. The service class calls the method of the DAO object, which is an intermediary layer to the database.

@ApplicationScoped
public class CityService implements ICityService {

@ApplicationScoped is a bean-defining annotation. It tells Weld to create one CityService instance for the whole application and to manage its lifecycle.

@Inject
private ICityDao cityDao;

With the @Inject annotation, we inject the CityDao into the cityDao attribute.

com/zetcode/dao/ICityDao.java
package com.zetcode.dao;

import com.zetcode.bean.City;
import java.util.List;

public interface ICityDao {
    
    public List<City> findAll();
}

Here we have the DAO findAll contract method.

com/zetcode/dao/CityDao.java
package com.zetcode.dao;

import com.zetcode.bean.City;
import jakarta.enterprise.context.ApplicationScoped;
import java.util.ArrayList;
import java.util.List;

@ApplicationScoped
public class CityDao implements ICityDao {

    @Override
    public List<City> findAll() {
        
        List<City> cities = new ArrayList<>();
        
        cities.add(new City(1L, "Bratislava", 432000));
        cities.add(new City(2L, "Budapest", 1759000));
        cities.add(new City(3L, "Prague", 1280000));
        cities.add(new City(4L, "Warsaw", 1748000));
        cities.add(new City(5L, "Los Angeles", 3971000));
        cities.add(new City(6L, "New York", 8550000));
        cities.add(new City(7L, "Edinburgh", 464000));
        cities.add(new City(8L, "Berlin", 3671000));
        
        return cities;        
    }
}

CityDao contains the implementations of the findAll DAO method. For simplicity reasons, we do not connect to the database but simply return a list of City objects.

@ApplicationScoped
public class CityDao implements ICityDao {

CityDao is also an application-scoped CDI bean, so Weld can inject it into CityService.

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

import com.zetcode.bean.City;
import com.zetcode.service.ICityService;
import jakarta.enterprise.inject.spi.CDI;
import jakarta.servlet.RequestDispatcher;
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.List;

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

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

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

        ICityService cityService = CDI.current()
                .select(ICityService.class).get();

        List<City> cities = cityService.getCities();
        request.setAttribute("cities", cities);

        RequestDispatcher dispatcher = request.getRequestDispatcher("listCities.jsp");
        dispatcher.forward(request, response);
    }
}

The GetCities servlet calls the city service's getCities method and responds with a HTML pages which contains all cities in an HTML table.

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

The Java class is decorated with the @WebServlet annotation. It is mapped to the GetCities URL pattern.

ICityService cityService = CDI.current()
        .select(ICityService.class).get();

The servlet obtains the ICityService bean from the CDI container with a programmatic lookup. Weld's servlet integration does not support injection into servlet instances on Jetty 12, so this is the portable way to reach a CDI bean from a servlet. Inside the CDI beans themselves, @Inject works normally: CityService receives its CityDao dependency from Weld.

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

The servlet outputs HTML and sets the character encoding to UTF-8 before it obtains the response writer.

List<City> cities = cityService.getCities();
request.setAttribute("cities", cities);

With CityService's getCities, we retrieve all cities.

request.setAttribute("cities", cities);

We set the list into the request.

RequestDispatcher dispatcher = request.getRequestDispatcher("listCities.jsp");
dispatcher.forward(request, response);

Using the RequestDispatcher, we send the processing to the listCities.jsp page. It is a template file which joins data with HTML and produces the final output to the client.

listCities.jsp
<%@page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib uri="jakarta.tags.core" prefix="c" %>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Cities</title>
    </head>
    <body>
        <h2>Cities</h2>
        
        <table>
            <thead>
                <tr>
                    <th>Id</th>
                    <th>Name</th>
                    <th>Population</th>
                </tr>
            </thead>
            
            <tbody>
                <c:forEach items="${cities}" var="city">
                <tr>
                    <td><c:out value="${city.id}"/></td>
                    <td><c:out value="${city.name}"/></td>
                    <td><c:out value="${city.population}"/></td>
                </tr>
                </c:forEach>   
            </tbody>
        </table>
    </body>
</html>

The listCities.jsp uses a c:forEach tag to generate an HTML table from the supplied data.

index.html
<!DOCTYPE html>
<html>
    <head>
        <title>Home page</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <a href="GetCities">GetCities</a>
    </body>
</html>

This is the home page. It contains a link to call the servlet.

Running the application

Start the application with the Jetty plugin and open http://localhost:8080/JavaServletWeld/. The home page links to the servlet.

$ mvn jetty:run

The servlet looks up the ICityService bean, which Weld has already instantiated and populated with the CityDao dependency. The response is the HTML table rendered by listCities.jsp.

$ curl localhost:8080/JavaServletWeld/GetCities
...
<tr>
    <td>1</td>
    <td>Bratislava</td>
    <td>432000</td>
</tr>
<tr>
    <td>2</td>
    <td>Budapest</td>
    <td>1759000</td>
</tr>
...

Source

Weld documentation and the Jakarta CDI specification.

In this tutorial we included Weld in a Jakarta Servlet web application and used CDI to manage the service and DAO dependencies.

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.