FAQ
Best resource: Java EE FAQ1) What is a Java Web Application?
A Java web application generates interactive web pages containing various types of markup language (HTML, XML, and so on) and dynamic content. It is typically comprised of web components such as JavaServer Pages (JSP), servlets and JavaBeans to modify and temporarily store data, interact with databases and web services, and render content in response to client requests. Because many of the tasks involved in web application development can be repetitive or require a surplus of boilerplate code, web frameworks can be applied to alleviate the overhead associated with common activities. For example, many frameworks, such as JavaServer Faces, provide libraries for templating pages and session management, and often promote code reuse.
2) What is Java EE?
Java EE (Enterprise Edition) is a widely used platform containing a set of coordinated technologies that significantly reduce the cost and complexity of developing, deploying, and managing multitier, server-centric applications. Java EE builds upon the Java SE platform and provides a set of APIs (application programming interfaces) for developing and running portable, robust, scalable, reliable and secure server-side applications. Some of the fundamental components of Java EE include:
- Enterprise JavaBeans (EJB): a managed, server-side component architecture used to encapsulate the business logic of an application. EJB technology enables rapid and simplified development of distributed, transactional, secure and portable applications based on Java technology.
- Java Persistence API (JPA): a framework that allows developers to manage data using object-relational mapping (ORM) in applications built on the Java Platform.
Comparative: JavaEE or .NET - an almost unbiased opinion
Old versions (J2EE) criticism and evolution to the current Java EE 6 version:
"The systems created with it (early J2EE version) were too complicated, and development time was frequently out of all proportion to the complexity of the user’s requirements. J2EE was seen as a heavyweight component model:
- difficult to test;
- difficult to deploy;
- difficult to run;
That’s when frameworks such as Struts, Spring, or Hibernate emerged and showed a new way of developing enterprise application. Fortunately, in the second quarter of 2006, Java EE 5 (JSR 244) was released and turned out to be a remarkable improvement. It took some inspiration from open source frameworks by bringing back a plain old java object (POJO) programming model. Metadata could be defined with annotations, and XML descriptors became optional. From a developer’s point of view, EJB 3 and the new JPA were more of a quantum leap than an evolution of the platform. JavaServer Faces (JSF) was introduced as the standard presentation tier framework, and JAX-WS 2.0 replaced JAX-RPC as the SOAP web services API.
Today, Java EE 6 (JSR 316) follows the path of ease of development by embracing the concepts of annotations, POJO programming, and the configuration-by-exception mechanism throughout the platform, including the web tier. It comes with a rich set of innovations such as the brand-new JAX-RS 1.1, it simplifies mature APIs like EJB 3.1, and enriches others such as JPA 2.0 or the timer service. But the major themes for Java EE 6 are portability (through standardizing global JNDI naming, for example), deprecation of some specifications (via pruning), and creating subsets of the platform through profiles.
Java EE provides open standards that are implemented by several commercial (WebLogic, Websphere, MQSeries, etc.) or open source (GlassFish, JBoss, Hibernate, Open JPA, Jersey, etc.) frameworks for handling transactions, security, stateful components, object persistence, and so on.
Today, more than ever in the history of Java EE, your application is deployable to any compliant
application server with very few changes." [6 pag.33]
"From its creation, the aim of Java EE was to enable the development of an application and its deployment to any application server without changing the code or the configuration files. This was never as easy as it seemed. Specifications don’t cover all the details, and implementations end up providing nonportable solutions. That’s what happened with JNDI names, for example. If you deployed an EJB to GlassFish, JBoss, or WebLogic, the JNDI name was different because it wasn’t part of the specification, so you had to change your code depending on the application server you used. That particular problem has now been fixed, because Java EE 6 specifies a syntax for JNDI names that is the same across application servers.
Another difficult point with EJBs was the ability to test them, or use them in a Java SE environment. Some application servers (such as JBoss) had specific implementations to do it. EJB 3.1 specifies an embedded container that is a standard API for executing EJBs within a Java SE environment" [6 pag.45]
The Java Platform, Enterprise Edition (Java EE) builds upon the Java SE platform and provides a set of technologies for developing and running portable, robust, scalable, reliable and secure server-side applications. [12]
General Concepts
Arguments Vs Parameters: Parameters refers to the list of variables in a method declaration. Arguments are the actual values that are passed in when the method is invoked. When you invoke a method, the arguments used must match the declaration's parameters in type and order;
- Class variable: see Instance variable;
- Beans (or JavaBeans components): A bean is a Java class with method names that follow the JavaBeans guidelines.
Writing beans is simply a matter of following certain coding conventions/guidelines for:- properties;
- methods;
- and events;
The power of JavaBeans is that you can use software components without having to write them or understand their implementation.
Beans are distributed as JAR files.
- Bean Validation (Java API for JavaBeans Validation)[10]: is a new validation model available as part of Java EE 6 platform. Bean Validation is integrated into the Java EE containers, allowing the same validation logic to be used in any of the tiers of an enterprise application.
The Bean Validation model is supported by constraints in the form of annotations placed on:
- a field;
- method;
- or class of a JavaBeans component, such as a managed bean or entity class.
Several built-in constraints are available in thejavax.validation.constraints package. The Table 9-2 lists all the built-in constraints, examples: @NotNull; @Digits; @Future; @Past; @Max; @Min
Constraints can be built in or user defined. User-defined constraints are called custom constraints. The Bean Validation provides a mechanism for validating application data.
- CDI (Contexts and Dependency Injection): for the Java EE platform is one of several Java EE 6 features that help to knit together the web tier and the transactional tier of the Java EE platform. CDI is a set of services that, used together, make it easy for developers to use enterprise beans along with JavaServer Faces technology in web applications. Designed for use with stateful objects, CDI also has many broader uses, allowing developers a great deal of flexibility to integrate various kinds of components in a loosely coupled but typesafe way.
- Dependency Injection (Design Pattern): see my other blog Design Patterns section.
Simplified overview of Dependency Injection:
- Façade:
- Facelets: the term Facelets refers to the view declaration language for JavaServer Faces technology. JavaServer Pages (JSP) technology, previously used as the presentation technology for JavaServer Faces, does not support all the new features available in JavaServer Faces 2.0. JSP technology is considered to be a deprecated presentation technology for JavaServer Faces 2.0. Facelets is a part of the JavaServer Faces specification and also the preferred presentation technology for building JavaServer Faces technology-based applications. (Wikipedia also has good facelets info)
Facelets applications are a type of JavaServer Faces applications that use XHTML pages rather than JSP pages.
Using facelets taglibs in XHTML:
Namespace declaration Description xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en Default XHTML namespace xmlns:ui="http://java.sun.com/jsf/facelets" Facelets UI tags like ui:compose and ui:define xmlns:h="http://java.sun.com/jsf/html" JSF HTML tags xmlns:f="http://java.sun.com/jsf/core" JSF core tags xmlns:c="http://java.sun.com/jstl/core" JSTL core tags
NOTE: Avoid using JSTL tags with Facelets! Because JSTL doesn't work with the JSF view tree, this will cause unexpected results. Yes, you can use some of the JSTL core tags with Facelets. However, there are a few that are not supported because they are either redundant (there is a JSF equivalent that is preferred) or they simply don't fit in to the JSF way of doing things.
- Database connection pool[4]: The most efficient way to implement communication between the server and database is to set up a database connection pool. Creating a new connection for each client request can be very time-consuming, especially for applications that continuously receive a large number of requests. To remedy this, numerous connections are created and maintained in a connection pool. Any incoming requests that require access to the application's data layer use an already-created connection from the pool. Likewise, when a request is completed, the connection is not closed down, but returned to the pool. See an example on creating a connection pool with NetBeans (you can also create it inside Glassfish).
- Enterprise Applications [2,3]: is a a shorthand name for large-scale, multi-tiered, scalable, reliable, and secure network applications.
The real time enterprise applications range from online shopping, automated billing mechanisms. Some examples could be payment or hr systems such as Peoplesoft and SAP.
They are called Enterprise Applications because these applications are designed to solve the problems encountered by large enterprises.
The features that make enterprise applications powerful, like security and reliability, often make these applications complex. The Java EE platform is designed to reduce the complexity of enterprise application development by providing a development model, API, and runtime environment that allows developers to concentrate on functionality.
- Entity class [7]: An entity class is a plain old Java object (POJO), a simple Java class that is identified as an entity by the @Entity annotation. Starting with the Java EE 5 specification, you can use entity classes as persistent objects to represent tables in a database. The Java Persistence API enables you to use persistence in web applications without the need to create an EJB module.
- instance variable VS class variable
- Instance variable (aka instance field, instance data member): In object-oriented programming with classes, an instance variable is a variable defined in a class (i.e. a member variable), for which each object of the class has a separate copy. They live in memory for the life of the object.
Ex.:public class MyClass { private int count = 1;
- Class variable (aka class property, class field, or class data member): In object-oriented programming with classes, a class variable is a variable defined in a class (i.e. a member variable) of which a single copy exists, regardless of how many instances of the class exist. A class variable is the opposite of an instance variable. It is a special type of class attribute (or class property, field, or data member). In Java, C#, and C++, class variables are declared with the keyword static, and may therefore be referred to as static member variables.
Ex.:public class MyClass { private static int count = 1;
- Instance variable (aka instance field, instance data member): In object-oriented programming with classes, an instance variable is a variable defined in a class (i.e. a member variable), for which each object of the class has a separate copy. They live in memory for the life of the object.
- JAR file (Java Archive file): this file format enables you to bundle multiple files into a single archive file. Typically a JAR file contains the class files and auxiliary resources associated with applets and applications.
The JAR file format provides many benefits: Security; Decreased download time; Compression; Packaging for extensions; Package Versioning; Package Sealing; Portability;
To learn how to create/run/manage jar files check the official leaning trail: Lesson: Packaging Programs in JAR Files
- JAVA [1] Java technology is both a programming language and a platform. The Java programming language is a high-level object-oriented language that has a particular syntax and style. A Java platform is a particular environment in which Java programming language applications run. There are several Java platforms. Many developers, even long-time Java programming language developers, do not understand how the different platforms relate to each other. There are four platforms of the Java programming language:
- Java Platform, Standard Edition (Java SE)
- Java Platform, Enterprise Edition (Java EE)
- Java Platform, Micro Edition (Java ME)
- JavaFX
- Java EE 6 Web Profile [7]: Java EE 6 Web is a lightweight Java EE 6 profile that contains a subset of the full Java EE 6 platform.
The Java EE 6 Web profile is designed for web applications that do not require advanced Java EE 6 technologies such as:- support for remote interfaces;
- the full EJB 3.1 specification;
- Java Message Service (JMS) API;
- the transaction processing;
- and persistence management
You can use the Java EE Web profile for web applications that use session beans with a local interface or no interface. The full Java EE profile is required if the application uses a remote interface.
Java Web Start:
Java rich internet applications (RIA) are applications that have traits similar to desktop applications, but are deployed via the internet. Java RIAs may be developed and deployed as Java applets or Java Web Start applications.
Applets - Java applets run in the context of a browser. The Java Plug-in software controls the execution and lifecycle of Java applets.
Java Web Start applications - Java Web Start applications are launched via a browser the first time. They may subsequently be launched from a desktop shortcut. Once a Java Web Start application is downloaded and its security certificate has been accepted by the user, it behaves almost like a standalone application.
With Java Web Start: Application clients are packaged inside JAR files and may be installed explicitly on a client’s machine or provisioned on demand using Java Web Start technology. Preparing an application client for Java Web Start deployment involves distributing its JAR with a Java Network Launching Protocol (JNLP) file. When a user running Java Web Start requests the JNLP file (normally by clicking a link in a Web browser), Java Web Start automatically downloads all necessary files. It then caches the files so the user can relaunch the application without having to download them again (unless they have changed, in which case Java Web Start technology takes care of downloading the appropriate files).
- JDBC (Java Database Connectivity) API [4]: Essentially, a JDBC Driver enables communication between Java code understood by the application server (ex. GlassFish), and content in SQL, the language understood by the database server (MySQL). For this, you need to ensure that the database driver (ex. MySQL Connector/J JDBC Driver) is accessible to the server.
The GlassFish Server Open Source Edition contains Database Connection Pooling (DBCP) libraries that provide connection pooling functionality in a way that is transparent to you as a developer. To take advantage of this, you need to configure a JDBC (Java Database Connectivity) data source for the server which your application can use for connection pooling.
The JDBC data source relies on JNDI, the Java Naming and Directory Interface. The JNDI API provides a uniform way for applications to find and access data sources. To learn more about JDBC and data sources: Connecting with DataSource Objects;
I.e. A data source (a.k.a. a JDBC resource) provides applications with the means of connecting to a database. Applications get a database connection from a connection pool by looking up a data source using the Java Naming and Directory Interface (JNDI) and then requesting a connection. The connection pool associated with the data source provides the connection for the application.
You can create connection pools and data sources directly on the GlassFish server using the GlassFish Administration Console, whoever If you use NetBeans, you can use the IDEs "GlassFish JDBC Resource wizard" to accomplish this, see an example here.
- JNDI API (Java Naming and Directory Interface)[4,9]: provides a uniform way for applications to find and access resources (ex. the JDBC Data Source relies on JNDI). For more information, see: The JNDI Tutorial; JNDI Glossary; The JDBC documentation also has some good examples of the JNDI usage - Connecting with DataSource Objects;
- JSP Implicit Objects: Implicit objects in jsp are the objects that are created by the container automatically and the container makes them available to the developers, the developer do not need to create them explicitly. These objects may be accessed as built-in variables via scripting elements and can also be accessed programmatically by JavaBeans and Servlets. Check this pages to see a list of JSP implicit objects, Implicit Objects (a great site with examples), official JavaEE 55 tutorial implicit objects;
- JSTL (JavaServer Pages Standard Tag Library) [4,5]:
Qual o problema?
Dificuldade de construir páginas JSPs bem organizadas internamente; Páginas JSPs com muito código Java; Web designers não sabem programar em Java; Problemas na interação entre desenvolvedores e web designers.
O que queremos?
Criar páginas dinâmicas bastante complexas sem escrever código Java dentro delas; Fornecer tags que tornem fáceis tarefas que exigiriam várias linhas de código Java, como formatação de números e datas seguindo configurações regionais do usuário; Facilitar a interação entre desenvolvedores e web designers.
Qual a solução?
Utilizar JSTL.
JSTL JSTL consiste em uma coleção de bibliotecas, tendo cada uma um propósito bem definido, que permitem escrever páginas JSPs sem código Java, aumentando assim a legibilidade do código e a interação entre desenvolvedores e web designers. Uma página JSTL é uma página JSP contendo um conjunto de tags JSTLs. Cada tag realiza um determinado tipo de processamento (equivalente a código Java dentro de JSP). Cada tag JSTL, faz parte uma biblioteca JSTL. Uma página JSTL pode utilizar várias bibliotecas JSTLs.
There are 4 area libraries that provide basic functionality, - core: common, structural tasks such as iterators and conditionals for handling flow control
- fmt: internationalization and localization message formatting
- sql: simple database access
- xml: handling of XML content
- Managed Bean: "In a typical JavaServer Faces application, each page of the application connects to a managed bean. The managed bean defines the methods and properties that are associated with the components." [11]
A typical JavaServer Faces application includes one or more managed beans, each of which can be associated with the components used in a particular page. A managed bean is created with a constructor with no arguments, a set of properties, and a set of methods that perform functions for a component. Each of the managed bean properties can be bound to one of the following:
- A component value
- A component instance
- A converter instance
- A listener instance
- A validator instance
The most common functions that managed bean methods perform include the following:
- Validating a component’s data
- Handling an event fired by a component
- Performing processing to determine the next page to which the application must navigate
- Multitiered Applications: In a multi-tiered application, the functionality of the application is separated into isolated functional areas, called tiers. Typically, multi-tiered applications have:
- a client tier: consists of a client program that makes requests to the middle tier. This client programs can be a web browser, a standalone application, or other servers, and they run on a different machine from the Java EE server;
- a middle tier: this tier's business functions handle client requests and process application data storing it in a permanent datastore in the data tier. Java EE application development concentrates on the middle tier to make enterprise application management easier, more robust, and more secure;
- the data tier (often called the EIS - Enterprise Information Systems tier): permanent datastore, like database servers, enterprise resource planning systems, and other legacy data sources, like mainframes.
- Web Tier: consists of components that handle the interaction between clients and the business tier. Its primary tasks are the following:
- Dynamically generate content in various formats for the client.
- Collect input from users of the client interface and return appropriate results from the components in the business tier.
- Control the flow of screens or pages on the client.
- Maintain the state of data for a user's session.
- Perform some basic logic and hold some data temporarily in JavaBeans components.
- There are distinct Java EE technologies used in each tier:
- Java EE Technologies Used in the Web Tier:
- Servlets: Java programming language classes that dynamically process requests and construct responses, usually for HTML pages
- JavaServer Faces technology: A user-interface component framework for web applications that allows you to include UI components (such as fields and buttons) on a page, convert and validate UI component data, save UI component data to server-side data stores, and maintain component state.
- JavaServer Faces Facelets technology: Facelets applications are a type of JavaServer Faces applications that use XHTML pages rather than JSP pages.
- Expression Language: A set of standard tags used in JSP and Facelets pages to refer to Java EE components.
- JavaServer Pages (JSP): Text-based documents that are compiled into servlets and define how dynamic content can be added to static pages, such as HTML pages.
- JavaServer Pages Standard Tag Library: A tag library that encapsulates core functionality common to JSP pages
- JavaBeans Components: Objects that act as temporary data stores for the pages of an application
- Enterprise JavaBeans (enterprise bean) components
- JAX-RS RESTful web services
- JAX-WS web service endpoints
- Java Persistence API entities
- The Java Database Connectivity API (JDBC)
- The Java Persistence API
- The Java EE Connector Architecture
- The Java Transaction API (JTA)
- Persistence Unit: provide the container with information about the data source and how the entities are managed;
A persistence unit is a collection of entity classes that exist in an application and is defined by a persistence.xml configuration file, which is read by your persistence provider (to define for example the data source). In NetBeans the persistence unit (persistence.xml) exists under the Configuration Files node. To create the persistence unit in NetBeans go to New -> Persistence -> Entity Classes from DataBase (or other), in the wizard check the option to "create Persistence Unit" [14]
- Port [8]: may refer to (see) Proxy;
- Properties (object properties): consists of a private data field and a set of accessor methods (i.e. A property is a field that has corresponding getter and setter methods);
- Proxy (in webservices)[8]: a client creates a proxy (a local object representing the service) and then simply invokes methods on the proxy; In Java this proxy is also known as a port.
- Serialization: Object serialization means converting an object into a data stream and writing it to storage. Any applet, application, or tool that uses that object can then "reconstitute" it by deserialization. The object is then restored to its original state.
For example, a Java application can serialize a Frame window on a Microsoft Windows machine, the serialized file can be sent with e-mail to a Solaris machine, and then a Java application can restore the Frame window to the exact state which existed on the Microsoft Windows machine.
Any applet, application, or tool that uses that bean can then "reconstitute" it by deserialization.
All beans must persist. To persist, your beans must support serialization by implementing either the java.io.Serializable (in the API reference documentation) interface, or the java.io.Externalizable (in the API reference documentation) interface. These interfaces offer you the choices of automatic serialization and customized serialization. If any class
- Servlet: A Java servlet is a web component that responds to HTTP requests. A servlet is a Java class used to extend the capabilities of servers that host applications accessed by means of a request-response programming model. The server passes service requests to the servlet through the standard interface javax.servlet, which every servlet must implement. Although servlets can respond to any type of request, they are commonly used to extend the applications hosted by web servers. For such applications, Java Servlet technology defines HTTP-specific servlet classes.
In addition to producing content, servlets have several features that support application structure:
- Listener interfaces: A developer can create classes that respond to events in a servlet’s lifecycle by implementing listener interfaces.
- Servlet Filters: A servlet can also be extended by one or more servlet filters, which are reusable classes that wrap calls to a servlet’s service method, transforming the request or the response. Servlet filters can be organized into filter chains that perform successive transformations on servlet requests or responses. [16, pag. 79]
In the Web tier, the question of whether to use JSP pages or servlets comes up repeatedly. JSP technology is intended for application user interface components, while Java Servlets are preferred for request processing and application control logic. Servlets and JSP pages work together to provide dynamic content from the Web tier. [15]
The servlet API provides a simple interface for handling incoming GET and POST requests and for extracting any parameters sent along with the requests.
The javax.servlet and javax.servlet.http packages provide interfaces and classes for writing servlets. All servlets must implement the Servlet interface, which defines lifecycle methods. When implementing a generic service, you can use or extend the GenericServlet class provided with the Java Servlet API. The HttpServlet class provides methods, such as doGet and doPost, for handling HTTP-specific services.
NetBeans has a template for servlets: Right Click your project node -> New -> Servlet. This template already implements doGet and doPost for you;
- Web Resources: In the Java EE architecture, web components and static web content files, such as images, are called web resources;
- Web Module: is the smallest deployable and usable unit of web resources. A Java EE web module corresponds to a web application as defined in the Java Servlet specification.
In addition to web components and web resources, a web module can contain other files:
- Server-side utility classes, such as shopping carts
- Client-side classes, such as applets and utility classes
A web module has a specific structure. The top-level directory of a web module is the document root of the application. The document root is where XHTML pages, client-side classes and archives, and static web resources, such as images, are stored. You can also create application-specific subdirectories (that is, package directories) in either the document root or the WEB-INF/classes/ directory.
A web module can be deployed as an unpacked file structure or can be packaged in a JAR file known as a Web Archive (WAR) file. Because the contents and use of WAR files differ from those of JAR files, WAR file names use a .war extension. The web module just described is portable; you can deploy it into any web container that conforms to the Java Servlet specification. - Web Components: in the Java EE platform, web components provide the dynamic extension capabilities for a web server. Web components can be:
- Java servlets;
- web pages implemented with JavaServer Faces technology;
- web service endpoints;
- or JSP pages
Although servlets and Java Server Faces and Facelets pages can be used to accomplish similar things, each has its own strengths. - Servlets are Java programming language classes that dynamically process requests and construct responses. Servlets are best suited for service-oriented applications (web service endpoints can be implemented as servlets) and the control functions of a presentation-oriented application, such as dispatching requests and handling nontextual data;
- On the other hand Java technologies, such as JavaServer Faces and Facelets, are used for building interactive web applications. (Frameworks can also be used for this purpose.) Java Server Faces and Facelets pages are more appropriate for generating text-based markup, such as XHTML, and are generally used for presentation–oriented applications.
- Web Service: Web services are client and server applications that communicate over the World Wide Web’s (WWW) HyperText Transfer Protocol (HTTP). As described by the World Wide Web Consortium (W3C), web services provide a standard means of interoperating between software applications running on a variety of platforms and frameworks. Web services are characterized by their great interoperability and extensibility, as well as their machine-processable descriptions, thanks to the use of XML. Web services can be combined in a loosely coupled way to achieve complex operations. Programs providing simple services can interact with each other to deliver sophisticated added-value services.
- XML: The Java language offers portable code, XML provides portable data.
References:
[0] - Java EE FAQ (a great resource of info);[1] - Differences between Java EE and Java SE;
[2] - Overview of Enterprise Applications
[3] - What is enterprise application?
[4] - Creating a Simple Web Application Using a MySQL Database
[5] - Biblioteca Padrão de Tags JSP
[6] - Beginning Java™ EE 6 Platform with GlassFish™ 3 From Novice to Professional, Antonio Goncalves, Apress, 2009, ISBN: 978-1-4302-1955-2
[7] - Getting Started with Java EE 6 Applications
[8] - Creating a Simple Web Service and Clients with JAX-WS
[9] - Accessing Enterprise Beans
[10] - Using Bean Validation
[11] - Developing a Simple Facelets Application
[12] - The NetBeans E-commerce Tutorial - Introduction
[13] - New to Java Programming Center - Unraveling Java Terminology
[14] - The NetBeans E-commerce Tutorial - Adding Entity Classes and Session Beans
[15] - Designing Enterprise Applications with the J2EETM Platform, Second Edition
[16] - BOOK: Designing Enterprise Applications with the J2EE Platform, Second Edition (free pdf download)
Sem comentários:
Enviar um comentário