Java EE 7

Notes from Java EE 7 tutorial Sep 2013


  • Default dmin port: 4848, HTTP Port: 8080
  • asadmin stop-domain domain1
  • glassfish contains a java db: asadmin start-database
  • Netbeans has a profiler inside it.

Resource Injection

In Java EE, JNDI enables components to locate other components and resources.
A resource is a program object that provides connections to systems, such as database servers (data source) and messaging systems.
An administrator creates resources in a JNDI namespace inside the Glassfish.
You inject resources by using the @Resource annotation in an application
Resource injection enables you to inject any resource available in the JNDI namespace into any container-managed object, such as a servlet, an enterprise bean, or a managed

Dependency injection

Contexts and Dependency Injection for Java EE (CDI) is one of several Java EE 7 features that help to knit together the web tier and the transactional tier of the Java EE platform.
CDI is for javaee but using Weld from jboss we can use it in javase.
Dependency injection enables you to turn regular Java classes into managed objects and to inject them into any other managed object. CDI is based on interceptor concept. This is similar to injecting classes in spring using autowire.

public class NewServlet extends HttpServlet {
    //Message is just a normal interface with an implementation
    @Inject private Message message;
//managed object/bean which is a normal class. 
//can be and interface also.
//can have scope
public class CurrencyConverter { ... }
//injecting managed bean:
public class MyServlet extends HttpServlet {
@Inject CurrencyConverter cc;



The lifecycle of a JavaServer Faces application starts and ends with the following activity: The client makes a request for the web page, and the server responds with the page. The lifecycle consists of two main phases: execute and render.

During the execute phase, several actions can take place:

  • The application view is built or restored.
  • The request parameter values are applied.
  • Conversions and validations are performed for component values.
  • Managed beans are updated with component values.
  • Application logic is invoked.

The JavaServer Faces component architecture is designed such that the functionality of the components is defined by the component classes, whereas the component rendering can be defined by a separate renderer class.

A render kit defines how component classes map to component tags that are appropriate for a particular client. The JavaServer Faces implementation includes a standard HTML render kit for rendering to an HTML client.

Each custom tag defined in the standard HTML render kit is composed of the component functionality (defined in the UIComponent class) and the rendering
attributes (defined by the Renderer class)

A UICommand component can be rendered as a button or a link, using the h:commandButton or h:commandLink tag.

Any request after the initial request to the application are called postback requests.

A JavaServer Faces application can optionally associate a component with server-side object data. This object is a JavaBeans component, such as a managed bean. An application gets and sets the object data for a component by calling the appropriate object properties for that component.

The JavaServer Faces specification defines three types of events: application events (action or value change), system events, and data-model events.


Facelets is a to the view declaration language for JavaServer Faces technology.
Facelets is a powerful but lightweight page declaration language that is used to build JavaServer Faces views using HTML style templates
Facelets is the preferred presentation technology for building JSF applications. JSP technology, previously used as the presentation technology for JSF.
Facelets views are usually created as XHTML pages.


EL provides a mechanism for enabling the presentation layer (web pages) to communicate with the application logic (managed beans). Both JSP and JSF use EL.

<c:if test="${sessionScope.cart.numberOfItems> 0}">


JSF uses the EL for the following functions:

  • Deferred and immediate evaluation of expressions
  • The ability to set as well as get data
  • The ability to invoke methods

Immediate evaluation ${} means that the expression is evaluated and the result returned as soon as
the page is first rendered. Deferred evaluation #{} means that the technology using the
expression language can use its own machinery to evaluate the expression sometime
later during the page's lifecycle, whenever it is appropriate to do so.

JSP usually uses #{}.

Immediate evaluation expressions are always read-only value expressions.

The EL defines two kinds of expressions: value expressions and method expressions.
Value expressions can either yield a value or set a value. Method expressions reference
methods that can be invoked and can return a value.

Value Expressions

To refer to these objects, you write an expression using a variable that is the name of the object. The following expression references a managed bean called customer: ${customer}

To reference the name property of the customer bean (the bean should have a getName()), use either of these:
${} or
${customer["name"]} or

we can also access enums, list and map items: ${customer.orders[1]}

Value expressions using ${} can be used in

  • Static text: some text ${expr} some text
  • Any standard or custom tag attribute that can accept an expression: <some:tag value="${expr} ${another_exp}"/>

Method Expressions

method expressions must always use the deferred evaluation syntax.
#{object.method} is equivalent to #{object["method"]}.
Method expressions can be used only in tag attributes: <some:tag value="#{bean.method}"/>


The EL offers support for parameterized method calls:

<h:inputText value="#{userNumberBean.userNumber('5')}">

EL has a complete list of operators. for example:
${'hip' gt 'hit'}
${100.0 == 100}
${10 mod 4}

In HTTP, most browsers by default send GET requests for URL retrieval and POST requests for data processing. The GET requests can have query parameters and can be cached, which is not advised for POST requests, which send data to servers for processing.

<a href="/simplebookmark/faces/somepage.xhtml>Message</a>
This is a simple GET request that cannot pass any data from page to page.


Ajax functionality can be added to a JavaServer Faces application in one of the following ways:

  • Adding the required JavaScript code to an application
  • Using the built-in Ajax resource library

The built-in Ajax resource can be used in JavaServer Faces web applications in one of the following ways:

  • By using the f:ajax tag
  • By using the JavaScript API method jsf.ajax.request() directly within the Facelets application. This method provides direct access to Ajax methods, and allows customized control of component behavior.

Ajax behavior is added to an input component:

<h:inputText value="#{bean.message}">
<f:ajax />

If an event is not defined for f:ajax, the default action for the component is performed. For the inputText component, when no event attribute is specified, the default event is valueChange.

Behind the scenes, the jsf.ajax.request() method of the JavaScript resource library collects the data provided by the f:ajax tag and posts the request to the JavaServer Faces lifecycle.

In the following example userNo is the bean name. render indicated the component id to render for the results.

<h:commandButton id="submit" value="Submit">
<f:ajax event="click" execute="userNo" render="result"/>
<h:outputText id="result" value="#{userNumberBean.response}"/>
We still need a form for the ajax tag to work:
        <h:commandButton id="submit" value="Submit">
            <f:ajax event="click" render = "result"/>
        <h:outputText id="result" value="#{}"/>
    title="Type a number from 0 to 10:"
<h:commandButton id="submit" value="Submit">
    <f:ajax execute="userNo" render="result" onevent="msg"/>
<h:outputText id="result" style="color:blue"
The f:ajax tag specifies that when the button is clicked, the h:inputText componentwith the id value userNo is executed. The components with the id values result and errors1 are then rendered.
msg is a js function. we can call js from jsf.

A composite component is a special type of template that acts as a component. A composite component consists of a collection of markup tags and other existing components. This reusable, user-created component has a customized, defined functionality and can have validators, converters, and listeners attached to it like any other component.

The Faces Flows feature of JavaServer Faces technology allows you to create a set of pages with a scope, javax.faces.flows.FlowScoped, that is greater than request scope but less than session scope.


  • Web service endpoints can be implemented as servlets
  • Java servlet spec now provide in built facilities to upload files.


  1. Web container loads the servlet class if it already exist or creates one
  2. Initializes the servlet instance by calling the init method.
  3. Invokes the service method, passing request and response objects.
  4. If it needs to remove the servlet, the container finalizes the servlet by calling the servlet's destroy method.

Asynchronous processing

Servlet 3.0 introduces the ability for asynchronous processing of requests so that the thread may return to the container and perform other tasks.
Web containers in application servers normally use a server thread per client request.
If we have blocking or long running tasks we should use async servlets. This is to reuse server threads and not having them sit idle.

@WebServlet(urlPatterns={"/asyncservlet"}, asyncSupported=true)
public class AsyncServlet extends HttpServlet { ... }
public void doGet(HttpServletRequest request, HttpServletResponse response) {
This call puts the request into asynchronous mode and ensures that the response is not committed after exiting the service method. You have to generate the response in the
asynchronous context after the blocking operation completes or dispatch the request to another servlet.
final AsyncContext acontext = request.startAsync();
acontext.start(new Runnable() {
public void run() {
String param = acontext.getRequest().getParameter("param");
String result = resource.process(param);
HttpServletResponse response = acontext.getResponse();
/* ... print to the response ... */

The dukeetf example application uses a programming model known as long polling. In the traditional HTTP request and response model, the user must make an explicit request (like clicking on a link or submitting a form) to get any new information from the server, and the page has to be reloaded. Long polling provides a mechanism for web applications to push updates to clients using HTTP without the user making an explicit request. The server handles connections asynchronously and the client use JavaScript to make new connections. In this model, clients make a new request immediately after receiving new data and the server keeps the connection open until new data becomes available.

DukeETF example is very useful.

Servlet bad practices

  • Servlet containing business logic
  • Servlet creates a new thread. You should use threads provided by the container whenever possible, instead of manually creating new threads.
  • Servlet calls Thread.sleep inside a while loop to simulate periodic events. You should use the timer service from the enterprise Java beans (EJB) container to schedule periodic notifications.


WebSocket is an application protocol that provides full-duplex communications between two peers over the TCP protocol.
WebSocket provide a full-duplex and bi-directional communication protocol over a single TCP connection.
In websocket, server can initiate the connection unlike http.

As opposed to servlets, WebSocket endpoints are instantiated multiple times. The container creates an instance of an endpoint per connection to its deployment URI. Each instance is associated with one and only one connection. This facilitates keeping user state for each connection and makes development easier since there is only one thread executing the code of an endpoint instance at any given time.

If there are 2 clients then there will be 2 server instances in jvm.

In dukeetf2 example profiler shows 2 instances of ETFEndpoint and 1 instance of PriceVolumeBean as it is singleton.

websocket example is very good.


  • Webservices in java ee support JAXWS- java api for xml web services and JAXRS- java api for restful web services.
  • REST is well suited for basic, ad hoc integration scenarios.
  • RESTful web services, often better integrated with HTTP than SOAP-based services are, do not require XML messages or WSDL service-API definitions.
  • Metro is a webservice framework. Jersey is a rest framework.


  • JAX-WS: addresses advanced QoS requirements commonly occurring in enterprise computing. When compared to JAX-RS, JAX-WS makes it easier to support the WS-* set of protocols, which provide standards for security ad reliability, among other things, and interoperate with other WS-* conforming clients and servers.
  • JAX-RS: makes it easier to write web applications that apply some or all of the constraints of the REST style to induce desirable properties in the application, such as loose coupling (evolving the server is easier without breaking existing clients scalability (start small and grow), and architectural simplicity (use off-the-shelf components, such as proxies or HTTP routers). You would choose to use JAX-RS for your web application because it is easier for many types of clients to consum RESTful web services while enabling the server side to evolve and scale. Clients can choose to consume some or all aspects of the service and mash it up with other web-based services.

Webservice client

webservice clients calls are made through a port, a local object that acts as a proxy for the remote service. The port can be created at development time by the wsimport Maven goal (or other ways), which generates JAX-WS portable artifacts based on a WSDL file.


JAXRS has no wsdl. JAX-RS isn't a Web Services library - it's a library for building RESTful services running over HTTP.
If you want WSDL use CXF or Axis, or JAXWS.
Jersey is a JAXRS open source implementation.

public class UserResource {
public String getUser(@PathParam("username") String userName) {
to have more variables:
public class SomeResource {

Spaces in the value of a variable should be substituted with %20: Main%20Street
JAXRS clients can be async.

Enterprise beans

  • Types: session, message driven
  • Session beans are of three types: stateful (one client), stateless, and singleton (one per app).
  • Beans can implement a webservice
  • MDB is stateless, async, has no (business/exposed) interface unlike session beans.

Client Access:

Clients access enterprise beans either through a no-interface view or through a business interface. A no-interface view of an enterprise bean exposes the public methods of the enterprise bean implementation class to clients. Clients using the no-interface view of an enterprise bean may invoke any public methods in the enterprise bean implementation class or any superclasses of the implementation class. A business interface is a standard Java interface that contains the business methods of the enterprise bean.

  • Remote clients cannot access an enterprise bean through a no-interface view.
  • A business interface is not required if the enterprise bean exposes a local, no-interface view (for local clients)

The client of an enterprise bean obtains a reference to an instance of an enterprise bean through either dependency injection, using annotations, or JNDI lookup to find the enterprise bean instance.
Type of client access allowed by the enterprise beans: remote, local, or web service
A web service client can invoke the business methods of a stateless session bean. Message beans cannot be accessed by web service clients.

Naming Conventions:

  • Enterprise bean class: AccountBean
  • Business interface: Account

Embedded ejb container

The embedded enterprise bean container is used to access enterprise bean components from client code executed in a Java SE environment. The container and the client code are executed within the same virtual machine. The embedded enterprise bean container is typically used for testing enterprise beans without having to deploy them to a server.

Async ejb

Session beans can implement asynchronous methods, business methods where control is returned to the client by the enterprise bean container before the method is invoked on the session bean instance. Clients may then use the Java SE concurrency API to retrieve the result, cancel the invocation, and check for exceptions.

public Future<String> processPayment(Order order) throws PaymentException {
    String status = ...;
    return new AsyncResult<String>(status);


Java SE security mechanisms: JAAS, Java GSS, JCE, JSSE, SASL.

Java EE security mechanisms:

Application layer security

  • component containers are responsible for providing application-layer security
  • application firewalls can also be used to enhance application protection

Transport layer security

  • transport-layer security relies on HTTPS using SSL
  • Certificates are necessary when running HTTPS using SSL
  • Additionally messages can be encrypted

Message layer security

  • security is embedded within soap message/attachment and travels with the message (WSS)

I left the rest of this chapter for later.


You can demarcate a transaction in a web component by using either the java.sql.Connection or the javax.transaction.UserTransaction interface. These are the same interfaces that a session bean with bean-managed transactions can use.

Resource adapters

A resource adapter is analogous to a JDBC driver. Both provide a standard API through which an application can access a resource that is outside the Java EE server. For a resource adapter, the target system is an EIS; for a JDBC driver, it is a DBMS.

The Java EE Connector Architecture defines system contracts that enable resource adapter lifecycle and thread management.

Batch processing

We need to define a job in an xml using the Job Specification Language (JSL). A job consists of steps. Each step can be either a chunk step or task step.
We also have decision elements, flows, splits, etc.

Chunk steps are often long-running because they process large amounts of data. Batch frameworks enable chunk steps to bookmark their progress using checkpoints. A chunk step that is interrupted can be restarted from the last checkpoint. The input retrieval and output writing parts of a chunk step save their current position after the processing of each chunk, and can recover it when the step is restarted.


The Java EE web and EJB containers instantiate objects using container-managed thread pools. Therefore, using Java SE concurrent APIs to instantiate Thread objects was strongly discouraged.

Future object is a callback object

Clean Me

read jsf lifecycle
what is the difference between flow and navigation rules?
i left the rest of security chap for when i want to do a project
17.9.4 Session Tracking
skipped chapter 33,34
skipped persistence and messaging
I left the security chap for when i want to do a project
Read the jndi details
Stopped at the case study.

Examples to check: interceptor, dukeETF, websocket, rsvp, last example of JAXRS, CDI example at the end of chap 32

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License