Invoking session beans from web applications

Frequently, Java EE applications consist of web applications acting as clients for EJBs. Before Java EE 6, the most common way of deploying a Java EE application that consists of both a web application and one or more session beans was to package both the WAR file for the web application and the EJB JAR files into an EAR (Enterprise ARchive) file.

Java EE 6 simplified the packaging and deployment of applications consisting of both EJBs and web components.

In this section, we will develop a JSF application with a CDI named bean acting as a client to the DAO session bean we just discussed in the previous section.

In order to make this application act as an EJB client, we will develop a CustomerController named bean so that it delegates the logic to save a new customer to the database to the CustomerDaoBean session bean we developed in the previous section:

package net.ensode.javaeebook.jsfjpa; 
 
//imports omitted for brevity 
 
@Named 
@RequestScoped 
public class CustomerController implements Serializable { 
 
    @EJB 
    private CustomerDaoBean customerDaoBean; 
 
    private Customer customer; 
 
    private String firstName; 
    private String lastName; 
    private String email; 
 
    public CustomerController() { 
        customer = new Customer(); 
    } 
 
    public String saveCustomer() { 
        String returnValue = "customer_saved"; 
 
        try { 
            populateCustomer(); 
            customerDaoBean.saveCustomer(customer); 
        } catch (Exception e) { 
            e.printStackTrace(); 
            returnValue = "error_saving_customer"; 
        } 
 
        return returnValue; 
    } 
 
    private void populateCustomer() { 
        if (customer == null) { 
            customer = new Customer(); 
        } 
        customer.setFirstName(getFirstName()); 
        customer.setLastName(getLastName()); 
        customer.setEmail(getEmail()); 
    } 
 
//setters and getters omitted for brevity 
 
} 

As we can see, all we had to do was to declare an instance of the CustomerDaoBean session bean, and decorate it with the @EJB annotation so that an instance of the corresponding EJB is injected, then invoke the EJB's saveCustomer() method.

Notice that we injected an instance of the session bean directly into our client code. The reason we can do this is because of a feature introduced in Java EE 6. When using Java EE 6 or newer, we can do away with local interfaces and use session bean instances directly in our client code.

Now that we have modified our web application to be a client for our session bean, we need to package it in a WAR (web archive) file and deploy it in order to use it.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.107.193