Jakarta EE Basics
Jakarta EE is the official set of standard APIs for enterprise Java: web endpoints, dependency injection, database access, validation, transactions and more. You write your code against these standard interfaces, package it as a WAR file, and an application server such as GlassFish, WildFly, Payara or Open Liberty provides the implementation. Because the APIs are standards, the same application can move between servers with little or no change.
This lesson uses Jakarta EE 11 on Eclipse GlassFish 8 with Java 21 or newer. You already used two Jakarta EE APIs: the Java servlet API and Jakarta Persistence (JPA).
What Is Jakarta EE?
Jakarta EE is the continuation of Java EE. In 2017 Oracle moved Java EE to the Eclipse Foundation, and from Jakarta EE 9 onward every package was renamed from javax.* to jakarta.*.
// Java EE 8 and older
import javax.servlet.http.HttpServlet;
import javax.persistence.Entity;
// Jakarta EE 9 and newer (including Jakarta EE 11)
import jakarta.servlet.http.HttpServlet;
import jakarta.persistence.Entity;
How it works:
- The APIs are the same ideas with a new package name. Old tutorials that use
javaxneed this rename before they compile against Jakarta EE. - Spring Boot 4 also builds on Jakarta EE 11 APIs (Servlet 6.1, Persistence 3.2, Validation 3.1), which is why Spring code imports
jakarta.persistence.Entitytoo.
Jakarta EE Profiles
A server can implement the whole platform or a smaller profile.
| Profile | Contains | Good for |
|---|---|---|
| Core Profile | CDI Lite, Jakarta REST, JSON-P, JSON-B, Annotations, Interceptors | Small REST microservices |
| Web Profile | Core + Servlet, Pages (JSP), Faces, Persistence, Validation, Transactions, Security, Data | Most web applications |
| Platform | Web + Messaging, Batch, Mail, Connectors and more | Large enterprise systems |
Key Jakarta EE 11 Specifications
| Specification | Version | What it gives you |
|---|---|---|
| Jakarta REST (JAX-RS) | 4.0 | @Path, @GET, @POST REST endpoints |
| Contexts and Dependency Injection (CDI) | 4.1 | @Inject, scopes such as @ApplicationScoped |
| JSON Binding (JSON-B) | 3.0 | Java objects to and from JSON |
| Persistence (JPA) | 3.2 | @Entity, EntityManager |
| Bean Validation | 3.1 | @NotBlank, @Min, @Valid |
| Transactions | 2.0 | @Transactional |
| Servlet | 6.1 | HttpServlet, filters, sessions |
| Data | 1.0 | Repository interfaces (new in EE 11) |
| Concurrency | 3.1 | Managed executors, virtual thread support |
Set Up a Jakarta EE Project With Maven
A Jakarta EE application is a normal Maven project with war packaging and one API dependency.
<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.gocourse</groupId>
<artifactId>courses</artifactId>
<version>1.0.0</version>
<packaging>war</packaging>
<properties>
<maven.compiler.release>21</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- every Jakarta EE 11 API; the server supplies the implementation -->
<dependency>
<groupId>jakarta.platform</groupId>
<artifactId>jakarta.jakartaee-api</artifactId>
<version>11.0.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<finalName>courses</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.4.0</version>
</plugin>
</plugins>
</build>
</project>
courses/
├── pom.xml
└── src/main/
├── java/com/gocourse/courses/...
└── resources/META-INF/persistence.xml (added later for JPA)
How it works:
providedscope means "compile against it but do not put it in the WAR". The server already contains Jersey, Weld, EclipseLink, Hibernate Validator and the other implementations.- The resulting
target/courses.warstays tiny, often a few kilobytes, as described in Build WAR file in Java. - To target only the Web Profile, use the artifact
jakarta.jakartaee-web-apiinstead.
Your First Jakarta REST Endpoint
Jakarta REST needs two classes: an Application subclass that sets the base path, and a resource class with the endpoints.
package com.gocourse.courses;
import jakarta.ws.rs.ApplicationPath;
import jakarta.ws.rs.core.Application;
@ApplicationPath("/api")
public class RestApplication extends Application {
// empty: the server scans the WAR for @Path classes
}
package com.gocourse.courses;
import jakarta.ws.rs.DefaultValue;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.core.MediaType;
@Path("hello")
public class HelloResource {
@GET
@Produces(MediaType.TEXT_PLAIN)
public String hello(@QueryParam("name") @DefaultValue("guest") String name) {
return "Hello, " + name + "! Served by Jakarta EE.";
}
}
Build, start GlassFish and deploy:
mvn -q clean package
asadmin start-domain
asadmin deploy target/courses.war
curl -s -w "\n" http://localhost:8080/courses/api/hello
curl -s -w "\n" "http://localhost:8080/courses/api/hello?name=Asha"
Waiting for domain1 to start ...
Successfully started the domain : domain1
Command start-domain executed successfully.
Application deployed with name courses.
Command deploy executed successfully.
Hello, guest! Served by Jakarta EE.
Hello, Asha! Served by Jakarta EE.
How it works:
- The URL has three parts:
/coursesis the context root (the WAR name),/apicomes from@ApplicationPath, and/hellofrom@Path. @QueryParamreads?name=Asha, and@DefaultValuesuppliesguestwhen it is missing.asadminis GlassFish's command-line tool in itsbinfolder. Redeploy after changes withasadmin redeploy --name courses target/courses.war.
Note: Unlike Spring Boot, the server runs separately and your WAR is deployed into it. One GlassFish instance can host many applications, each with its own context root.
Dependency Injection With CDI
CDI creates objects (beans), manages how long they live and injects them where needed. A class with a scope annotation becomes a bean automatically.
| Scope | One instance per | Typical use |
|---|---|---|
@ApplicationScoped | Application | Services, caches, repositories |
@RequestScoped | HTTP request | Per-request data |
@SessionScoped | User session | Shopping cart, wizard state |
@Dependent | Injection point (default) | Small helpers |
package com.gocourse.courses;
import jakarta.enterprise.context.ApplicationScoped;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentSkipListMap;
@ApplicationScoped
public class CourseCatalog {
private final Map<String, Course> courses = new ConcurrentSkipListMap<>();
public CourseCatalog() {
add(new Course("java", "Java Programming", "backend", 4999, 30));
add(new Course("go", "Go Language", "backend", 2999, 20));
add(new Course("html", "HTML and CSS", "web", 1999, 40));
}
public List<Course> findAll() {
return List.copyOf(courses.values());
}
public Optional<Course> find(String code) {
return Optional.ofNullable(courses.get(code));
}
public boolean add(Course course) {
return courses.putIfAbsent(course.code(), course) == null;
}
}
package com.gocourse.courses;
public record Course(String code, String title, String category, int feeInr, int seats) {}
package com.gocourse.courses;
import jakarta.inject.Inject;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import java.util.List;
@Path("catalog")
@Produces(MediaType.APPLICATION_JSON)
public class CatalogResource {
@Inject
CourseCatalog catalog; // CDI supplies the single application-wide instance
@GET
public List<Course> all() {
return catalog.findAll();
}
}
curl -s -w "\n" http://localhost:8080/courses/api/catalog
[{"category":"backend","code":"go","feeInr":2999,"seats":20,"title":"Go Language"},{"category":"web","code":"html","feeInr":1999,"seats":40,"title":"HTML and CSS"},{"category":"backend","code":"java","feeInr":4999,"seats":30,"title":"Java Programming"}]
How it works:
@ApplicationScopedmakes one sharedCourseCatalog.@Injecton the field asks CDI to fill it in; you never callnew CourseCatalog().- JSON-B converts the list to JSON. By default it writes properties in alphabetical order, which is why
categorycomes beforecode. Add@JsonbPropertyOrder({"code", "title", "category", "feeInr", "seats"})to the record to choose your own order. - The idea is the same as Spring's dependency injection from Spring Framework basics; only the annotation names differ.
Path Parameters, POST and Status Codes
Resource methods can return a Response to control the status code and headers. Built-in exceptions such as NotFoundException map to standard status codes.
package com.gocourse.courses;
import jakarta.inject.Inject;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.NotFoundException;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.UriInfo;
import java.net.URI;
@Path("catalog/items")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class CatalogItemResource {
@Inject
CourseCatalog catalog;
@GET
@Path("{code}")
public Course get(@PathParam("code") String code) {
return catalog.find(code)
.orElseThrow(() -> new NotFoundException("Course " + code + " not found"));
}
@POST
public Response create(Course course, @Context UriInfo uriInfo) {
if (!catalog.add(course)) {
return Response.status(Response.Status.CONFLICT).build();
}
URI location = uriInfo.getAbsolutePathBuilder().path(course.code()).build();
return Response.created(location).entity(course).build();
}
}
BASE=http://localhost:8080/courses/api/catalog/items
curl -s -w "\n" $BASE/java
curl -s -o /dev/null -w "%{http_code}\n" $BASE/rust
curl -s -D - -o /dev/null -X POST -H "Content-Type: application/json" \
-d '{"code":"docker","title":"Docker Basics","category":"devops","feeInr":2499,"seats":35}' $BASE | grep -E "HTTP|Location"
curl -s -o /dev/null -w "%{http_code}\n" -X POST -H "Content-Type: application/json" \
-d '{"code":"java","title":"Java Again","category":"backend","feeInr":1,"seats":1}' $BASE
{"category":"backend","code":"java","feeInr":4999,"seats":30,"title":"Java Programming"}
404
HTTP/1.1 201 Created
Location: http://localhost:8080/courses/api/catalog/items/docker
409
How it works:
@Path("{code}")on a method adds a template to the class path, and@PathParam("code")reads it.- The POST body is converted from JSON into the
Courserecord by JSON-B because of@Consumes(APPLICATION_JSON). @Context UriInfogives the current request URL, so theLocationheader points to the new course.NotFoundExceptionbecomes 404;Response.status(CONFLICT)returns 409 for a duplicate code.
Validate Input With Bean Validation
Put constraints on the data class and add @Valid to the parameter. Jakarta REST rejects invalid input with 400 Bad Request before your method runs.
package com.gocourse.courses;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Pattern;
import jakarta.validation.constraints.PositiveOrZero;
public record Course(
@NotBlank @Pattern(regexp = "[a-z0-9-]{2,20}") String code,
@NotBlank String title,
@NotBlank String category,
@PositiveOrZero int feeInr,
@Min(1) int seats) {}
// in CatalogItemResource
@POST
public Response create(@Valid Course course, @Context UriInfo uriInfo) {
// unchanged body
}
curl -s -o /dev/null -w "%{http_code}\n" -X POST -H "Content-Type: application/json" \
-d '{"code":"Bad Code","title":"","category":"web","feeInr":-5,"seats":0}' \
http://localhost:8080/courses/api/catalog/items
400
How it works:
- The server's Bean Validation implementation (Hibernate Validator in GlassFish) checks every constraint on the record components.
- Each server formats the 400 body differently. To return your own JSON error, write an
ExceptionMapper<ConstraintViolationException>, as the real-world example does for missing courses.
Store Data With Jakarta Persistence and Transactions
Jakarta Persistence (JPA) maps classes to tables. In Jakarta EE the server manages the EntityManager and the transactions for you.
<!-- src/main/resources/META-INF/persistence.xml -->
<persistence xmlns="https://jakarta.ee/xml/ns/persistence" version="3.2">
<persistence-unit name="coursesPU">
<!-- default database every Jakarta EE server provides -->
<jta-data-source>java:comp/DefaultDataSource</jta-data-source>
<properties>
<property name="jakarta.persistence.schema-generation.database.action" value="drop-and-create"/>
</properties>
</persistence-unit>
</persistence>
package com.gocourse.courses.data;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
@Entity
@Table(name = "course")
public class CourseEntity {
@Id
private String code;
private String title;
private String category;
private int feeInr;
private int seats;
protected CourseEntity() {} // required by JPA
public CourseEntity(String code, String title, String category, int feeInr, int seats) {
this.code = code;
this.title = title;
this.category = category;
this.feeInr = feeInr;
this.seats = seats;
}
public String getCode() { return code; }
public String getTitle() { return title; }
public String getCategory() { return category; }
public int getFeeInr() { return feeInr; }
public int getSeats() { return seats; }
}
package com.gocourse.courses.data;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import jakarta.transaction.Transactional;
import java.util.List;
import java.util.Optional;
@ApplicationScoped
public class CourseRepository {
@PersistenceContext(unitName = "coursesPU")
EntityManager em;
public List<CourseEntity> findAll() {
return em.createQuery("select c from CourseEntity c order by c.code", CourseEntity.class)
.getResultList();
}
public Optional<CourseEntity> find(String code) {
return Optional.ofNullable(em.find(CourseEntity.class, code));
}
@Transactional
public void save(CourseEntity course) {
em.persist(course);
}
}
How it works:
java:comp/DefaultDataSourceis a standard JNDI name, so the samepersistence.xmlworks on every Jakarta EE server. For production you point it at a real database configured in the server.@PersistenceContextinjects anEntityManagermanaged by the server. You never create or close it yourself.@Transactionalstarts a transaction beforesaveand commits after it, or rolls back if a runtime exception escapes.
Note: If deployment fails because the default database is not running, start it with
asadmin start-database.
Jakarta EE vs Spring Boot
Both use the same Jakarta APIs underneath, but they package and wire applications differently.
| Task | Jakarta EE | Spring Boot |
|---|---|---|
| REST endpoint | @Path, @GET | @RestController, @GetMapping |
| Path variable | @PathParam | @PathVariable |
| Dependency injection | @Inject, @ApplicationScoped | Constructor injection, @Service |
| JSON library | JSON-B (alphabetical by default) | Jackson (declaration order) |
| Run model | WAR deployed into a server | Executable JAR with embedded server |
| Configuration | Server admin console, asadmin | application.properties |
The same endpoint in Spring Boot looks like this, as covered in the Spring Boot REST API lesson:
@GetMapping("/api/catalog/items/{code}")
public Course get(@PathVariable String code) {
return catalog.find(code).orElseThrow(() -> new CourseNotFoundException(code));
}
How it works:
- The code shape is almost identical. Most of the difference is in setup and deployment, not in your business logic.
- Teams often choose Jakarta EE when they already run application servers, and Spring Boot when they want self-contained JARs.
Real-World Example: Jakarta EE Course API With JPA
This version stores courses in the database, seeds them at startup, validates new courses and returns JSON errors for missing courses.
package com.gocourse.courses.data;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.event.Observes;
import jakarta.enterprise.event.Startup;
import jakarta.inject.Inject;
@ApplicationScoped
public class DataSeeder {
@Inject
CourseRepository repository;
// CDI fires the Startup event once the application is ready
void seed(@Observes Startup startup) {
repository.save(new CourseEntity("java", "Java Programming", "backend", 4999, 30));
repository.save(new CourseEntity("go", "Go Language", "backend", 2999, 20));
repository.save(new CourseEntity("html", "HTML and CSS", "web", 1999, 40));
}
}
package com.gocourse.courses.api;
import jakarta.json.bind.annotation.JsonbPropertyOrder;
@JsonbPropertyOrder({"status", "message"})
public record ApiError(int status, String message) {}
package com.gocourse.courses.api;
import jakarta.ws.rs.NotFoundException;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.ext.ExceptionMapper;
import jakarta.ws.rs.ext.Provider;
@Provider
public class NotFoundMapper implements ExceptionMapper<NotFoundException> {
@Override
public Response toResponse(NotFoundException ex) {
return Response.status(Response.Status.NOT_FOUND)
.type(MediaType.APPLICATION_JSON)
.entity(new ApiError(404, ex.getMessage()))
.build();
}
}
package com.gocourse.courses.api;
import com.gocourse.courses.Course;
import com.gocourse.courses.data.CourseEntity;
import com.gocourse.courses.data.CourseRepository;
import jakarta.inject.Inject;
import jakarta.validation.Valid;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.NotFoundException;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.UriInfo;
import java.util.List;
@Path("courses")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class CourseResource {
@Inject
CourseRepository repository;
@GET
public List<Course> list() {
return repository.findAll().stream().map(CourseResource::toCourse).toList();
}
@GET
@Path("{code}")
public Course get(@PathParam("code") String code) {
return repository.find(code)
.map(CourseResource::toCourse)
.orElseThrow(() -> new NotFoundException("Course " + code + " not found"));
}
@POST
public Response create(@Valid Course course, @Context UriInfo uriInfo) {
if (repository.find(course.code()).isPresent()) {
return Response.status(Response.Status.CONFLICT)
.entity(new ApiError(409, "Course " + course.code() + " already exists"))
.build();
}
repository.save(new CourseEntity(course.code(), course.title(), course.category(),
course.feeInr(), course.seats()));
return Response.created(uriInfo.getAbsolutePathBuilder().path(course.code()).build())
.entity(course)
.build();
}
private static Course toCourse(CourseEntity entity) {
return new Course(entity.getCode(), entity.getTitle(), entity.getCategory(),
entity.getFeeInr(), entity.getSeats());
}
}
mvn -q clean package && asadmin redeploy --name courses target/courses.war
API=http://localhost:8080/courses/api/courses
curl -s -w "\n" $API
curl -s -w "\n" $API/rust
curl -s -w " [%{http_code}]\n" -X POST -H "Content-Type: application/json" \
-d '{"code":"react","title":"React Basics","category":"web","feeInr":3499,"seats":25}' $API
curl -s -w " [%{http_code}]\n" -X POST -H "Content-Type: application/json" \
-d '{"code":"react","title":"React Again","category":"web","feeInr":1,"seats":1}' $API
curl -s -o /dev/null -w "%{http_code}\n" -X POST -H "Content-Type: application/json" \
-d '{"code":"x","title":"","category":"web","feeInr":0,"seats":1}' $API
Application deployed with name courses.
Command redeploy executed successfully.
[{"category":"backend","code":"go","feeInr":2999,"seats":20,"title":"Go Language"},{"category":"web","code":"html","feeInr":1999,"seats":40,"title":"HTML and CSS"},{"category":"backend","code":"java","feeInr":4999,"seats":30,"title":"Java Programming"}]
{"status":404,"message":"Course rust not found"}
{"category":"web","code":"react","feeInr":3499,"seats":25,"title":"React Basics"} [201]
{"status":409,"message":"Course react already exists"} [409]
400
How it works:
- Startup seeding. CDI fires the
Startupevent after deployment.DataSeederobserves it and saves three rows; eachsaveruns in its own transaction because of@Transactional. - Entity vs API record.
CourseEntityis the database shape andCourseis the JSON shape. Mapping between them keeps database details, such as lazy fields, out of your API. - Error mapping.
NotFoundMapperis found automatically because of@Provider. EveryNotFoundExceptionin the application now returns the same small JSON error instead of the server's default page. - Validation and conflicts. The one-letter code and blank title fail Bean Validation (400). A duplicate code returns a 409 with a clear message.
- Portable code. Nothing in these classes is GlassFish-specific. Deploy the same
courses.warto WildFly, Payara or Open Liberty and it runs unchanged, which is the main promise of Jakarta EE.