Over a million developers have joined DZone.
Refcard #198

Java Enterprise Edition 7

Streamlining Modern Java Development

by Andrew Rubinger and Arun Gupta

Focuses on the key APIs of Java EE7 most relevant to modern development, and more.

Free PDF
Java Enterprise Edition 7
Section 1

About the Platform

Enterprise software development is inherently complex; multiuser systems open the door to concerns such as transactional integrity, security, persistence integration, and interaction between components. Very simply put, the mission of the Java Enterprise Edition is to enable an out-of-thebox set of configurable services which allow the programmer to write less and focus on delivering clean business logic.

To this end, Java EE 7 is in fact an aggregate of many interoperable technologies designed to deliver a unified experience. Application Servers which are certified to the standards defined by the Java Community Process are intended to service applications written to the specifications within the platform.

For the sake of brevity, this Refcard will focus on the key APIs of Java EE 7 most relevant to modern development.

Section 2

Java Platform, Enterprise Edition 7 (Java EE7)


This umbrella specification ties together the various subsystems which compose the platform, and provides additional integration support. The Java EE 7 platform added the following new APIs to previous version of the platform:

  • Java API for WebSocket 1.0
  • Batch Applications for the Java Platform
  • Java API for JSON Processing 1.0
  • Concurrency Utilities for Java EE 1.0

In addition, Java API for RESTful Web Services 2.0 and Java Message Service 2.0 went through significant updates. Several other technologies like Contexts and Dependency Injection 1.1, Bean Validation 1.1, Servlet 3.1, Java Persistence API 2.1, Java Server Faces 2.2, and Java Transaction API 1.2 were updated to provide a more coherent way of building enterprise applications.

Useful Resources:

Section 3

Java API for Websocket 1.0


WebSocket provides a full-duplex, bi-directional communication over a single TCP channel. This overcomes a basic limitation of HTTP where the server can send updates to the client and a TCP connection is maintained between client and server until one of them explicitly closes it. WebSocket is also a very lean protocol and requires minimal framing on the wire. Java API for WebSocket 1.0 is a new addition to the platform and provides an annotated and a programmatic way to develop, deploy, and invoke WebSocket endpoints.

Annotated endpoint can be defined as:

@ServerEndpoint(value=“/chat”, encoders=ChatMessageEncoder.class, 
public class ChatServer {
  public String receiveMessage(ChatMessage message, Session client) 
    for (Session s : client.getOpenSessions()) {

Alternatively, programmatic endpoint can be defined as:

public class ChatServer extends Endpoint {
  public void onOpen(Session session, EndpointConfig ec) {

Client endpoint is annotated with @ClientEndpoint and can be connected to a server endpoint as:

WebSocketContainer container = ContainerProvider.
String uri = “ws://localhost:8080/chat/websocket”;
container.connectToServer(ChatClient.class, URI.create(uri));

Public API from javax.websocket:

Class Name Description
Server Endpoint Annotation that decorates a POJO as a WebSocket server endpoin
Client Endpoint Annotation that decorates a POJO as a WebSocket client endpoint
PathParam Annotate method parameters of an endpoint with URItemplate
Session Represents a conversation between two WebSocket endpoints
Encoders Interface to convert application objects into WebSocket messages
Decoders Interface to convert WebSocket objects into application messages
Message Handler Interface to receive incoming messages in a conversation
OnMessage Makes a Java method receive incoming message
OnOpen Decorates a Java method to be called when connection is opened
OnClose Decorates a Java method to be called when connection is closed
OnError Decorates a Java method to be called when there is an error
Section 4

Batch Applications for the Java Platform 1.0


Batch Applications allows developers to easily define non-interactive, bulk-oriented, long-running tasks in item-oriented and task-oriented ways. It provides a programming model for batch applications and a runtime for scheduling and executing batch jobs. It supports item-oriented processing using Chunks and task-oriented processing using Batchlets. Each job is defined using Job Specification Language, aka Job XML.

<job id=”myJob” xmlns=”http://xmlns.jcp.org/xml/ns/javaee” 
  <step id=”myStep”>
    <chunk item-count=”3”>
      <reader ref=”myItemReader”/>
      <processor ref=”myItemProcessor”/>
      <writer ref=”myItemWriter”/>

Each item is read, processed, and aggregated for writing. item-count number of items are processed within a container-managed transaction.

Different elements define the sequence of a job:

  • Step: Independent and sequential phase of a job
  • Flow: Sequence of execution elements that execute together as a unit
  • Split: Set of flows that execute concurrently
  • Decision: Customized way of determining sequencing among step, flows, and splits

Public API from javax.batch:

Class Name Definition
BatchRuntime Represents the JSR 352 runtime
JobOperator Interface for operating on batch jobs
ItemReader Batch artifact that reads item for chunk processing
ItemProcessor Batch artifact that operate on an input item and produce an output item for chunk processing
ItemWriter Batch artifact that writes to a list of item for chunk processing
Batchlet Batch step for item-oriented processing
BatchProperty Annotation to define a batch property injected from Job XML
JobListener Interface that intercepts job execution
StepListener Interface that intercepts step execution
ChunkListener Interface that intercepts chunk processing
Checkpoint Algorithm Provides a custom checkpoint policy for chunk steps
Partition Mapper Provides unique batch properties for each batch execution
Partition Reducer Unit of work demarcation across partitions
Section 5

Java API for JSON Processing 1.0


JSON is a lightweight data-interchange format and is the lingua franca of the web for consuming and creating web services. A new API to parse and generate JSON is introduced in the platform which reduces the dependency on third-party libraries. The API offers to produce/consume JSON text in a low-level streaming fashion (similar to StAX API for XML).

JsonParser parser = Json.createParser(new FileInputStream(...));

The event-based parser allows an application developer to ask for an event using parser.next(). This API returns a JsonParser.Eventwhich consists of values that indicate the start of an object, end of an object, and other similar events. This gives a more procedural control over processing of the JSON.

The streaming API allows you to generate a simple JSON object as:

StringWriter w = new StringWriter();
JsonGenerator gen = factory.createGenerator(w);
  .write(“apple”, “red”)
  .write(“banana”, “yellow”)

The API also offers a high-level Object Model API that provides immutable object models for JSON object and array structures. These JSON structures are represented as object models via the Java types JsonObject and JsonArray.

JsonReader reader = Json.createReader(new FileInputStream(...));
JsonObject json = reader.readObject();

Object Model API allows you to generate a simple JSON object as:

  .add(“apple”, “red”)
  .add(“banana”, “yellow”)

Public API from javax.json:

Class Name Definition
Json Factory class for creating JSON processing objects.
JsonObject Represents an immutable JSON object value
JsonArray Represents an immutable JSON array
JsonWriter Writes a JSON object or array structure to an output source
JsonReader Reads a JSON object or an array structure from an input source.
JsonGenerator Writes JSON data to an output source in a streaming way.
JsonParser Provides forward, read-only access to JSON data in a streaming way.
JsonParser.EVENT An event from JsonParser
Section 6

Concurrency Utilities for Java EE 1.0


Concurrency Utilities for Java EE provides a simple, standardized API for using concurrency from application components without compromising container integrity while still preserving the Java EE platform’s fundamental benefits. This API extends the Concurrency Utilities API developed under JSR-166 and found in Java 2 Platform, Standard Edition 7 in the java.util.concurrent package.

Four managed objects are provided:


A new default instance of these objects is available for injection in the following JNDI namespace:


A new instance of ManagedExecutorServicecan be created as:

InitialContext ctx = new InitialContext(); ManagedExecutorService 
executor =

It can also be injected as:

ManagedExecutorService executor;

An application-specific ManagedExecutorcan be created by adding the following fragment to web.xml:



Class Name Definition
ManagedExecutorService Manageable version of ExecutorService
ManagedScheduled ExecutorService Manageable version of ScheduledExecutorService
ManagedThreadFactory Manageable version of ThreadFactory
ContextService Provides methods for creating dynamic proxy objects with contexts in a typical Java EE application
ManagedTaskListener Is used to monitor the state of a task's Future

Definitions for variable argument lists are in the header file cstdarg. Here’s how that works out in code:

#include <cstdarg>
void funct(int num, ... )
  va_list arg_list;
  va_start(arg_list, num);
  int i = va_arg (arg_list, int);
  int j = va_arg(arg_list, double);
Section 7

Java API for RESTful Web Services (JAX-RS) 2.0


JAX-RS provides a standard annotation-driven API that helps developers build a RESTful web service and invoke it. The standard principles of REST, such as identifying resource as URI, a well-defined set of methods to access the resource, and multiple representation formats of a resource can be easily marked in a POJO via annotations.

JAX-RS 2 adds a new Client API that can be used to access web resources. Without this API, users must use a low-level HttpUrlConnection to access the REST endpoint.

Author author = ClientBuilder
  .resolveTemplate(“author”, 1)

Client API provides support for different HTTP verbs, support for custom media types by integration with entity providers, and dynamic invocation. JAX-RS 2 allows an asynchronous endpoint that suspends the client connection if the response is not readily available and later resumes it when it is.

  public class Authors {
    public void getAll(@Suspended final AsyncResponse ar) {
      executor.submit(new Runnable() {
        public void run() { … }

Client API also permits retrieval of the response asynchronously by adding an async()method call before the method invocation.

Author author = ClientBuilder.newClient().target(...).async().

Filters and Entity Interceptors are extension points to customize the request/response processing on the client and the server side. Filters are mainly used to modify or process incoming and outgoing request or response headers. A filter is defined by implementing ClientRequestFilter, ClientResponseFilter, ContainerRequestFilter, and/or ContainerResponseFilter.

public class HeaderLoggingFilter implements ClientRequestFilter, 
ClientResponseFilter {
  // from ClientRequestFilter
  public void filter(ClientRequestContext crc) throws 
  IOException {
    for (Entry e : crc.getHeaders().entrySet()) {
      … = e.getKey();
      … = e.getValue();

  // from ClientResponseFilter
  public void filter(ClientRequestContext crc, ClientResponseContext crc1) throws IOException {

Entity Interceptors are mainly concerned with marshaling and unmarshaling of HTTP message bodies. An interceptor is defined by implementing ReaderInterceptor or WriterInterceptor, or both.

public class BodyLoggingFilter implements WriterInterceptor {
  public void aroundWriteTo(WriterInterceptorContext wic) {

JAX-RS 2 also enables declarative validation of resources using Bean Validation 1.1.

public class Author {
  @NotNull @Size(min=5)
  private String firstName;

Public API Selection from javax.ws.rs Package:

Class Name Description
AsyncInvoker Uniform interface for asynchronous invocation of HTTP methods
ClientBuilder Entry point to the Client API
Client Entry point to build and execute client requests
ClientRequestFilter Interface implemented by client request filters
ClientResponseFilter Interface implemented by client response filters
ContainerResponseFilter Interface implemented by server request filters
ContainerRequestFilter Interface implemented by server response filters
ConstrainedTo Indicates the runtime context in which an JAXRS provider is applicable
Link Class representing hypermedia links
ReaderInterceptor Interface for message body reader interceptor
WriterInterceptors Interface for message body writer interceptor
NameBinding Meta-annotation used for name binding annotations for filters and interceptors
WebTarget Resource target identified by a URI
Section 8

Java Message Service 2.0


Message-oriented middleware (MOM) allows sending and receiving messages between distributed systems. JMS is a MOM that provides a way for Java programs to create, send, receive, and read an enterprise system’s messages.

A message can be easily sent as:

@JMSDestinationDefinition(name=”...”, interfaceName=”javax.jms.Queue”)
public class MessageSender {
  @Inject JMSContext context;
  Destination myQueue;
  public void sendMessage() {
    context.sendProducer().send(myQueue, message);

The newly introduced simplified API is very fluent, uses runtime exceptions, is annotation-driven, and makes usage of CDI to reduce the boilerplate code.

A message can be received as:

public void receiveMessage() {
  String message = context.createConsumer(myQueue).
receiveBody(String.class, 1000);

Public API from javax.jms:

Class Name Definition
JMSContext Main interface to the simplified API
JMSProducer Simple object used to send messages on behalf of JMSContext
JMSConsumer Simple object used to receive messages from a queue or topic
JMS Connection Factory Annotation used to specify the JNDI lookup name of ConnectionFactory
JMS Destination Definition Annotation used to specify dependency on a JMS destination
QueueBrowser Object to look at messages in client queue without removing them
Section 9

Contexts and Dependency Injection for Java


The Java Contexts and Dependency Injection specification (CDI) introduces a standard set of application component management services to the Java EE platform. CDI manages the lifecycle and interactions of stateful components bound to well-defined contexts.

CDI provides typesafe dependency injection between components and defines interceptors and decorators to extend the behavior of components, an event model for loosely coupled components, and an SPI allowing portable extensions to integrate cleanly with the Java EE environment.

Java EE 7 platform enables default CDI injection for all beans that explicitly contain a CDI scope annotation and EJBs. A new attribute, “beandiscovery-mode” attribute is added to beans.xml:

  http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd” bean-discoverymode=”all”>

This attribute can take the following values:

all: All types in the archive are considered for injection.

annotated: Only types with an explicitly declared CDI scope are considered for injection. none: Disable CDI

By default, CDI interceptors are disabled and can be enabled and ordered via the @javax.interceptor.Interceptor.Priority annotation as shown:

public class LoggingInterceptor {
  //. . .

This can be done for decorators and alternatives too.

In addition, CDI 1.1 also introduces the following:

  • Support for @AroundConstructlifecycle callback for constructors
  • Binding interceptors to constructors
  • Interceptor binding moved to the interceptors spec, allowing for reuse by other specifications
  • Support for decorators on built in beans
  • EventMetadatato allow inspection of event metadata
  • @Vetoedannotation allowing easy programmatic disablement of classes
  • Many improvements for passivation capable beans, including @ TransientReferenceallowing instances to be retained only for use within the invoked method or constructor
  • Scope activation and destruction callback events
  • AlterableContextallowing bean instances to be explicitly destroyed
  • Class exclusion filters to beans.xml to prevent scanning of classes and packages
  • Unmanagedallowing easy access to non-contextual instances of beans
  • Allow easy access to the current CDI container
  • AfterTypeDiscoveryevent, allowing extensions to register additional types after type discovery
  • @WithAnnotationsas a way of improving extension loading performance enchancements
Section 10

Bean Validation 1.1


Expanded in Java EE 7, the Bean Validation Specification provides for unified declaration of validation constraints upon bean data. It may be used to maintain the integrity of an object at all levels of an application – from user form input in the presentation tier all the way to the persistence layer.

New in the 1.1 release is:

  • Method-level validation (validation of parameters or return values)
  • Dependency injection for Bean Validation components
  • Integration with Context and Dependency Injection (CDI)
  • Group conversion in object graphs
  • Error message interpolation using EL expressions
  • Support for method and constructor validation (via CDI, JAX-RS etc)
  • Integration with CDI (Validatorand ValidatorFactoryinjectable instances, ConstraintValidatorinstances being CDI beans and thus accept @Inject, etc)

Here’s how to apply Bean Validation constraints in a declarative fashion to ensure the integrity of a User object:

public class User {
  @Size(min=1, max=15)
  private String firstname;

  @Size(min=1, max=30)
  private String lastname;

  public String email;
Section 11

Java Servlet 3.1


Servlet technology models the request/response programming model, and is commonly used to extend HTTP servers to tie into server-side business logic. In Servlet 3.1, the specification has been expanded over previous versions to include support for non-blocking I/O, security and API enhancements.

Non-Blocking I/O

Code Example

A traditional approach to reading data is to poll for available input in a loop:

public class TestServlet extends HttpServlet {
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { 
  ServletInputStream input = request.getInputStream();
    byte[] b = new byte[1024];
    int len = -1;
    while ((len = input.read(b)) != -1) {
    . . . 

In the case that we’re reading faster than data is available via the read() method, the calling Threadwill block. An alternative approach is to leverage event listeners; using the new nonblocking additions to the Servlet API, this can be done as follows:

AsyncContext context = request.startAsync();
ServletInputStream input = request.getInputStream();
input.setReadListener(new ReadListener(){...})

The ReadListener interface defines three callbacks:

  • onAllDataRead(): Invoked when all data for the current request has been read
  • onDataAvailable(): When an instance of the ReadListener is registered with a ServletInputStream, this method will be invoked by the container the first time when it is possible to read data
  • onError(Throwable t):Invoked when an error occurs processing the request
Security Enhancements:
  • Applying run-as security roles to #initand #destroymethods
  • Session fixation attack by adding HttpServletRequest. changeSessionId and a new interface HttpSessionIdListener. You can listen for any session id changes using these methods.
  • Default security semantic for non-specified HTTP method in <security-constraint>
  • Clarifying the semantics if a parameter is specified in the URI and payload
  • Addition of <deny-uncovered-http-methods/>to web.xmlin order to block HTTP methods not covered by an explicit constraint
Miscellaneous Additions to the API:
  • ServletResponse.resetclears any data that exists in the buffer as well as the status code, headers. In addition, Servlet 3.1 also clears the state of calling getServletOutputStreamor getWriter.
  • ServletResponse.setCharacterEncoding:sets the character encoding (MIME charset) of the response being sent to the client (for example, to UTF-8).
  • Relative protocol URL can be specified in HttpServletResponse. sendRedirect. This will allow a URL to be specified without a scheme. That means instead of specifying "http://anotherhost.com/foo/bar. jsp" as a redirect address, "//anotherhost.com/foo/bar.jsp" can be specified. In this case the scheme of the corresponding request will be used.
Section 12

Java Persistence 2.1


Most enterprise applications will need to deal with persistent data, and interaction with relational databases can be a tedious and difficult endeavor. The Java Persistence specification aims to provide an object view of backend storage in a transactionally-aware manner. By dealing with POJOs, JPA enables developers to perform CRUD operations without the need for manually tuning SQL.

New in JPA 2.1 is:

Support for Stored Procedures

We may use the new @NamedStoredProcedureQueryannotation atop an entity to define a stored procedure:

public class Blog {...}

From the client side, we may call this stored procedure like:

StoredProcedureQuery query = EntityManager.createNamedStoredProce
query.registerStoredProcedureParameter(1, String.class, 
query.setParameter(1, “newest”);
query.registerStoredProcedureParameter(2, Integer.class, 
query.setParameter(2, 10);
String response = query.getOutputParameterValue(1);
Bulk Update and Delete via the Query API

CriteriaUpdate, CriteriaDelete, CommonAbstractQueryinterfaces have been added to the API, and the AbstractQuery interface has been refactored.

A spec example of bulk update might look like:

CriteriaUpdate<Customer> q = cb.createCriteriaUpdate(Customer.
Root<Customer> c = q.from(Customer.class); 
q.set(c.get(Customer_.status), “outstanding”)
.where(cb.lt(c.get(Customer_.balance), 10000));
Entity listeners using CDI

Listeners on existing entity events @PrePersist, @PostPersist, @ PreUpdate, and @PreRemove now support CDI injections, and entity listeners may themselves be annotated with @PostConstructand @PreDestroy.

Synchronization of Persistence Contexts

In JPA 2, the persistence context is synchronized with the underlying resource manager. Any updates made to the persistence context are propagated to the resource manager. JPA 2.1 introduces the concept of unsynchronized persistence context. Here is how you can create a container-managed unsynchronized persistence context:

UNSYNCHRONIZED) EntityManager em;
Section 13

Java Server Faces 2.2


JavaServer Faces is a user interface (UI) framework for the development of Java web applications. Its primary function is to provide a componentbased toolset for easily displaying dynamic data to the user. It also integrates a rich set of tools to help manage state and promote code reuse. JSF 2.2 introduces Faces Flow which provides an encapsulation of related pages and corresponding backing beans as a module. This module has well-defined entry and exit points assigned by the application developer. The newly introduced CDI scope @FlowScoped defines the scope of a bean in the specified flow. This enables automatic activation/passivation of the bean when the scope is entered/exited:

public class MyFlow1Bean {
  String address;
  String creditCard; //. . .   

A new EL object for flow storage, #{flowScope}, is also introduced.

<h:inputText id=”input” value=”#{flowScope.value}” />

JSF 2.2 defines Resource Library Contracts, a library of templates and associated resources that can be applied to an entire application in a reusable and interchangeable manner. A configurable set of views in the application will be able to declare themselves as template-clients of any template in the resource library contract.

JSF 2.2 introduces passthrough attributes, which allow us to list arbitrary name/value pairs in a component that are passed straight through to the user agent without interpretation by the UIComponent or Renderer.

Public API from javax.faces.*:

Flow Runtime representation of a Faces Flow.
FlowScoped CDI scope that associates the bean to be in the scope of the specified Flow.
Section 14

Java Transaction API 1.2


Java Transaction API enables distributed transactions across multiple X/ Open XA resources such as databases and message queues in a Java application. The API defines a high-level interface, annotation, and scope to demarcate transaction boundaries in an application. The UserTransactioninterface enables the application to control transaction boundaries programmatically by explicitly starting and committing or rolling back a transaction.

@Inject UserTransaction ut;

ut.rollback()can be called to rollback the transaction.

JTA 1.2 Introduces:

@javax.transaction.Transactionalannotation that enables to declaratively control transaction boundaries on POJOs. This annotation can be specified at both the class and method level, where method-level annotations override those at the class level.

class MyBean {
  . . .

All methods of this bean are executed in a transaction managed by the container. This support is provided via an implementation of CDI interceptors that conduct the necessary suspending, resuming, etc.

JTA 1.2 also introduces a new CDI scope @TransactionScoped. This scope defines a bean instance whose lifecycle is scoped to the currently active JTA transaction.

Public API from javax.transaction.*:

Class Name Definition
User Transaction Allows an application to explicitly manage application boundaries
Transactional Provides the application the ability to declaratively control transaction boundaries on CDI-managed beans, as well as classes defined as managed beans
Transaction Scoped Specifies a standard CDI scope to define bean instances whose lifecycle is scoped to the currently active JTA transaction


  • Featured
  • Latest
  • Popular
Getting Started With Docker
Teaches you typical Docker workflows, building images, creating Dockerfiles, and includes helpful commands to easily automate infrastructure and contain your distributed application.
10.3k 7,328
Getting Started With Real User Monitoring
Teaches you how to use new web standards—like W3C’s Beacon API—to see how your site is performing for actual users, letting you better understand how to improve overall user experience.
4,482 3,703
Core Java
Gives you an overview of key aspects of the Java language and references on the core library, commonly used tools, and new Java 8 features.
104.1k 264.2k
JavaFX 8
Gives you what you need to start using the powerful JavaFX 8 UI and graphics tool with code snippets and visual examples of shapes and controls.
6,818 9,013
Continuous Delivery With Jenkins Workflow
Provides an introduction to the Jenkins Workflow plugin, a tool that extends the popular CD application to manage even the most complex software pipelines and help you continuously deliver more efficiently.
8,707 9,826
Functional Programming in JavaScript
Explains functions, data types, and techniques to demonstrate the functional paradigm through the familiar JavaScript language.
12k 8,737
Java Caching
Explores the building blocks of JCache and other caching APIs, as well as multiple strategies for implementing temporary data storage in your application.
10.5k 10.6k
Getting Started With Microservices
Still re-deploying your entire application for one small update? Microservices deploy modular updates and increase the speed of application deployments.
13.8k 14.3k
Getting Started With MQTT
Explores the fundamentals of MQTT, including message types, QoS levels, and security.
6,090 7,179
Monitoring NGINX
Overcome dropped connections, server errors, and more by efficiently monitoring your NGINX web server.
4,885 3,829
Getting Started With Apache Tomcat
Learn Apache Tomcat, a pure Java open-source web server that implements the Java Servlet, JavaServer Pages, and Expression Language specifications.
8,874 7,348
IntelliJ IDEA Essentials
Helps Java developers navigate the various facets of this world-class IDE, with tips, tricks, shortcuts, and quick tutorials on editor basics, navigation, and more.
20.4k 91.1k
{{ card.title }}
{{card.downloads | formatCount }} {{card.views | formatCount }}

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}