Java EE 7 Application Developer cheat sheet
Java EE 7 Application Developer · Keep the key ideas within reach.
Java EE 7 Platform and Web Application Architecture
Java EE 7 (JSR 342) profiles: Full Platform and Web Profile. Web Profile includes Servlet, JSP, JSF, CDI, EJB Lite, JPA, Bean Validation, JTA, JAX-RS; it excludes JMS, JAX-WS, JCA, and full EJB (MDB, remote, timers).
Java EE 7 new features: JAX-RS 2.0 client API, JSON-P 1.0, WebSocket 1.0, Batch 1.0, Concurrency Utilities 1.0, CDI 1.1 (interceptors, @Transactional), JPA 2.1 (schema generation, stored procedures), Servlet 3.1 (non-blocking I/O), JMS 2.0 (simplified API).
Deployment units: WAR (web components), EJB JAR (enterprise beans), EAR (aggregates modules plus shared libraries under EAR/lib). A WAR can contain EJB Lite beans in WEB-INF/classes.
Packaging of classes: web resources in WEB-INF/classes or WEB-INF/lib; EJB classes in the EJB module; entities may be packaged in either module and are visible to persistence units declaring them.
Classloader delegation: EAR/lib is parent-visible to all modules; by default modules do not see each other's classes unless declared via Class-Path manifest or EAR/lib.
Annotation scanning is controlled per module by web.xml metadata-complete, ejb-jar.xml metadata-complete, and beans.xml (bean-discovery-mode of annotated or all).
Resource injection uses @Resource, @EJB, @Inject; JNDI names follow java:comp/env for component environment, java:module, java:app, java:global scopes.
Lifecycle: Servlet, EJB, and CDI beans have distinct lifecycles; CDI beans default to @Dependent scope, EJBs are pooled, servlets are single-instance multi-threaded.
Servlets and JavaServer Pages (JSP)
Servlet 3.1 adds non-blocking I/O: ServletInputStream.setReadListener and ServletOutputStream.setWriteListener; async processing uses request.startAsync() and AsyncContext, with async-supported set on servlet and filters.
Servlet lifecycle: init(ServletConfig) once, service() per request dispatching to doGet/doPost, destroy() once. Servlets are not thread-safe by default; avoid mutable instance fields.
Session tracking: JSESSIONID cookie or URL rewriting via response.encodeURL; HttpSession methods include setAttribute, getAttribute, invalidate, setMaxInactiveInterval; listeners: HttpSessionListener, HttpSessionAttributeListener.
Filters implement javax.servlet.Filter with init, doFilter(chain), destroy; order is defined by order in web.xml or @WebFilter ordering is undefined.
Request dispatch: RequestDispatcher.forward keeps the same request/response and URL; sendRedirect issues a new client request. Include merges output of another resource.
JSP directives: page (import, contentType, isELIgnored, session), include (translation-time static include), taglib. Actions: jsp:include (runtime), jsp:forward, jsp:useBean, jsp:setProperty.
JSP implicit objects: request, response, out, session, application, config, pageContext, page, exception. EL implicit objects: pageScope, requestScope, sessionScope, applicationScope, param, paramValues, header, cookie, initParam.
JSP lifecycle: translation to servlet, then jspInit, _jspService, jspDestroy. JSPs are compiled on first access unless precompiled; JSP documents (.jspx) use XML syntax.
JavaServer Faces (JSF) and Web Components
JSF 2.2 request lifecycle phases: Restore View, Apply Request Values, Process Validations, Update Model Values, Invoke Application, Render Response. Immediate=true skips validation and model update.
Facelets is the default view technology; templates use ui:composition, ui:define, ui:insert; composite components use composite:interface and composite:implementation in a resource library.
Managed beans are replaced by CDI beans annotated @Named with a scope; @ViewScoped (javax.faces.bean.ViewScoped) keeps state per view, @SessionScoped across requests, @RequestScoped per request.
Navigation: implicit navigation matches outcome to view name; in faces-config.xml defines explicit cases. FacesContext provides access to request, response, and external context.
Conversion and validation: converters implement Converter (getAsObject, getAsString); validators implement Validator. Bean Validation annotations on bean properties integrate with JSF via <f:validateBean>.
Ajax in JSF uses <f:ajax> with execute and render attributes; PartialViewContext handles partial rendering; f:ajax listener can be a method expression.
Resource handling: resources under webapp/resources are referenced with #{resource['lib:name']} or h:graphicImage library/name attributes.
Facelets expression language uses #{...}; JSF 2.2 adds passthrough attributes (p: namespace) and HTML5-friendly markup.
Enterprise JavaBeans (EJB) and CDI
Session bean types: @Stateless (pooled, no client state), @Stateful (conversation state, @Remove), @Singleton (one per JVM, @Startup, @DependsOn). @MessageDriven handles JMS messages implementing MessageListener.
EJB Lite (Web Profile) excludes @Remote interfaces, MDBs, timers, and asynchronous methods; it includes @Stateless, @Stateful, @Singleton, interceptors, and @TransactionAttribute.
Transaction attributes on session beans: REQUIRED (default), REQUIRES_NEW, MANDATORY, NEVER, NOT_SUPPORTED, SUPPORTS. EJB exceptions: application exceptions roll back only if annotated @ApplicationException(rollback=true); system exceptions roll back.
EJB timers: @Schedule for calendar-based, TimerService.createTimer for programmatic; @Timeout method receives Timer. Timers survive restart if persistent.
CDI: @Inject injection points, qualifiers (@Qualifier), producers (@Produces), alternatives (@Alternative), stereotypes (@Stereotype). beans.xml enables bean discovery.
CDI scopes: @Dependent (default), @RequestScoped, @SessionScoped, @ApplicationScoped, @ConversationScoped. @ConversationScoped requires Conversation.begin/end.
CDI interceptors use @InterceptorBinding and @AroundInvoke; decorators use @Decorator and @Delegate to add behavior to interfaces.
@Asynchronous methods on session beans return void or Future; @Lock(READ/WRITE) controls concurrency on singleton beans.
Java Persistence API (JPA) and Entity Mapping
Entity requirements: @Entity class, public/protected no-arg constructor, non-final class, no final persistent fields, @Id mapping. Persistence unit defined in persistence.xml.
Mapping annotations: @Table, @Column, @JoinColumn, @OneToMany, @ManyToOne, @OneToOne, @ManyToMany. Fetch defaults: @ManyToOne and @OneToOne EAGER; @OneToMany and @ManyToMany LAZY.
EntityManager operations: persist, merge, remove, find, createQuery/createNamedQuery, createNativeQuery. Persistence contexts: transaction-scoped (container-managed) vs extended (@PersistenceContext(type=EXTENDED)).
Entity states: new, managed, detached, removed. persist on detached throws EntityExistsException; merge returns a managed copy.
JPQL supports SELECT, UPDATE, DELETE, joins, aggregate functions, and named parameters (:name). Bulk updates bypass the persistence context; use clear() or refresh.
JPA 2.1 additions: schema generation via javax.persistence.schema-generation.* properties, stored procedure queries (@NamedStoredProcedureQuery), converters (@Convert), and entity graphs.
Locking: optimistic via @Version, pessimistic via LockModeType.PESSIMISTIC_WRITE. @Version fields must be numeric or timestamp types.
Relationships: owning side defines the foreign key; mappedBy indicates the inverse side. CascadeType values: PERSIST, MERGE, REMOVE, REFRESH, DETACH, ALL. Orphan removal uses orphanRemoval=true.
RESTful Web Services with JAX-RS
JAX-RS annotations: @Path on class/method, @GET/@POST/@PUT/@DELETE, @Produces and @Consumes for media types, @PathParam, @QueryParam, @FormParam, @HeaderParam, @MatrixParam, @CookieParam, @BeanParam.
Default media type is /; if @Produces is absent the container negotiates. Content negotiation uses Accept header; 406 Not Acceptable when no match.
Response building: Response.ok(entity).type(MediaType.APPLICATION_JSON).build(); Response.status(Response.Status.CREATED).entity(e).build(). @Produces can list multiple types.
JAX-RS 2.0 client API: ClientBuilder.newClient(), client.target(uri).request(mediaType).get(Entity.class). WebTarget, Invocation.Builder, Invocation.
Sub-resource locators are methods annotated only with @Path returning an object whose methods carry HTTP method annotations.
Exception mapping: WebApplicationException and subclasses map to HTTP status; ExceptionMapper customizes responses. @Provider registers providers.
Application subclass overrides getClasses()/getSingletons(); @ApplicationPath sets the base URI. Providers include MessageBodyReader/Writer, filters (ContainerRequestFilter), and interceptors.
Security: @RolesAllowed, @PermitAll, @DenyAll on resource methods; SecurityContext injected via @Context for principal and role checks.
SOAP Web Services with JAX-WS
JAX-WS service endpoint: class annotated @WebService, methods exposed unless private; @WebMethod(exclude=true) hides a method; @WebParam and @WebResult customize WSDL names.
Deployment: @WebService on a class deployed in a WAR (JSR-109 style) or standalone; the WSDL is published at ?wsdl relative to the endpoint URL.
Client proxies: generated via wsimport from WSDL, or dynamic via Dispatch and Provider for message-level access.
SOAP handlers implement SOAPHandler or LogicalHandler; registered via @HandlerChain or in the deployment descriptor.
WS-* support in Java EE 7: WS-Security via @DeclareRoles and container policy; WS-Addressing, WS-ReliableMessaging, and WS-Policy configured via @Policy or XML.
Faults: application faults are checked exceptions annotated @WebFault; SOAPFaultException carries SOAP fault details.
JAX-WS and JAXB: parameter and return types must be JAXB-mappable; @XmlType, @XmlElement, and @XmlAccessorType control schema generation.
Binding: SOAP 1.1 default (text/xml); SOAP 1.2 uses application/soap+xml. MTOM enabled via @MTOM for binary attachments.
Security, Transactions, and Messaging
Declarative security: @RolesAllowed, @PermitAll, @DenyAll (javax.annotation.security) on EJBs and servlets; web.xml , (BASIC, FORM, DIGEST, CLIENT-CERT), .
Programmatic security: EJBContext.isCallerInRole, HttpServletRequest.isUserInRole, SecurityContext for JAX-RS. JAAS realm configuration is container-specific.
JTA transactions: @TransactionAttribute values REQUIRED, REQUIRES_NEW, MANDATORY, NEVER, NOT_SUPPORTED, SUPPORTS. UserTransaction for bean-managed transactions.
Two-phase commit across XA resources; @TransactionAttribute on session bean methods; setRollbackOnly marks rollback. Synchronization callbacks via SessionSynchronization.
JMS 2.0 simplified API: JMSContext, @JMSDestinationDefinition, @JMSConnectionFactoryDefinition. Messaging styles: point-to-point (Queue) and publish/subscribe (Topic).
MDB: @MessageDriven with activationConfig properties (destinationLookup, destinationType); implements MessageListener.onMessage; supports @TransactionAttribute and pooled instances.
JMS message types: TextMessage, BytesMessage, MapMessage, ObjectMessage, StreamMessage. Acknowledge modes: AUTO_ACKNOWLEDGE, CLIENT_ACKNOWLEDGE, DUPS_OK_ACKNOWLEDGE, SESSION_TRANSACTED.
Bean Validation integrates with JPA, JSF, JAX-RS, and EJBs: @NotNull, @Size, @Pattern, @Min, @Max; custom constraints implement ConstraintValidator.
Java EE 7 Platform and Web Application Architecture
Java EE 7 (JSR 342) profiles: Full Platform and Web Profile. Web Profile includes Servlet, JSP, JSF, CDI, EJB Lite, JPA, Bean Validation, JTA, JAX-RS; it excludes JMS, JAX-WS, JCA, and full EJB.
Java EE 7 new features: JAX-RS 2.0 client API, JSON-P 1.0, WebSocket 1.0, Batch 1.0, Concurrency Utilities 1.0, CDI 1.1, JPA 2.1, Servlet 3.1, JMS 2.0.
Deployment units: WAR, EJB JAR, EAR. EAR/lib is visible to all modules; WAR classes in WEB-INF/classes and WEB-INF/lib.
Annotation scanning controlled by metadata-complete in web.xml/ejb-jar.xml and bean-discovery-mode in beans.xml.
Injection: @Resource, @EJB, @Inject; JNDI scopes java:comp/env, java:module, java:app, java:global.
CDI beans default @Dependent; EJBs are pooled; servlets are single-instance multi-threaded.
Servlets and JavaServer Pages (JSP)
Servlet 3.1 non-blocking I/O: setReadListener/setWriteListener; async via request.startAsync() with async-supported on servlet and filters.
Servlet lifecycle: init once, service per request, destroy once. Servlets are not thread-safe; avoid mutable instance fields.
Session tracking: JSESSIONID cookie or URL rewriting via encodeURL; HttpSession listeners include HttpSessionListener.
Filters implement Filter with doFilter(chain); order from web.xml filter-mapping; @WebFilter ordering undefined.
RequestDispatcher.forward keeps request/response; sendRedirect creates new request. Include merges output.
JSP directives: page, include (static), taglib; actions jsp:include (runtime), jsp:forward, jsp:useBean.
JSP implicit objects: request, response, out, session, application, config, pageContext, page, exception.
JSP lifecycle: translation, jspInit, _jspService, jspDestroy; .jspx is XML syntax.
JavaServer Faces (JSF) and Web Components
JSF 2.2 lifecycle: Restore View, Apply Request Values, Process Validations, Update Model Values, Invoke Application, Render Response; immediate=true skips validation.
Facelets templates use ui:composition, ui:define, ui:insert; composite components use composite:interface and composite:implementation.
CDI @Named beans with scopes @ViewScoped, @SessionScoped, @RequestScoped replace managed beans.
Navigation: implicit outcome-to-view matching; explicit in faces-config.xml.
Converters implement Converter; validators implement Validator; Bean Validation integrates via f:validateBean.
Ajax uses <f:ajax> with execute and render; PartialViewContext handles partial rendering.
Resources under webapp/resources referenced via #{resource['lib:name']} or h:graphicImage library/name.
JSF 2.2 adds passthrough attributes (p: namespace) and HTML5-friendly markup.
Enterprise JavaBeans (EJB) and CDI
Session bean types: @Stateless, @Stateful (@Remove), @Singleton (@Startup, @DependsOn); @MessageDriven implements MessageListener.
EJB Lite excludes @Remote, MDBs, timers, async; includes stateless, stateful, singleton, interceptors, @TransactionAttribute.
Transaction attributes: REQUIRED (default), REQUIRES_NEW, MANDATORY, NEVER, NOT_SUPPORTED, SUPPORTS.
Application exceptions roll back only if @ApplicationException(rollback=true); system exceptions roll back.
Timers: @Schedule calendar-based, TimerService.createTimer programmatic, @Timeout receives Timer.
CDI: @Inject, qualifiers, @Produces, @Alternative, @Stereotype; beans.xml enables discovery.
CDI scopes: @Dependent default, @RequestScoped, @SessionScoped, @ApplicationScoped, @ConversationScoped.
Interceptors use @InterceptorBinding with @AroundInvoke; decorators use @Decorator and @Delegate.
Java Persistence API (JPA) and Entity Mapping
Entity requirements: @Entity, no-arg constructor, non-final class, @Id; persistence unit in persistence.xml.
Fetch defaults: @ManyToOne and @OneToOne EAGER; @OneToMany and @ManyToMany LAZY.
EntityManager: persist, merge, remove, find, createQuery, createNativeQuery; transaction-scoped vs extended persistence context.
Entity states: new, managed, detached, removed; persist on detached throws EntityExistsException.
JPQL supports SELECT, UPDATE, DELETE, joins, aggregates, named parameters; bulk updates bypass persistence context.
JPA 2.1: schema generation properties, stored procedure queries, converters, entity graphs.
Locking: optimistic @Version; pessimistic LockModeType.PESSIMISTIC_WRITE.
CascadeType: PERSIST, MERGE, REMOVE, REFRESH, DETACH, ALL; orphanRemoval=true removes orphans.
RESTful Web Services with JAX-RS
Annotations: @Path, @GET/@POST/@PUT/@DELETE, @Produces, @Consumes, @PathParam, @QueryParam, @FormParam, @HeaderParam, @BeanParam.
Content negotiation via Accept; 406 Not Acceptable when no match; default media type /.
Response building: Response.ok(entity).type(mediaType).build(); Response.status(CREATED).entity(e).build().
JAX-RS 2.0 client: ClientBuilder.newClient(), target(uri).request(type).get(Entity.class).
Sub-resource locators are @Path-only methods returning objects with HTTP method annotations.
Exception mapping: WebApplicationException and ExceptionMapper; @Provider registers providers.
Application subclass overrides getClasses()/getSingletons(); @ApplicationPath sets base URI.
Security: @RolesAllowed, @PermitAll, @DenyAll; SecurityContext via @Context.
SOAP Web Services with JAX-WS
@WebService exposes public methods; @WebMethod(exclude=true) hides; @WebParam and @WebResult customize WSDL names.
WSDL published at ?wsdl relative to endpoint URL; deployment in WAR or standalone.
Clients: wsimport-generated proxies, or Dispatch and Provider for dynamic message access.
Handlers implement SOAPHandler or LogicalHandler; registered via @HandlerChain.
WS-Security, WS-Addressing, WS-ReliableMessaging, WS-Policy configured via @Policy or XML.
Application faults are checked exceptions annotated @WebFault; SOAPFaultException carries fault details.
JAXB mapping via @XmlType, @XmlElement, @XmlAccessorType controls schema generation.
SOAP 1.1 default (text/xml); SOAP 1.2 uses application/soap+xml; MTOM via @MTOM for attachments.
Security, Transactions, and Messaging
Declarative security: @RolesAllowed, @PermitAll, @DenyAll; web.xml security-constraint, login-config (BASIC, FORM, DIGEST, CLIENT-CERT).
Programmatic security: EJBContext.isCallerInRole, HttpServletRequest.isUserInRole, SecurityContext for JAX-RS.
JTA attributes: REQUIRED, REQUIRES_NEW, MANDATORY, NEVER, NOT_SUPPORTED, SUPPORTS; UserTransaction for BMT.
Two-phase commit across XA resources; setRollbackOnly marks rollback; SessionSynchronization callbacks.
JMS 2.0: JMSContext, @JMSDestinationDefinition; point-to-point Queue vs publish/subscribe Topic.
MDB: @MessageDriven with activationConfig (destinationLookup, destinationType); implements MessageListener.
JMS message types: TextMessage, BytesMessage, MapMessage, ObjectMessage, StreamMessage; acknowledge modes AUTO, CLIENT, DUPS_OK, SESSION_TRANSACTED.
Bean Validation: @NotNull, @Size, @Pattern, @Min, @Max; custom constraints implement ConstraintValidator.