Java EE - How to use EJB and WEB technologies

Java EE - An example on how to use EJB and web components
G.Morreale

Clicca qui per la versione in italiano
Introduction:

The purpose of this article is to create an enterprise application can use the following technologies

  • Entity Bean
  • Session Bean
  • Servlet
  • JSP 

Java EE platform is a very large and able to explain only small parts of them would require much more than a simple article.
Despite this, the attempt is to give an input to the programmer to stimulate the interest and cause him to deepen into a technology.

In order to speed up the approach to Java EE will be used Netbeans and consequently the whole series of wizards that the IDE provides.
Efforts will also include links to in-depth about the individual steps executed.

What will be able to make an example:

The design that you will be able to extract data from a table of a DBMS (mysql in this case) and print them via web page.

What should I install for example:


Note: The last two are not strictly necessary, it is possible to carry out similar operations with another DBMS or waive the graphical tool for the query.

The steps for implementing the example:

  1. The Database
    1. Create the schema
    2. Create a table
    3. People Table
  2. Enterprise Creation Project
  3. EJB
    1. Create a JDBC datasource
    2. Create a persistence unit
    3. Create the entity bean
    4. Create a session facade for the entity bean
  4. WEB Module
    1. Create a servlet
    2. Creare una jsp Create a jsp

1. The Database

Open Mysql query browser, logging on localhost, you create a new DB EsempioDB called with the following SQL:

CREATE DATABASE `EsempioDB`;

Create the table:

CREATE TABLE `esempiodb`.`EsempioTable` (
  `id` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
  `testo` VARCHAR(45) NOT NULL,
  PRIMARY KEY (`id`)
)
ENGINE = InnoDB;

Populate it:

INSERT INTO EsempioTable VALUES(1,'TESTO 1');
INSERT INTO EsempioTable VALUES(2,'TESTO 2');
INSERT INTO EsempioTable VALUES(3,'TESTO 3');


2. Creation Empty Project

Now create a new Enterprise selecting "New Project" in the file menu of NetBeans.

You choose a name, for example, "Example" and leave undisturbed all the required options until the end of the wizard.
This allows you to create a NetBeans EJB module project, a Web module project and a project EAR can include EJB and WEB in single file.

As you can see the list of projects will be the following 3 projects:

  • Example
  • Example-EJB
  • Example-war

note: 
Making a brief mention of the MVC design pattern the last two projects on hold model (EJB) and controller / view (war).

3. EJB

JDBC resource and PERSISTENCE UNIT

Now you need to create a JDBC server resource, a resource that is able to communicate with the DBMS and db created.

note:
This resource is usually created through the command its server (eg Glassfish asadmin add-resources-sun resources.xml) or through the administrative console of the server itself.
In the case of the Glassfish jdbc resource is created through an xml file in which a range of parameters such as username and password database, number of connections in the pool etc.

Xml file example:
<? xml version = "1.0" encoding = "UTF-8"?>
<! DOCTYPE resources PUBLIC "- / / Sun Microsystems, Inc. / / DTD Application Server 9.0 Resource Definitions / / EN" "http://www.sun.com/software/appserver/dtds/sun-resources_1_3.dtd">
<resources>
<jdbc-resource enabled="true" jndi-name="esempioJNDI" object-type="user" pool-name="mysqlPool"/>
<jdbc-connection-pool allow-no-component-callers = "false" associate-with-thread = "false" connection-creation-retry-attempts = "0" connection-creation-retry-interval-in-seconds = " 10 "connection-leak-reclaim =" false "connection-leak-timeout-in-seconds =" 0 "connection-validation-method =" auto-commit "datasource-classname =" com.mysql.jdbc.jdbc2.optional. MysqlDataSource fail-all-connections = "false" idle-timeout-in-seconds = "300" is-connection-validation-required = "false" is-isolation-level-guaranteed = "true" lazy-connection-association = "false" lazy-connection-enlistment = "false" match-connections = "false" max-connection-usage-count = "0" max-pool-size = "32" max-wait-time-in-Millis = " 60000 "name =" mysqlPool "non-transactional-connections =" false "pool-resize-quantity =" 2 "res-type =" javax.sql.DataSource "statement-timeout-in-seconds =" -1 "steady - pool-size = "8" validate-atmost-once-period-in-seconds = "0" wrap-jdbc-objects = "false">
<property name="serverName" value="localhost"/>
<property name="portNumber" value="3306"/>
<property name="databaseName" value="esempioDB"/>
<property name="User" value="root"/>
<property name="password" value="123456"/>
<property name="url" value="jdbc:mysql://localhost:3306/esempioDB"/>
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
</ jdbc-connection-pool>
</ resources>

Netbeans automatically generates the xml file and is responsible to communicate to the Glassfish in order to deploy this resource.

To do this you can go directly to create the persistence unit (would be the next step) and select from combobox DataSource "New Data Source"
(To obtain this window click the right button on the EJB project and choose within the category persistence: persistence unit.) 

Clicking on New Data Source abandons for a moment the creation of the persistence unit and move to the creation of a resource for communication with the db.
Initially you are asked a JNDI name and a URL jdbc.
On the first, you can choose an arbitrary name, eg. esempioJNDI

note:
The jndi name used to identify the resource inside the container, but this path will not be used directly in the code when using the dependency injection will be the same container to find the resource (using the path JNDI)

About the Database Connection, proceed by clicking the "New Database Connection", will appear in another window which must indicate the type of jdbc driver to use (mysql!) And the connection parameters.



Setting everything correctly in order to return to the "New Unit persistence."

On the "New persistence Unit must operate with the following options:

  • Persistence Unit Name is the name of the configuration of the persistence unit

  • Persistence Provider: Indicates which libraries use to manage the mapping between the database and its representation object
(default is proposed Toplink, but there are other viable alternatives, I personally prefer to hibernate, but for the example you give Toplink optional)

  • DataSource is the name of the newly created Datasource
  • Use Java Transaction API: Indicates whether to manage the JTA transaction or not. (leave checked)

  • Table generation Strategy: Tells the persistence provider whether or not to create the tables if there are the entity and not the card tables. (In this example, the tables have been created, but you could directly create the entity representing the tables and let that the persistence provider to automatically generate)

Ultimately chose the name of the persistence unit (for example - Example-ejbPU) you can continue clicking Finish leaving all options unchanged.

Netbeans has created two files automatically

  • sun-resources.xml - needed to create a resource on the server jdbc
  • persistence.xml - needed to indicate a range of options for the management of persistence (mapping O / R) etc.


Entity Bean

What is an entity bean? E 'POJO an object capable of representing the notation through an object table.
Correspondence between entity bean and tables is gestista the persistence provider (a number of libraries).
In the previous step has been chosen as provider Toplink (its libraries are installed by default).

note:
There are two types

BMP - entity Bean Managed Persistence
CMP - Container Managed Persistence entity

The first state that the programmer to deal with the logic of the mapping between the entity and the relational database, the latter supporting the persistence provider. In the entity will be created CMP.

These beans can be created automatically by another wizard of NetBeans.

Right click on the draft EJB Entity + Classes From Databases .. Choose the datasource "esempioJNDI" and choose the tables to be submitted to the wizard (only 1 in this case).

Click next, indicating a package that contains the entity, such entities, click on finish.

note:
The "Generated named query annotation ..." used to automatically generate the query within dell'entity, these queries have the advantage of being precompiled and therefore slightly more efficient. In this instance, however, is not used, so the option is left out.

Entities within the package you can find the entity bean through annotations (@ Table, @ Column etc.) Indicates the persistence provider how to make the mapping between data and nell'entity db.

Session Bean

What is a Session bean? It 'a component that manages the application logic, the classic example of the bank will look to carry out the transfer, etc list movements.

He has a particular life-cycle management by the container (through pooling) and usually are used to manage the request-response model.

note:
There are two types of session bean: Stateless and Stateful, the difference lies in the maintenance of information between clients and servers, only the latter are in fact able to retain such data.

The session bean is composed of its interface and its implementation

note:
The interface can be of two types, Local and Remote, the first is used when the EJB module and web module residing within the same enterprise application (EAR), are obviously more efficient. The latter are used when the EJB modules and the web form (or other forms EJB) reside on different applications or other container.

We use the wizard again NetBeans to automatically create a session bean can implement and expose local interface through the most common methods (insert, edit, deletions etc.) Interaction with the newly created entity.

Right click on the draft EJB - Session Bean Entity For Classes - to choose the entity - to choose a package (eg session) -> Finish!

Inside the package was created session the session bean and its interface.
The interface exposes the methods used from the outside (eg web form: servlet)

It gives a look to the implementation of the session bean


@Stateless
public class EsempiotableFacade implements EsempiotableFacadeLocal {

    @PersistenceContext
    private EntityManager em;

    public void create(Esempiotable esempiotable)
    {
        em.persist(esempiotable);
    }

    public void edit(Esempiotable esempiotable)
    {
        em.merge(esempiotable);
    }

    public void remove(Esempiotable esempiotable)
    {
        em.remove(em.merge(esempiotable));
    }

    public Esempiotable find(Object id)
    {
        return em.find(entities.Esempiotable.class, id);
    }

    public List<Esempiotable> findAll()
    {
        return em.createQuery("select object(o) from Esempiotable as o").getResultList();
    }

}

@Stateless merely indicates the type of bean.

@PersistenceContext
private EntityManager em;

Used to initialize the EntityManager, or that object which has been mapping between entity and tables.
The EntityManager class is a key provider of persistence.
the annotation @ PersistenceContext allows the container to initialize the variable em considering the information entered in the file persistence.xml (Remember the persistence unit!).
The initialization is done through the mechanism of dependency injection (see my previous article).

methods "em.find, em.remove, em.merge, em. persist"
belong to and serve dell'entity manager respectively for the following basic

  • em.find -> search through an entity id (corresponds to a SELECT ... WHERE id =: id)
  • em.remove -> elimination by id (equal to DELETE .. WHERE id =: id
  • em.merge -> insert or update (INSERT or UPDATE) (also serves to recover entity detached ...)
  • em. persist -> inclusion on dell'entity db (corresponds to INSERT)

To achieve the specific operations through ad hoc queries are used, as in method (findall ()), generating a query through the "createQuery" 

The query to be submitted all'entitymanager must be written in EJB-QL, or a specific language can make queries on the entity and not on tables. EJB-QL helps ensure the portability of the queries through various DBMS (the query written in fact exclude mysql).
For more on EJB-ql here.

Of course we must learn to write their own session bean but the example intends to give a fair view ..


WEB Module

We have built the business logic, the EJB is able to extract data from db and communicating through a data structure (List <Esempiotable>)

Now you can create a servlet to invoke the session bean. (According to the MVC pattern, the servlet will serve as a controller).

Right click on the form war -> New Servlet -> Servlet class name = test -> package = servlet -> Finish

It empties the ProcessRequest method so that it is equal to the portion of code following

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
{
    //clicca qui con il tasto dx.

Now you proceed with the initialization (once again made through dependency injection) of the EJB component to be recalled.

Where there is a comment click the right button -> Enterprise Resources -> Call Enterprise Bean -> Click-EJB Example -> EsempioTableFacade -> Finish 

In the latter case, the wizard is used to insert a single line of code:

@ EJB
Private EsempiotableFacadeLocal esempiotableFacade;

Or the one for the initialization of the session bean.
This variable does not need further initialization (thanks all'annotation has already thought of the container!), Is then ready for use.

Within ProcessRequest is then able to enter the following code in order to extract the contents of the table.

<Esempiotable> List esempiotableFacade.findAll list = ();
/ / (do not forget to fix the import!)

Well, have you suffered in the servlet that could print the contents of the List attarverso a PrintWriter or similar response from starting.
But wanting to respect the MVC paradigm and set the example for a more structured you decide to move the data to a view (a JSP page).

In order to move data between the servlet and jsp page using the technique of using a RequestDispatcher forward.

The dispatcher can be initialized as follows:

String arg = "/" + this.getServletName () + ". Jsp";
RequestDispatcher dispatcher = this.getServletContext (). GetRequestDispatcher (arg);

forwarding is done through education

dispatcher.forward (request, response);

This technique does not generate a redirect to the jsp page, but to tell the container that the flow is passed from servlet to jsp keeping intact the status of your request and response.
So it can then transmit the information contained in the "list" to jsp settandoli inside of the request and act in the following manner:

request.setAttribute ( "list", list);

then ultimately the code ProcessRequest will be the following:

protected void ProcessRequest (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException (
        
<Esempiotable> List esempiotableFacade.findAll list = ();
  
request.setAttribute ( "list", list);
            
String arg = "/" + this.getServletName () + ". Jsp";
RequestDispatcher dispatcher = this.getServletContext (). GetRequestDispatcher (arg);
dispatcher.forward (request, response);
            
)

Now create a jsp with the same name as the servlet (test.jsp) (According to MVC, we are creating a view)

The jsp code is as follows:

<% @ page contentType = "text / html"%>
<% @ page pageEncoding = "UTF-8"%>
<% @ page import = "entities.Esempiotable"%>
<% @ page import = "java.util.List"%>
<%
<Esempiotable> List list = (List <Esempiotable>) request.getAttribute ( "list");
%>
<! DOCTYPE HTML PUBLIC "- / / W3C / / DTD HTML 4.01 Transitional / / EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title> JSP Page </ title>
</ head>
<body>
<h1> Content Table EsempioTable </ h1>
<% If (list! = Null)
(For (Esempiotable e: list)
(Out.println (e.getId () + "" + e.getTesto () + "<br/>");)
)
%>
</ body>
</ html>

The code is trivial, is extracted from the request the attribute list and then in the html code is made for a course through the list to print the contents of the entity.

Clicking sull'Enterprise Application Example Run and typing in your browser
http://localhost/Esempio-war/test

The output obtained will be similar to the following image:




Conclusion:

This article is just an introduction to the Java EE world of things to explore and explain this is not really a lot .. This is just the beginning!



2 comments:

kuiro said...

your example is clear, but if i would add another war, for example same first war but change the name, how ???

Giuseppe Morreale said...

add the new war to the ear and update properly application.xml.