Top Banner

of 234

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • 1 - java platform, enterprise edition

    1 - JAVA PLATFORM, ENTERPRISE EDITION

    1.1 the state of java EE

    The Java EE 7 (released in august 2013) is the current Java Enterprise Edition specification. Compared to the previous specification, Java EE 7 introduces several new features:

    New technologies, including the following:

    Batch Applications for the Java Platform

    Concurrency Utilities for Java EE

    Java API for JSON Processing (JSON-P)

    Java API for WebSocket

    New features for Enterprise JavaBeans ( EJB) components (see Enterprise JavaBeans Technology for details)

    New features for servlets (see Java Servlet Technology for details)

    New features for JavaServer Faces components (see JavaServer Faces Technology for details)

    New features for the Java Message Service (JMS) (see Java Message Service API for details)

    The next release is Java EE 8 and is scheduled for Q3 2016. The state of the Java EE 8 release can be found in a draft of the release attached to the link - https://java.net/projects/javaee-spec/lists/users/archive/2014-05/message/0

    Novelties expected in the forthcoming release:

    better support for HTML5

    support for the emerging HTTP 2.0 standard

    enhanced simplification and managed bean integration

    improved infrastructure for applications running in the cloud.

    1.2 the application model

    The application model starts with the Java programming language and the Java Virtual Machine. This combination provides high portability, scalability and developing efficiency.

    Java EE is designed to support applications that implement enterprise services for customers, employees, suppliers, partners, and others who make demands on or contributions to the enterprise. Such applications are inherently complex, potentially accessing data from a variety of sources and distributing applications to a variety of clients.

    To better control and manage these applications, the business functions to support these varioususers are conducted in the middle tier. The middle tier is typically run on dedicated server hardwareand has access to the full services of the enterprise.

    The Java EE application model defines an architecture for implementing services as multi-tier

    1

  • 1 - java platform, enterprise edition

    applications that deliver the scalability, accessibility, and manageability needed by enterprise-level applications. This model partitions the work needed to implement a multi-tier service into two parts:the business and presentation logic to be implemented by the developer, and the standard system services provided by the Java EE platform. The developer can rely on the platform to provide solutions for the hard systems-level problems of developing a multi-tier service.

    1.3 distributed multitiered applications

    The Java EE platform uses a distributed multitiered application model for enterprise applications. Application logic is divided into components according to function, and the various application components that make up a Java EE application are installed on different machines depending on the tier in the multitiered Java EE environment to which the application component belongs. Figure 1.1 shows generic multitiered Java EE applications divided into the tiers describedin the list below. The Java EE application parts shown in figure 1.1 are presented in the Java EE components section.

    client-tier components run on the client machine.

    web-tier components run on the Java EE server. business-tier components run on the Java EE server.

    enterprise information system (EIS)-tier software runs on the EIS server

    Figure 1.1 Distributed multitiered applications

    Although a Java EE application can consist of the three or four tiers shown in figure 1.1, Java EE

    2

  • 1 - java platform, enterprise edition

    multitiered applications are generally considered to be three-tiered applications because they are distributed over three locations: client machines, the Java EE server machine, and the database or legacy machines at the back end. Three-tiered applications that run in this way extend the standardtwo-tiered client and server model by placing a multithreaded application server between the client application and back-end storage.

    1.4 java EE components

    Java EE applications are made up of components. A Java EE component is a self-contained functional software unit that is assembled into a Java EE application with its related classes and files and that communicates with other components.

    The Java EE specification defines the following Java EE components:

    Application clients and applets are components that run on the client.

    Java Servlet, JavaServer Faces, and JavaServer Pages (JSP) technology components areweb components that run on the server.

    Enterprise JavaBeans (EJB) components (enterprise beans) are business components that run on the server.

    Java EE components are written in the Java programming language and are compiled in the same way as any program in the language. The difference between Java EE components and standard Java classes is that Java EE components are assembled into a Java EE application, areverified to be well formed and in compliance with the Java EE specification, and are deployed to production, where they are run and managed by the Java EE server.

    1.5 java EE Clients

    A Java EE client can be a web client or an application client.

    1.5.1 Web Clients A web client consists of two parts: (1) dynamic web pages containing various types of markup

    language (HTML, XML, and so on), which are generated by web components running in the web tier, and (2) a web browser, which renders the pages received from the server.

    A web client is sometimes called a thin client. Thin clients usually do not query databases, execute complex business rules, or connect to legacy applications. When you use a thin client, such heavyweight operations are off-loaded to enterprise beans executing on the Java EE server, where they can leverage the security, speed, services, and reliability of Java EE server-side technologies.

    1.5.2 Applets A web page received from the web tier can include an embedded applet. An applet is a small

    client application written in the Java programming language that executes in the Java virtual machine installed in the web browser. However, client systems will likely need the Java Plug-in andpossibly a security policy file in order for the applet to successfully execute in the web browser.

    1.5.3 Application Clients An application client runs on a client machine and provides a way for users to handle tasks that

    require a richer user interface than can be provided by a markup language. It typically has a

    3

  • 1 - java platform, enterprise edition

    graphical user interface (GUI) created from the Swing or the Abstract Window Toolkit (AWT) API, but a command-line interface is certainly possible.

    Application clients directly access enterprise beans running in the business tier. However, if application requirements warrant it, an application client can open an HTTP connection to establishcommunication with a servlet running in the web tier. Application clients written in languages other than Java can interact with Java EE 7 servers, enabling the Java EE 7 platform to interoperate withlegacy systems, clients, and non-Java languages.

    1.5.4 The JavaBeans Component Architecture The server and client tiers might also include components based on the JavaBeans component

    architecture to manage the data flow between an application client or applet and components running on the Java EE server, or between server components and a database. JavaBeans components are not considered Java EE components by the Java EE specification.

    JavaBeans components have properties and have get and set methods for accessing the properties. JavaBeans components used in this way are typically simple in design and implementation but should conform to the naming and design conventions outlined in the JavaBeans component architecture.

    1.5.5 Java EE Server Communications Figure 1.2 shows the various elements that can make up the client tier. The client communicates

    with the business tier running on the Java EE server either directly or, as in the case of a client running in a browser, by going through JSP pages or servlets running in the web tier. Your Java EEapplication uses a thin browser-based client or thick application client. In deciding which one to use, you should be aware of the trade-offs between keeping functionality on the client and close to the user and off-loading as much functionality as possible to the server. The more functionality you off-load to the server, the easier it is to distribute, deploy, and manage the application; however, keeping more functionality on the client can make for a better perceived user experience.

    Figure 1.2 Server communication

    4

  • 1 - java platform, enterprise edition

    1.6 web components

    Java EE web components are either servlets or pages created using JSP technology (JSP pages) and/or Java Server Faces technology. Servlets are Java programming language classes that dynamically process requests and construct responses. JSP pages are text-based documents that execute as servlets but allow a more natural approach to creating static content. Java Server Faces technology builds on servlets and JSP technology and provides a user interface component framework for web applications.

    Static HTML pages and applets are bundled with web components during application assembly but are not considered web components by the Java EE specification. Server-side utility classes can also be bundled with web components and are not considered web components.

    The web tier, like the client tier, might include a JavaBeans component to manage the user input and send that input to enterprise beans running in the business tier for processing.

    1.7 business components

    Business code, which is logic that solves or meets the needs of a particular business domain such as banking, retail, or finance, is handled by enterprise beans running in the business tier. Figure 1.3 shows how an enterprise bean receives data from client programs, processes it (if necessary), and sends it to the enterprise information system tier for storage. An enterprise bean also retrieves data from storage, processes it (if necessary), and sends it back to the client program.

    Figure 1.3 Web, Business and EIS Tiers

    5

  • 1 - java platform, enterprise edition

    1.8 enterprise information system tier

    The enterprise information system tier handles EIS software and includes enterprise infrastructure systems such as enterprise resource planning (ERP), mainframe transaction processing, database systems, and other legacy information systems. For example, Java EE application components might need access to enterprise information systems for database connectivity.

    1.9 java EE Containers

    Normally, thin-client multitiered applications are hard to write because they involve many lines of intricate code to handle transaction and state management, multithreading, resource pooling, and other complex low-level details. The component-based and platform-independent Java EE architecture makes Java EE applications easy to write because business logic is organized into reusable components. In addition, the Java EE server provides underlying services in the form of a container for every component type. Because you do not have to develop these services yourself, you are free to concentrate on solving the business problem at hand.

    1.9.1 Container Services Containers are the interface between a component and the low-level platform-specific

    functionality that supports the component. Before a web, enterprise bean, or application client component can be executed, it must be assembled into a Java EE module and deployed into its container.

    The assembly process involves specifying container settings for each component in the Java EE application and for the Java EE application itself. Container settings customize the underlying support provided by the Java EE server, including services such as security, transaction management, Java Naming and Directory Interface (JNDI) lookups, and remote connectivity. Here are some of the highlights:

    The Java EE security model lets you configure a web component or enterprise bean so that system resources are accessed only by authorized users.

    The Java EE transaction model lets you specify relationships among methods that make up a single transaction so that all methods in one transaction are treated as a single unit.

    JNDI lookup services provide a unified interface to multiple naming and directory services in the enterprise so that application components can access these services.

    The Java EE remote connectivity model manages low-level communications between clients and enterprise beans. After an enterprise bean is created, a client invokes methods on it as if it were in the same virtual machine.

    Because the Java EE architecture provides configurable services, application components withinthe same Java EE application can behave differently based on where they are deployed. For example, an enterprise bean can have security settings that allow it a certain level of access to database data in one production environment and another level of database access in another production environment.

    The container also manages nonconfigurable services such as enterprise bean and servlet life cycles, database connection resource pooling, data persistence, and access to the Java EE platform APIs.

    6

  • 1 - java platform, enterprise edition

    1.9.2 Container Types The deployment process installs Java EE application components in the Java EE containers

    illustrated in figure 1.4.

    Figure 1.4 Java EE Server and Containers

    Java EE server - the runtime portion of a Java EE product. A Java EE server provides EJB and web containers.

    Enterprise JavaBeans (EJB) container - manages the execution of enterprise beans for Java EE applications. Enterprise beans and their container run on the Java EE server.

    Web container - manages the execution of JSP page and servlet components for Java EE applications. Web components and their container run on the Java EE server.

    Application client container - manages the execution of application client components. Application clients and their container run on the client.

    Applet container - manages the execution of applets. Consists of a web browser and Java Plug-in running on the client together.

    1.10 support for web services

    Web services are web-based enterprise applications that use open, XML-based standards and transport protocols to exchange data with calling clients. The Java EE platform provides the XML APIs and tools you need to quickly design, develop, test, and deploy web services and clients that fully interoperate with other web services and clients running on Java-based or non-Java-based platforms.

    7

  • 1 - java platform, enterprise edition

    To write web services and clients with the Java EE XML APIs, all you do is pass parameter data to the method calls and process the data returned; or for document-oriented web services, you send documents containing the service data back and forth. No low-level programming is needed because the XML API implementations do the work of translating the application data to and from an XML-based data stream that is sent over the standardized XML-based transport protocols. These XML-based standards and protocols are introduced in the following sections.

    The translation of data to a standardized XML-based data stream is what makes web services and clients written with the Java EE XML APIs fully interoperable. This does not necessarily mean that the data being transported includes XML tags because the transported data can itself be plain text, XML data, or any kind of binary data such as audio, video, maps, program files, computer-aided design (CAD) documents and the like. The next section introduces XML and explains how parties doing business can use XML tags and schemas to exchange data in a meaningful way.

    1.10.1 XML XML is a cross-platform, extensible, text-based standard for representing data. When XML data

    is exchanged between parties, the parties are free to create their own tags to describe the data, setup schemas to specify which tags can be used in a particular kind of XML document, and use XML stylesheets to manage the display and handling of the data.

    For example, a web service can use XML and a schema to produce price lists, and companies that receive the price lists and schema can have their own stylesheets to handle the data in a way that best suits their needs. Here are examples:

    One company might put XML pricing information through a program to translate the XML toHTML so that it can post the price lists to its intranet.

    A partner company might put the XML pricing information through a tool to create a marketing presentation.

    Another company might read the XML pricing information into an application for processing.

    1.10.2 SOAP Transport Protocol Client requests and web service responses are transmitted as Simple Object Access Protocol

    (SOAP) messages over HTTP to enable a completely interoperable exchange between clients and web services, all running on different platforms and at various locations on the Internet. HTTP is a familiar request-and response standard for sending messages over the Internet, and SOAP is an XML-based protocol that follows the HTTP request-and-response model.

    The SOAP portion of a transported message handles the following:

    Defines an XML-based envelope to describe what is in the message and how to process the message

    Includes XML-based encoding rules to express instances of application-defined data types within the message

    Defines an XML-based convention for representing the request to the remote service and the resulting response

    1.10.3 WSDL Standard Format The Web Services Description Language (WSDL) is a standardized XML format for describing

    network services. The description includes the name of the service, the location of the service, and ways to communicate with the service. WSDL service descriptions can be stored in UDDI registriesor published on the web (or both). The Sun Java System Application Server Platform Edition 8 provides a tool for generating the WSDL specification of a web service that uses remote procedurecalls to communicate with clients.

    8

  • 1 - java platform, enterprise edition

    1.10.4 UDDI and ebXML Standard Formats Other XML-based standards, such as Universal Description, Discovery and Integration (UDDI)

    and ebXML, make it possible for businesses to publish information on the Internet about their products and web services, where the information can be readily and globally accessed by clients who want to do business.

    1.11 java EE 7 core technologies and APIs

    Figure 1.5 illustrates the availability of the Java EE 6 platform APIs in each Java EE container type. The following sections give a brief summary of the technologies required by the Java EE platform, and the APIs used in Java EE applications.

    Figure 1.5 Java EE Platform APIs

    For Java EE 7, the following technologies have to be added:

    At Application Client Container level : JSON-P

    At Web container level:

    WebSocket

    Concurrency utilities

    Batch

    JSON-P

    At EJB container level:

    Concurrency utilities

    Batch

    JSON-P

    9

  • 1 - java platform, enterprise edition

    1.11.1 Enterprise JavaBeans Technology An Enterprise JavaBeans (EJB) component, or enterprise bean, is a body of code having fields

    and methods to implement modules of business logic. You can think of an enterprise bean as a building block that can be used alone or with other enterprise beans to execute business logic on the Java EE server.

    There are two kinds of enterprise beans: session beans and message-driven beans. A session bean represents a transient conversation with a client. When the client finishes executing, the session bean and its data are gone. A message-driven bean combines features of a session bean and a message listener, allowing a business component to receive messages asynchronously. Commonly, these are Java Message Service (JMS) messages.

    In Java EE 5, entity beans have been replaced by Java persistence API entities. An entity represents persistent data stored in one row of a database table. If the client terminates, or if the server shuts down, the persistence manager ensures that the entity data is saved.

    1.11.2 Java Servlet Technology Java servlet technology lets you define HTTP-specific servlet classes. A servlet class extends

    the capabilities of servers that host applications that are accessed by way of a request-response programming model. Although servlets can respond to any type of request, they are commonly used to extend the applications hosted by web servers.

    In Java EE 7, some of the new Servlet features include:

    Non-blocking I/O

    HTTP protocol upgrade

    Java EE 7 requires Servlet 3.1.

    1.11.3 JavaServer Pages Technology JavaServer Pages (JSP) technology lets you put snippets of servlet code directly into a text-

    based document. A JSP page is a text-based document that contains two types of text: static data (which can be expressed in any text-based format such as HTML, WML, and XML) and JSP elements, which determine how the page constructs dynamic content.

    Java EE 7 requires JSP 2.3 but recommends the use of Facelets as the display technology innew applications.

    1.11.4 JavaServer Pages Standard Tag Library The JavaServer Pages Standard Tag Library (JSTL) encapsulates core functionality common to

    many JSP applications. Instead of mixing tags from numerous vendors in your JSP applications, you employ a single, standard set of tags. This standardization allows you to deploy your applications on any JSP container that supports JSTL and makes it more likely that the implementation of the tags is optimized.

    JSTL has iterator and conditional tags for handling flow control, tags for manipulating XML documents, internationalization tags, tags for accessing databases using SQL, and commonly used functions.

    Java EE 7 requires JSTL 1.2.

    1.11.5 JavaServer Faces JavaServer Faces technology is a user interface framework for building web applications. The

    main components of JavaServer Faces technology are as follows:

    A GUI component framework.

    10

  • 1 - java platform, enterprise edition

    A flexible model for rendering components in different kinds of HTML or different markup languages and technologies. A Renderer object generates the markup to render the component and converts the data stored in a model object to types that can be representedin a view.

    A standard RenderKit for generating HTML/4.01 markup.The following features support the GUI components:

    Input validation

    Event handling

    Data conversion between model objects and components

    Managed model object creation

    Page navigation configuration

    All this functionality is available via standard Java APIs and XML-based configuration files.

    New features in Java EE 7:

    HTML 5 friendly markup

    Faces Flows

    Resource Library contracts

    Java EE 7 requires JFS 2.2 and Expression Language 3.0.

    1.11.6 Java Message Service API The Java Message Service (JMS) API is a messaging standard that allows Java EE application

    components to create, send, receive, and read messages. It enables distributed communication that is loosely coupled, reliable, and asynchronous.

    Java EE 7 requires JMS 2.0.

    1.11.7 Java Transaction API The Java Transaction API (JTA) provides a standard interface for demarcating transactions. The

    Java EE architecture provides a default auto commit to handle transaction commits and rollbacks. An auto commit means that any other applications that are viewing data will see the updated data after each database read or write operation. However, if your application performs two separate database access operations that depend on each other, you will want to use the JTA API to demarcate where the entire transaction, including both operations, begins, rolls back, and commits.

    1.11.8 JavaMail API Java EE applications use the JavaMail API to send email notifications. The JavaMail API has two

    parts: an application-level interface used by the application components to send mail, and a serviceprovider interface. The Java EE platform includes JavaMail with a service provider that allows application components to send Internet mail.

    1.11.9 JavaBeans Activation Framework The JavaBeans Activation Framework (JAF) is included because JavaMail uses it. JAF provides

    standard services to determine the type of an arbitrary piece of data, encapsulate access to it, discover the operations available on it, and create the appropriate JavaBeans component to perform those operations.

    11

  • 1 - java platform, enterprise edition

    1.11.10 Java API for WebSocketWebSocket is an application protocol that provides full-duplex communications between two

    peers over TCP. The Java API for WebSocket enables Java EE applications to create endpoints using annotations that specify the configuration parameters of the endpoint and designate its lifecycle callback methods.

    The WebSocket API is new to the Java EE 7 platform. The Java EE 7 platform requires Java APIfor WebSocket 1.0.

    1.11.11 JSON processingJSON is a text-based data exchange format derived from JavaScript that is used in web services

    and other connected applications. The Java API for JSON Processing (JSON-P) enables Java EE applications to parse, transform, and query JSON data using the object model or the streaming model.

    JSON-P is new to the Java EE 7 platform. The Java EE 7 platform requires JSON-P 1.0.

    1.11.12 Java API for XML Processing The Java API for XML Processing (JAXP), part of the Java SE platform, supports the processing

    of XML documents using Document Object Model (DOM), Simple API for XML (SAX), and Extensible Stylesheet Language Transformations (XSLT). JAXP enables applications to parse and transform XML documents independent of a particular XML processing implementation.

    JAXP also provides namespace support, which lets you work with schemas that might otherwise have naming conflicts. Designed to be flexible, JAXP lets you use any XML-compliant parser or XSL processor from within your application and supports the W3C schema. You can find information on the W3C schema at this URL: http://www.w3.org/XML/Schema.

    1.11.13 Java API for XML Web Services (JAX-WS) The JAX-WS specification provides support for web services that use the JAXB API for binding

    XML data to Java objects. The JAX-WS specification defines client APIs for accessing web services as well as techniques for implementing web service endpoints. The Web Services for J2EE specification describes the deployment of JAX-WS-based services and clients. The EJB and servlet specifications also describe aspects of such deployment. It must be possible to deploy JAX-WS-based applications using any of these deployment models.

    The JAX-WS specification describes the support for message handlers that can process message requests and responses. In general, these message handlers execute in the same container and with the same privileges and execution context as the JAX-WS client or endpoint component with which they are associated. These message handlers have access to the same JNDI java:comp/env namespace as their associated component. Custom serializers and deserializers, if supported, are treated in the same way as message handlers.

    1.11.14 Java API for RESTful Web Services (JAX-RS)The Java API for RESTful Web Services (JAX-RS) defines APIs for the development of Web

    services built according to the Representational State Transfer (REST) architectural style. A JAX-RS application is a web application that consists of classes that are packaged as a servlet in a WAR file along with required libraries.

    The JAX-RS API is new to the Java EE 6 platform.

    1.11.15 Java Architecture for XML Binding (JAXB) The Java Architecture for XML Binding (JAXB) provides a convenient way to bind an XML

    schema to a representation in Java language programs. JAXB can be used independently or in combination with JAX-WS, where it provides a standard data binding for web service messages. All

    12

  • 1 - java platform, enterprise edition

    Java EE application client containers, web containers, and EJB containers support the JAXB API.

    1.11.16 SOAP with Attachments API for Java The SOAP with Attachments API for Java (SAAJ) is a low-level API on which JAX-WS and JAXR

    depend. SAAJ enables the production and consumption of messages that conform to the SOAP 1.1 specification and SOAP with Attachments note. Most developers do not use the SAAJ API, instead using the higher-level JAX-WS API.

    1.11.17 Java API for XML Registries The Java API for XML Registries (JAXR) lets you access business and general-purpose

    registries over the web. JAXR supports the ebXML Registry and Repository standards and the emerging UDDI specifications. By using JAXR, developers can learn a single API and gain access to both of these important registry technologies.

    Additionally, businesses can submit material to be shared and search for material that others have submitted. Standards groups have developed schemas for particular kinds of XML documents; two businesses might, for example, agree to use the schema for their industry's standard purchase order form. Because the schema is stored in a standard business registry, both parties can use JAXR to access it.

    1.11.18 J2EE Connector Architecture The J2EE Connector architecture is used by tools vendors and system integrators to create

    resource adapters that support access to enterprise information systems that can be plugged in to any Java EE product. A resource adapter is a software component that allows Java EE application components to access and interact with the underlying resource manager of the EIS. Because a resource adapter is specific to its resource manager, typically there is a different resource adapter for each type of database or enterprise information system.

    The J2EE Connector architecture also provides a performance-oriented, secure, scalable, and message-based transactional integration of Java EE-based web services with existing EISs that can be either synchronous or asynchronous. Existing applications and EISs integrated through the J2EE Connector architecture into the Java EE platform can be exposed as XML-based web services by using JAX-WS and Java EE component models. Thus JAX-WS and the J2EE Connector architecture are complementary technologies for enterprise application integration (EAI) and end-to-end business integration.

    1.11.19 Java Database Connectivity API The Java Database Connectivity (JDBC) API lets you invoke SQL commands from Java

    programming language methods. You use the JDBC API in an enterprise bean when you have a session bean access the database. You can also use the JDBC API from a servlet or a JSP page to access the database directly without going through an enterprise bean.

    The JDBC API has two parts: an application-level interface used by the application components to access a database, and a service provider interface to attach a JDBC driver to the Java EE platform.

    1.11.20 Java Persistence API The Java Persistence API is a new all Java standards based solution for persistence.

    Persistence uses an object-relational mapping approach to bridge the gap between an object oriented model and a relational database. Java Persistence consists of three areas:

    The Java Persistence API

    The query language

    Object/relational mapping metadata

    13

  • 1 - java platform, enterprise edition

    1.11.21 Java Naming and Directory Interface The Java Naming and Directory Interface (JNDI) provides naming and directory functionality,

    enabling applications to access multiple naming and directory services, including existing naming and directory services such as LDAP (Lightweight Directory Access Protocol), NDS (Novell Directory Services), DNS, and NIS (Network Information services). It provides applications with methods for performing standard directory operations, such as associating attributes with objects and searching for objects using their attributes. Using JNDI, a Java EE application can store and retrieve any type of named Java object, allowing Java EE applications to coexist with many legacy applications and systems.

    Java EE naming services provide application clients, enterprise beans, and web components with access to a JNDI naming environment. A naming environment allows a component to be customized without the need to access or change the component's source code. A container implements the component's environment and provides it to the component as a JNDI naming context.

    A Java EE component can locate its environment naming context using JNDI interfaces. A component can create a javax.naming.InitialContext object and looks up the environmentnaming context in InitialContext under the name java:comp/env. A component's naming environment is stored directly in the environment naming context or in any of its direct or indirect subcontexts.

    A Java EE component can access named system-provided and user-defined objects. The names of system-provided objects, such as JTA UserTransaction objects, are stored in the environment naming context, java:comp/env. The Java EE platform allows a component to name user-defined objects, such as enterprise beans, environment entries, JDBC DataSource objects, and message connections. An object should be named within a subcontext of the naming environment according to the type of the object. For example, enterprise beans are named within the subcontext java:comp/env/ejb, and JDBC DataSource references in the subcontext java:comp/env/jdbc.

    1.11.22 Java Authentication and Authorization Service The Java Authentication and Authorization Service (JAAS) provides a way for a Java EE

    application to authenticate and authorize a specific user or group of users to run it.

    JAAS is a Java programming language version of the standard Pluggable Authentication Module (PAM) framework, which extends the Java Platform security architecture to support user-based authorization.

    1.11.23 Java Authorization Service Provider Contract for Containers (Java ACC)

    The Java ACC specification defines a contract between a Java EE application server and an authorization policy provider. All Java EE containers support this contract.

    The Java ACC specification defines java.security.Permission classes that satisfy the Java EE authorization model. The specification defines the binding of container access decisions tooperations on instances of these permission classes. It defines the semantics of policy providers that employ the new permission classes to address the authorization requirements of the Java EE platform, including the definition and use of roles.

    1.11.24 Java Authentication Service Provider Interface for Containers (JASPIC)

    The Java Authentication Service Provider Interface for Containers (JASPIC) specification definesa service provider interface (SPI) by which authentication providers that implement message authentication mechanisms may be integrated in client or server message processing containers or

    14

  • 1 - java platform, enterprise edition

    runtimes. Authentication providers integrated through this interface operate on network messages provided to them by their calling container. They transform outgoing messages so that the source of the message may be authenticated by the receiving container, and the recipient of the message may be authenticated by the message sender. They authenticate incoming messages and return totheir calling container the identity established as a result of the message authentication.

    1.11.25 Simplified Systems Integration The Java EE platform is a platform-independent, full systems integration solution that creates an

    open marketplace in which every vendor can sell to every customer. Such a marketplace encourages vendors to compete, not by trying to lock customers into their technologies but instead by trying to outdo each other in providing products and services that benefit customers, such as better performance, better tools, or better customer support.

    The Java EE 7 APIs enable systems and applications integration through the following:

    Unified application model across tiers with enterprise beans

    Simplified request-and-response mechanism with JSP pages and servlets

    Reliable security model with JAAS

    XML-based data interchange integration with JAXP, SAAJ, and JAX-WS

    Simplified interoperability with the J2EE Connector architecture

    Easy database connectivity with the JDBC API

    Enterprise application integration with message-driven beans and JMS, JTA, and JNDI

    1.12 java EE application assembly and deployment

    A Java EE application is packaged into one or more standard units for deployment to any Java EE platform-compliant system. Each unit contains:

    A functional component or components (such as an enterprise bean, JSP page, servlet, or applet)

    An optional deployment descriptor that describes its content

    Once a Java EE unit has been produced, it is ready to be deployed. Deployment typically involves using a platforms deployment tool to specify location-specific information, such as a list of local users that can access it and the name of the local database. Once deployed on a local platform, the application is ready to run.

    A Java EE application is delivered in an Enterprise Archive (EAR) file, a standard Java Archive (JAR) file with an .ear extension. Using EAR files and modules makes it possible to assemble a number of different Java EE applications using some of the same components. No extra coding is needed; it is only a matter of assembling (or packaging) various Java EE modules into Java EE EAR files.

    An EAR file contains Java EE modules and deployment descriptors. A deployment descriptor is an XML document with an .xml extension that describes the deployment settings of an application, a module, or a component. Because deployment descriptor information is declarative, itcan be changed without the need to modify the source code. At runtime, the Java EE server reads the deployment descriptor and acts upon the application, module, or component accordingly.

    15

  • 1 - java platform, enterprise edition

    Figure 1.6 EAR file structure

    There are two types of deployment descriptors: Java EE and runtime. A Java EE deployment descriptor is defined by a Java EE specification and can be used to configure deployment settingson any Java EE-compliant implementation. A runtime deployment descriptor is used to configureJava EE implementation-specific parameters. For example, the Sun Java System Application Server Platform Edition 9 runtime deployment descriptor contains information such as the context root of a web application, the mapping of portable names of an applications resources to the servers resources, and Application Server implementation-specific parameters, such as caching directives. The Application Server runtime deployment descriptors are named sun-moduleType.xml and are located in the same META-INF directory as the Java EE deployment descriptor.

    A Java EE module consists of one or more Java EE components for the same container type and one component deployment descriptor of that type. An enterprise bean module deployment descriptor, for example, declares transaction attributes and security authorizations for an enterprisebean. A Java EE module without an application deployment descriptor can be deployed as a stand-alone module.

    The four types of Java EE modules are as follows:

    EJB modules, which contain class files for enterprise beans and an EJB deployment descriptor. EJB modules are packaged as JAR files with a .jar extension.

    Web modules, which contain servlet class files, JSP files, supporting class files, GIF and HTML files, and a web application deployment descriptor. Web modules are packaged as JAR files with a .war (Web ARchive) extension.

    Application client modules, which contain class files and an application client deployment descriptor. Application client modules are packaged as JAR files with a .jar extension.

    Resource adapter modules, which contain all Java interfaces, classes, native libraries, and other documentation, along with the resource adapter deployment descriptor. Together, these implement the Connector architecture (see J2EE Connector Architecture) for a particular EIS. Resource adapter modules are packaged as JAR files with an .rar (resource adapter archive) extension.

    16

  • 1 - java platform, enterprise edition

    1.13 scripting versus application servers

    In this section we attempt to answer a recurrent question why bother with servlets, java server pages or java server faces when we can achieve faster the same results using a versatile languagelike PHP? Without ignoring its major qualities, let's point out some of weaknesses of PHP, which are inherent to its nature.

    PHP scripts are tied to a the web server and require writing explicit database queries to generatedynamic content. Even these queries are written in a way which is specific to a particular database engine. In PHP, the application programmer writes the SQL queries and embeds them directly into the script, mixing presentation and business logic in the process. No direct support is provided for the management of component pooling and lifecycle management, client session management, database connection pooling, persistence, transaction management, authentication, and access control. On the other hand, all these may be achieved through an application server.

    For those who want a deeper understanding of this debate, the following links may help.

    http://stiri.rol.ro/dezbatere-forum-la-link-academy-php-vs-java-820468.html

    http://www.cs.montana.edu/~tosun/phpvsjava.pdf

    http://shootout.alioth.debian.org/u32q/benchmark.php?test=all&lang=java&lang2=php

    http://raibledesigns.com/rd/entry/php_vs_java_which_is

    17

  • 2 - HTTP

    2 - HTTP

    2.1 what is http?

    HTTP stands for HyperText Transfer Protocol while hypertext means text contatining links to another text. HTTP was created by by Tim Berners-Lee in 1990 at CERN as a mean to store scientific data. It quickly evolved into the preferred communication protocol over the internet.

    The first oficial version HTTP 1.0 dates from 05/95 and is the object of RFC 1945 (www.apps.ietf.org/rfc/rfc1945.html). It is authored by Tim Berners-Lee, Roy Fielding and Henrik Nielsen.

    The second (and last, so far) version, namely HTTP 1.1, was the object of several RFCs, of which we mention RFC 2068 (01/97), RFC 2616 (06/99), RFC 2617 (06/99) and RFC 2774 (02/00).

    For a complete specification of the different HTTP versions, check the official HTTP site www.w3.org/Protocols . As a site for understanding how HTTP works, we recommend www.jmarshall.com/easy /http.

    The next version of the HTTP specification is HTTP 2.0 (or HTTP/2) and is scheduled to be released as an RFC at the beginning of 2015 (february).

    The working group for HTTP/2 hopes to address the following issues and goals:

    Negotiation mechanism that allows clients and servers to elect to use HTTP 1.1, 2.0, orpotentially other non-HTTP protocols.

    Maintain high-level similarity with HTTP 1.1 (for example with methods, status codes,header fields, and URIs, and most header fields)

    Decrease latency to improve page load speed in web browsers by considering:

    Data compression of HTTP headers

    Server push technologies

    Fixing the head-of-line blocking problem in HTTP 1

    Loading page elements in parallel over a single TCP connection

    Support common existing use cases of HTTP, such as desktop web browsers, mobile webbrowsers, web APIs, web servers at various scales, proxy servers, reverse proxy servers,firewalls, and content delivery networks

    2.2 the structure of http transactions

    HTTP follows the client server model. The client sends a request message to the server. The server answers with a response message. These messages may have different contents, but they also have some common structural elements, as follows:

    1. an initial line

    2. zero or more header lines

    3. a blank line (CR/LF)

    4. an optional message body

    18

  • 2 - HTTP

    Header1: value1

    ... Headern: valuen

    2.3 the initial request line

    Contains 3 elements, separated by spaces:

    a command (method) name (like GET, POST, HEAD, ...)

    a file specification (path) (the part of the URL after the host name)

    the HTTP version (usually, HTTP/1.0). Here is an example of an initial request line:

    GET /path/to/the/file/index.html HTTP/1.0

    2.4 http commands (methods)

    As of HTTP 1.1, there are 8 HTTP commands (methods) that are widely supported. Here is their list:

    1. GET

    2. HEAD

    3. POST

    4. CONNECT

    5. DELETE

    6. OPTIONS

    7. PUT

    8. TRACE

    Three other commands are listed, as well, in the HTTP 1.1 specification, but lack of support makes them obsolete. These commands are:

    LINK

    UNLINK

    PATCH

    The HEAD command is identical to the GET command in all respects but one. The only difference is that the response must not have a body. All the information requested is returned in the header section of the response.

    19

  • 2 - HTTP

    2.5 the GET and POST methods

    The GET method means retrieve whatever information (in the form of an entity) is identified by the Request-URI. If the Request-URI refers to a data-producing process, it is the produced data which shall be returned as the entity in the response and not the source text of the process, unless that text happens to be the output of the process.

    The POST method is used to request that the origin server accept the entity enclosed in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line. POST is designed to allow a uniform method to cover the following functions:

    - Annotation of existing resources;

    - Posting a message to a bulletin board, newsgroup, mailing list,

    or similar group of articles;

    - Providing a block of data, such as the result of submitting a

    form, to a data-handling process;

    - Extending a database through an append operation.

    The actual function performed by the POST method is determined by the server and is usually dependent on the Request-URI. The posted entity is subordinate to that URI in the same way that afile is subordinate to a directory containing it, a news article is subordinate to a newsgroup to which it is posted, or a record is subordinate to a database.

    The action performed by the POST method might not result in a resource that can be identified by a URI. In this case, either 200 (OK) or 204 (No Content) is the appropriate response status, depending on whether or not the response includes an entity that describes the result.

    2.6 differences between GET and POST

    1. The method GET is intended for getting (retrieving) data, while POST may involve anything, like storing or updating data, or ordering a product, or sending E-mail

    2. When used for form data submission, GET attaches this data to the URL of the request, after the ? character, as a sequence of name=value pairs, separated by the character & or ; On the other side, form data submitted by POST may be encoded either as above (using application/x-www-form-urlencoded content type), or in the message body, (encoded as multipart/form-data).

    3. A POST request requires an extra transmission to retrieve the message body, while a GET request allows data sent via the URL to be processed immediately.

    2.7 the initial response (status) line

    Contains 3 elements, separated by spaces (although the reason phrase may contain spaces, as

    20

  • 2 - HTTP

    well):

    the HTTP version of the response

    a response status code (a number)

    a response status reason phrase (a human readable response status) Here is an example of an initial response line:HTTP/1.0 404 Not Found

    2.8 the status code

    A three-digit integer, where the first digit identifies the general category of response:

    1xx indicates an informational message only

    2xx indicates success of some kind

    3xx redirects the client to another URL

    4xx indicates an error on the client's part

    5xx indicates an error on the server's part The most common status codes are:

    200 OK - the request succeeded, and the resulting resource (e.g. file or script output) is returned in the message body.

    404 Not Found - the requested resource doesn't exist.

    301 Moved Permanently

    302 Moved Temporarily

    303 See Other (HTTP 1.1 only) - the resource has moved to another URL (given by the Location: response header), and should be automatically retrieved by the client. This is often used by a CGI script to redirect the browser to an existing file.

    500 Server Error - an unexpected server error. The most common cause is a server-side script that has bad syntax, fails, or otherwise can't run correctly.

    A complete list of status codes is in the HTTP specification (the URL was mentioned in the firs section of this chapter) (section 9 for HTTP 1.0, and section 10 for HTTP 1.1).

    2.9 header lines

    A header line consists of two parts, header name and header value, separated a semicolon. TheHTTP 1.0 version specifies 16 headers, none of them mandatory, while the HTTP 1.1 version specifies 46 of them, out of which, one (Host) is mandatory. Although the header names are not case sensitive, header values are.

    A couple of examples of header lines:

    User-agent: Mozilla/3.0Gold

    Last-Modified: Fri, 31 Dec 1999 23:59:59 GMT

    Header lines which begin with spaces or tabs are parts of the previous header line.

    21

  • 2 - HTTP

    2.10 the message body

    An HTTP message may have a body of data sent after the header lines. The most common use of the message body is in a response, that is, where the requested resource is returned to the client, or perhaps explanatory text if there's an error. In a request, this is where user-entered data or uploaded files are sent to the server.

    If an HTTP message includes a body, the header lines of the message are used to describe the body. In particular,

    the Content-Type: header gives the MIME-type of the data in the body, such as text/html orimage/jpg.

    the Content-Length: header gives the number of bytes in the body.

    2.11 mime types/subtypes

    MIME stands for Multipurpose Internet Mail Extensions. Each extension consists of a type and a subtype. RFC 1521 (www.apps.ietf.org/rfc/rfc1521.html) defines 7 types and several subtypes, although the list of admissible subtypes is much longer.

    Here is the list of the seven types, together with the subtypes defined in this particular RFC.1. text, with subtype plain2. multipart, with subtypes mixed, alternative, digest, parallel3. message, with subtypes rfc822, partial, external-body4. application, with subtypes octet-stream, postscript5. image, with subtypes jpeg, gif6. audio, with subtype basic 7. video, with subtype mpeg

    2.12 an example of an http transaction

    To retrieve the file at the URL http://web.info.uvt.ro/path/file.html

    first open a socket to the host web.info.uvt.ro, port 80 (use the default port of 80 because none is specified in the URL). Then, send something like the following through the socket:

    GET /path/file.html HTTP/1.0

    From: [email protected]

    User-Agent: HTTPTool/1.0

    [blank line here]

    The server should respond with something like the following, sent back through the same socket:

    HTTP/1.0 200 OK

    22

  • 2 - HTTP

    Date: Fri, 31 Dec 1999 23:59:59 GMT

    Content-Type: text/html

    Content-Length: 1354

    Happy birthday!

    (more file contents)

    .

    .

    After sending the response, the server closes the socket.

    23

  • 3 - HTML

    3 - HTML

    3.1 what is html?

    HTML stands for HyperText Markup Language. HTML describes how text, images and other components are to be displayed in a browser, using a variety of tags and their related attributes.

    The first version of HTML, namely HTML 1.0, appeared in summer 1991 and was supported by the first popular web browser, Mosaic. The first official version HTML 2.0 - was approved as a standard in September 1995 (as RFC 1866 (http://www.apps.ietf.org/rfc/rfc1866.html) and was widely supported. A newer standard, HTML 3.2 (3.0 was not widely accepted) appeared a W3C recommendation in January 1997.

    Version 4.0 introduces the Cascading Style Sheets.

    The latest version of HTML as SGML application is 4.01. It is a revision of 4.0 and was accepted in December 1997. However, a working draft for the next major revision, namely HTML 5 was published in January 2008. Originally named Web Applications 1.0, the specification includes several ideas of the WHAT (Web Hypertext Application Technology) working group. It might take several years (a formal target has been set for 2014) before the specification reaches final Recommendation status.

    From 1999 on, HTML is part of a new specification XHTML. The XHTML 1.0 draft was released in 01.99 and mirrors the HTML 4.01 specification. The latest version (XHTML 2.0) was a working draft but was abandoned in 2009 in favor of work on XHTML5, which is being defined alongside HTML5.

    For a complete specification of the different HTML versions, check the official HTML site www.w3c.org/Markup . As a practical reference site use www.blooberry.com/indexdot/html . Other helpful sites - www.htmlgoodies.com/tutors, www.jmarshall.com/easy/html .

    3.2 language definition

    HTML is a system for describing documents. It is a special version of SGML (Standard Generalized Markup Language an ISO standard (ISO 8879)). All markup languages defined in SGML are called SGML applications and are characterized by:

    1. An SGML declaration what characters and delimiters may appear. The SGML declarationof the latest version of HTML (4.01) can be found at this address: http://www.w3.org/TR/1999/PR-html40-19990824/sgml/sgmldecl.html. Since it fits in a couple of pages, we can afford to have a look at this declaration.

    SGML Declaration for HyperText Markup Language version HTML 4.01

    With support for the first 17 planes of ISO 10646 and increased limits for tag and literal lengths etc.

    -- CHARSET BASESET "ISO Registration Number 177//CHARSET

    24

  • 3 - HTML

    ISO/IEC 10646-1:1993 UCS-4 with implementation level 3//ESC 2/5 2/15 4/6" DESCSET 0 9 UNUSED 9 2 9 11 2 UNUSED 13 1 13 14 18 UNUSED 32 95 32 127 1 UNUSED 128 32 UNUSED 160 55136 160 55296 2048 UNUSED -- SURROGATES -- 57344 1056768 57344

    CAPACITY SGMLREF TOTALCAP 150000 GRPCAP 150000 ENTCAP 150000

    SCOPE DOCUMENTSYNTAX

    SHUNCHAR CONTROLS 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 127 BASESET "ISO 646IRV:1991//CHARSET International Reference Version (IRV)//ESC 2/8 4/2" DESCSET 0 128 0 FUNCTION RE 13 RS 10 SPACE 32 TAB SEPCHAR 9 NAMING LCNMSTRT "" UCNMSTRT "" LCNMCHAR ".-_:" UCNMCHAR ".-_:" NAMECASE GENERAL YES ENTITY NO DELIM GENERAL SGMLREF SHORTREF SGMLREF NAMES SGMLREF QUANTITY SGMLREF ATTCNT 60 -- increased -- ATTSPLEN 65536 -- These are the largest values -- LITLEN 65536 -- permitted in the declaration -- NAMELEN 65536 -- Avoid fixed limits in actual -- PILEN 65536 -- implementations of HTML UA's -- TAGLVL 100 TAGLEN 65536 GRPGTCNT 150 GRPCNT 64

    FEATURES MINIMIZE

    DATATAG NO OMITTAG YES RANK NO SHORTTAG YES

    25

  • 3 - HTML

    LINK SIMPLE NO IMPLICIT NO EXPLICIT NO OTHER CONCUR NO SUBDOC NO FORMAL YES APPINFO NONE>

    2. A Document Type Definition (DTD) defines the syntax of markup constructs. Check the address http://www.w3.org/TR/REC-html40/sgml/dtd.html for the latest version of the HTML DTD.

    3. A specification that describes the semantics to be ascribed to the markup and character entity references. This specification adds new syntactic restrictions which cannot be defined within the frame of the DTD.

    4. Document instances containing data (content) and markup. Each instance contains a reference to the DTD to be used to interpret it.

    Overall, the specification of HTML 4.0 contains an SGML declaration, three DTDs (HTML 4.0 Strict DTD, HTML 4.0 Transitional DTD, HTML 4.0 Frameset DTD) and a list of character references. If you wonder what a character reference is, look at these examples: &lt, &quot, "" (in hexadecimal) - the chinese character for water. You get the point.

    3.3 html5

    As of December 2012, HTML5 is a candidate recommendation of the World Wide Web Consortium (W3C). Its core aims have been to improve the language with support for the latest multimedia while keeping it easily readable by humans and consistently understood by computers and devices (web browsers, parsers, etc.). HTML5 is intended to subsume not only HTML 4, but also XHTML 1 and DOM Level 2 HTML.

    It includes detailed processing models to encourage more interoperable implementations; it extends, improves and rationalises the markup available for documents, and introduces markup and application programming interfaces (APIs) for complex web applications.

    HTML5 adds many new syntactic features. These include the new , and elements, as well as the integration of scalable vector graphics (SVG) content (that replaces the uses of generic tags) and MathML for mathematical formulas. These featuresare designed to make it easy to include and handle multimedia and graphical content on the web without having to resort to proprietary plugins and APIs. Other new elements, such as , , and , are designed to enrich the semantic content of documents. New attributes have been introduced for the same purpose, while some elements and attributes have been removed.

    3.4 html elements

    An HTML element consists of:

    a start tag

    26

  • 3 - HTML

    a content

    an end tag

    One exception, though; the element has no content and no end tag.

    There are 91 elements defined in the HTML 4.01 specification. This section deals with some of the most common elements.

    The start tag of the element contains the values of the (required or optional) attributes of the element. An example:

    declares an image element, with the required (mandatory) attributes SRC and ALT and the optional attributes HEIGHT and WIDTH. Other optional attributes of the element, like ALIGN, BORDER, CONTROLS, DYNSRC, , VSAPCE are omitted.

    A comment section in an HTML document starts with . An example:

    3.4.1 The elementMust contain one of the 2 attributes HREF, NAME. Main attributes:

    HREF specifies the absolute or relative URL of the hyperlink

    NAME assigns a symbolic name to the enclosed object (text, image, etc.) in order to use it as a destination in a hyperlink or another URL call.

    Example:

    Login to web mail

    3.4.2 The elementMain attributes:

    ALT required; specifies the text to be displayed in case source is not found

    SRC required; indicates the URL to reference the graphic

    HEIGHT

    WIDTH

    3.5 the minimal structure of an html document

    27

  • 3 - HTML

    All HTML documents start with the tag and end with the corresponding end tag . An HTML document consists of the parts:

    the part

    the part

    A minimal HTML document example:

    My Page

    Empty Body

    3.6 tables

    A table is a visual rectangular object consisting of several rows and columns. The intersection of any row and any column is called a cell. Usually, the cells in the first row contain are called headers and consist of a brief description of the content of the corresponding column. Here is a anexample of a table:

    3.7 table related elements

    The specific elements defining a table, its rows, columns, headers and cells are , , , and . Here is their description and attributes.

    the elementattributes:

    BORDER

    CELLSPACING

    CELLPADDING

    WIDTH

    28

  • 3 - HTML

    ALIGN

    VALIGN

    TBODY

    BORDERCOLOR

    FRAME

    RULES

    COLORGROUP

    BACKGROUND

    the elementattributes:

    ALIGN

    BGCOLOR

    CHAR

    CHAROFF

    VALIGN

    the elementattributes:

    ABBR

    AXIS

    CHAR

    CHAROFF

    HEADERS

    SCOPE

    the elementattributes:

    ALIGN

    BGCOLOR

    CHAR

    CHAROFF

    VALIGN

    the elementattributes:

    ABBR

    29

  • 3 - HTML

    ALIGN

    CHAR

    CHAROFF

    COLSPAN

    ROWSPAN

    SCOPE

    VALIGN

    WIDTH

    3.8 forms

    A form is a basic component container, allowing user input and parameter submittal.

    The element has the following attributes:

    ACTION - required, specifies the URL of the server side process that will receive the data

    METHOD - required, may have the values GET or POST, specifies how data will be sent to the server. Possible values for this attribute:

    "POST"- sends the form values in 2 steps: contacts first the server then the form values are sent in a separate transmission.

    "GET" - sends the form values in a single transmission, the browser appends the values to the URL, after a quotation mark - ?. The pairs name=value are separated by ampersand - & or (sometimes) by semicolon - :.

    Example:http://web.info.uvt.ro/servlet/MyServlet?a=12&b=25

    ENCTYPE - specifies the encoding type of the of the form content. Default value:

    "application/x-www-form-urlencoded" - the default value; however, since it converts spaces to '+' and non-alphanumerical to '%HH', where 'HH' is the hexadecimal ASCII code of the character.

    Other possible values for this attribute:

    "multipart/form-data" - used with forms that contain a file-selection field, data is sent as a single document with multiple sections.

    "text/plain"

    3.9 form related elements

    3.9.1 the element Defines input fields for the form. Main attributes:

    TYPE - required, specifies the type of the input which can have one of the following values:"text", "password", "checkbox", "radio", "submit", "image", "reset", "button", "hidden", "file".

    30

  • 3 - HTML

    NAME - required, specifies the parameter name.

    3.9.2 the element Used to create a list of choices, either as a drop-down menu or as a list box. Each of the listed

    choices is an OPTION element.

    Main attributes:

    NAME

    MULTIPLE - if specified, allows multiple selections from the choice list.

    SIZE - maximum number of options visible to the user.

    3.9.3 the element Used inside a element to list the selection choices. Main attributes:

    SELECTED

    Example of a element:

    Select ActionMake PaymentTransfer a balanceChange Mailing AddressChange e-mail AddressChange User Name/PasswordView Account Activity

    31

  • 4 - JAVA PRIMER

    4 - JAVA PRIMER

    4.1 history

    The initial name of this language was OAK and was developed as part of the GREEN project at Sun, project started in 12.90. Early versions of Java were released in 12.94 and was officially announced at Sun World in 05.95. The first commercial version was delivered to the first customer (Netscape, Inc.) in 08.95. The current version (as of 10.2004) of Java 2 Platform Standard Edition is J2SE 5.0, following the 1.4.2 version. The current version (as of 10.2014) of Java Platform Enterprise Edition is Java EE 7.

    4.2 java the interpreter, jit

    From source to execution, A java program goes thru the following phases:

    1. Java source a file with extension .java

    2. Java bytecode a file with extension .class

    3. The Java interpreter (which is part of the Java Virtual Machine) parses and executes the Java bytecode.

    Example:

    Edit the file prog1.java. The java compiler (javac) translates it to bytecode prog1.class. The java interpreter (as part of the JVM) parses and executes the prog1.class file.

    In terms of execution time, a Java interpreted program is about 10 times slower than a compiled and linked one. To overcome this significant shortage, a tool named Just In Time compiler, allows the compilation of the Java source into machine-dependent binary executable. The first time a class is loaded, the compilation process occurs, which accounts for a pretty slow execution, but next time execution is much faster, pretty much comparable to that of a binary executable.

    The java compiler is (in general) a command line tool, with the following main options: -classpath -sourcepath -d : specifies where to put the .class file. -g : generate all debugging info.

    One example of command line compilation:

    javac -classpath .;C:\TW\mySource;C:\TW\myPackages -g login.java

    4.3 java applications

    There exist 2 types of programs that can be written in Java. The first type are embedded in web pages applets, the others are the standalone programs Java applications.

    32

  • 4 - JAVA PRIMER

    A java applet is a java class that extends the standard Applet class. In general, an applet is inserted in a HTML page by an tag or by an tag.

    The element has 3 mandatory attributes, namely:

    CODE identifies the (compiled) class file of the applet

    WIDTH

    HEIGHT

    A java application is a collection of java classes. Generally, each class is implemented in a source file having the same name as the class itself and whose extension is .java. Exactly one of these classes must implement a method called main(). This method is the entry point in the application and must have the following signature:

    public static void main(String[] args)

    A compiled java application (class) may be executed from the command line using an executable called java (the java interpreter), as follows:

    java [-options] class [args]

    Where main options are:

    -cp : cp = classpath -D = : set a system property

    To execute a .jar file, use the command:

    java jar [-options] jarfile [args]

    4.4 object oriented concepts

    4.4.1 encapsulationThis is a fancy word for the tendency of hiding the implementation of the methods of some class

    and exposing only the interface of its public (and to some degree its protected) methods.

    4.4.2 inheritanceInheritance is a partial order relation in the set of all Java classes. A Java class B inherits

    another class A (or is a subclass of A, or is derived from A, or that it extends A). This binary relation is specified in the declaration of the derived class B using the keyword extends. An example:

    public class CaineComunitar extends Caine{

    33

  • 4 - JAVA PRIMER

    }

    In this case, all variables and methods of the base class A are automatically variables and methods of the derived class B.

    The derived class B can use (for free) all the methods of the base class, but it also can override the implementation of any method in the base class, providing its own implementation.

    While C++ allows multiple inheritance, a Java class can extend a single base class. That means that the graph of the direct inheritance relation is a forest (its connected components are trees). In fact, all classes in Java are (by default) subclasses of a universal base class, called Object. Therefore, the forest we mentioned is actually a tree, with the root the class Object.

    4.4.3 PolymorphismPolymorphism means the ability of a variable of a given (base) type (class) to be used to

    reference objects of different (derived) types (classes), and automatically call the method specific to the type (derived class) of the object that the variable references.

    4.4.4 Method overloadingA method (which has to be declared in some class (or interface)) is identified by its name and the

    type sequence of its parameters. The return type of a method is not part of this signature. Therefore, a class can have more than one method with the same name, provided that the types (and order) of its parameters are different. In OO jargon, this is called method overloading.

    4.5 java as programming language

    integer data types:

    byte

    short

    int

    long

    floating point data types:

    float

    double

    other types:

    boolean - 1 bit

    char - Unicode (16 bits)

    All basic types have associated classes which extend their functionality, namely: Byte, Short, Integer, Long, Float, Double, Boolean, Character.

    Other peculiarities: no pointers (only references), automatic garbage collection, no templates.

    34

  • 4 - JAVA PRIMER

    4.6 access specifiers and modifiers in java

    The access attributes of a member variable or method of a class are specified by the access specifiers. Except for the "package" concept, they have the same basic meaning as in C++.

    no specifier - the default value allows access from any class in the same package

    public - access from any class anywhere

    private - no access from outside the class itself

    protected - accessible from any class in the same package an any subclass anywhereWhile the above specifiers apply to the variables and the methods of a class, the specifiers for

    the class itself can be taken from the following list:

    no specifier - the default value makes the class visible only to the classes in the same package

    public - the class is visible from any class, anywhere

    abstract - the class is abstract (some of its methods (inherited or specified by some interface) are to be implemented by some of its subclasses)

    An example. The declaration:abstract class myFirstClass extends javax.servlet.http.HttpServlet

    implements Serializable{

    ...}declares an abstract class, which is visible only to the classes in the same package, which

    extends the class javax.servlet.http.HttpServlet and which implements the Serializable interface.

    The modifiers of the variables and methods of a class specify their range and stability. A static variable or method is one which is implemented at class level, rather than at class instance. A finalvariable (method, class) is one which cannot be modified (overridden, inherited). More precisely:

    A static (or class): variable - one which is defined at class level, has the same value for all class instances.

    method - all variables referenced in the function body are static variables.

    Static variables and methods can be referenced (invoked) using either the name of the class or the name of a class instance.

    A final: variable - one which is constant

    method - the method implementation cannot be overriden by some subclass.

    class - does not have any subclasses.

    4.7 exceptions in java

    35

  • 4 - JAVA PRIMER

    An exception signals an abnormal situation or an error in an application, due to a variety of execution factors or due to programming errors.

    In Java, an exception is an object which is created when the abnormal situation occurs.Exception categories:

    1. code or data errors - like invalid cast, array index out of bounds, division by 0.

    2. standard method exceptions

    3. programmer defined exceptions

    4. java errors - JVM execution errors (mostly caused by programming errors).

    All exceptions (even programmer defined) must inherit from the standard class Throwable.

    All the standard exceptions are derived from 2 direct subclasses of Throwable, namely class Error and the class Exception.

    4.7.1 The Error classRepresent conditions which are not expected to be caught in our code. Therte are 3 direct

    subclasses of the class Error - ThreadDeath, Linkage Error and VirtualMachineError.

    4.7.2 The Exception classExcept for the RuntimeException exceptions, all then exceptions in this category must be caught

    in our code.

    4.7.3 RuntimeException ExceptionsUsually, these exceptions take place because of serious code errors and they are supposed to

    be fixed in the coding phase, not at execution time.

    The subclasses of the RuntimeException class, as defined in the java.lang package are:

    ArithmeticException IndexOutOfBoundException NegativeArraySizeException NullPointerException ArrayStoreException ClassCastException IllegalArgumentException SecurityException IllegalMonitorStateException IllegalStateException UnsupportedOperationException

    4.7.4 Handling ExceptionsThere are 2 ways to deal with exceptions:

    supply then code to deal with the exception inside the method - this can be done by providinga try, catch, finally construct.

    ignore it (pass it to the code that called the method) - by adding the key word throws, followed by a comma separated list of exceptions after the parameter list of the method.

    36

  • 4 - JAVA PRIMER

    4.8 java packages

    A Java package is a named collection of classes. Each class belongs to a package (even if a package name is not specified, the default package is used). The names in a package are qualifiedby the package name, therefore, they have to be unique inside a package.

    4.8.1 Package namesThe default package has no name. The package containing the standard classes is java.lang

    (automatically available). All other packages must be explicitly imported. As a general rule, the package statement is the first one in a java source file, followed by the import statements. An example:

    package com.bank11.ccards.servlets;import javax.sql.*;import.java.util.Properties;...

    The name of the package is directly linked to the directory structure in which it is stored. In the example above, the class (the .class file, rather) defined in the java source must be stored in a directory called servlets, which is a subdirectory of ccards (which itself, is a subdirectory of a directory called bank11).

    4.9 standard Java packages

    java.lang - default, don't have to import

    java.io

    java.awt - support for user interface

    java.awt.event - support for event handling

    java.awt.geom - support for operations with 2D geometric figures

    java.net

    java.nio

    java.rmi

    java.util - support for data collections, string analyzers, date and time info

    java.util.zip - support for java archives creation

    java.sql

    java.security

    java.text

    javax.accessibility

    javax.swing - swing GUI components (minimal dependence on native code)

    java.swing.event - support for event handling

    37

  • 4 - JAVA PRIMER

    4.10 interfacesAn interface in Java corresponds to the abstract class concept in C++. While multiple

    inheritance is forbidden in Java (a class can be the subclass of a single base class), Java classes can implement zero or more interfaces.

    An interface is a collection of constants and "abstract" functions.All variables (actually, constants) of an interface are automatically (by default) public, static and

    final. All methods declared in an interface are (by default) public and abstract.

    If a class is declared as implementing an interface but omits some of its methods, it must be declared as abstract.

    38

  • 5 - javaScript

    5 - JAVASCRIPT

    5.1 so what is JavaScript?

    JavaScript is a scripting language designed to add interactivity to HTML pages.

    A scripting language is a lightweight programming language A JavaScript source consists of lines of executable computer code A JavaScript is usually embedded directly into HTML pages JavaScript is an interpreted language (means that scripts execute without preliminary

    compilation)

    The initial official name of this language was ECMAscript. ECMA stands for European Computer Manufacturers Association and is an organization founded in 1961 to standardize computer systems in Europe. The origins of this language date back to 1995, and was originally developed byBrendan Eich of Netscape under the names Mocha, then LiveScript and finally, as JavaScript. Subsequently, JavaScript was standardized by ECMA in June 1997 under the name ECMAScript. However, the general public knows it only by the name given by its creator JavaScript. Adaptations of the ECMA standard for other applications, like KDE or Adobe Flash bear different names, like QtScript or ActionScript.

    5.2 what can a JavaScript do?

    JavaScript gives HTML designers a programming tool - HTML authors are normally not programmers, but JavaScript is a scripting language with a very simple syntax! Almost anyone can put small "snippets" of code into their HTML pages

    JavaScript can put dynamic text into an HTML page - A JavaScript statement like this: document.write("" + name + "") can write a variable text into an HTML page

    JavaScript can react to events - A JavaScript can be set to execute when something happens, like when a page has finished loading or when a user clicks on an HTML element

    JavaScript can read and write HTML elements - A JavaScript can read and change the content of an HTML element

    JavaScript can be used to validate data - A JavaScript can be used to validate form databefore it is submitted to a server. This saves the server from extra processing

    JavaScript can be used to detect the visitor's browser - A JavaScript can be used to detect the visitor's browser, and - depending on the browser - load another page specifically designed for that browser

    JavaScript can be used to create cookies - A JavaScript can be used to store and retrieve information on the visitor's computer

    5.3 how and where?

    JavaScripts in a page will be executed immediately while the page loads into the browser. This isnot always what we want. Sometimes we want to execute a script when a page loads, other times when a user triggers an event.

    39

  • 5 - javaScript

    5.3.1 scripts in the head sectionScripts to be executed when they are called, or when an event is triggered, go in the head

    section. When you place a script in the head section, you will ensure that the script is loaded beforeanyone uses it. Here is an example:

    ....

    5.3.2 scripts in the body sectionScripts which are to be executed when the page loads go in the body section. When you place a

    script in the body section it generates the content of the page.

    ....

    5.3.3 using an external JavaScriptSometimes you might want to run the same JavaScript on several pages, without having to write

    the same script on every page. To simplify this, you can write a JavaScript in an external file.Save the external JavaScript file with a .js file extension.

    Note: The external script cannot contain the tag!

    To use the external script, point to the .js file in the "src" attribute of the tag:

    5.4 javaScript variables and expressions

    A variable is a "container" for some information whose value can change during the script.

    5.4.1 variable namesRules for variable names:

    Variable names are case sensitive

    40

  • 5 - javaScript

    They must begin with a letter or the underscore character

    5.4.2 variable declarationA variable can be declared or even created with the var statement:

    var strnum = "2157 Sunrise Blvd";or

    strnum = "2157 Sunrise Blvd";

    5.4.3 variable assignmentA value can be assigned to a variable at declaration time:

    var strnum = "Morii 771"

    Or just use a plain assignment:

    strname = "Morii 771"

    5.4.4 variable typesA variable declaration in JavaScript does not contain a type declaration. The type of the variable

    is determined by any assignment of a value to that variable. This means that the type of the variable can change during the execution of a JavaScript script.

    5.5 javaScript flow control

    Apart from the usual flow control constructs, namely if ... else, switch(), for(), while(), break, continue, while() it is worth mentioning the for ... in and the try ... catch constructs.

    5.5.1 JavaScript for...In statementThe for...in statement is used to loop (iterate) through the elements of an array or through the

    properties of an object.

    The code in the body of the for ... in loop is executed once for each element/property.

    Syntax

    for (variable in object){ code to be executed}

    The variable argument can be a named variable, an array element, or a property of an object.

    ExampleUsing for...in to loop through an array:

    41

  • 5 - javaScript

    var x;var mycars = new Array();mycars[0] = "Saab";mycars[1] = "Volvo";mycars[2] = "BMW";

    for (x in mycars){

    document.write(mycars[x] + "");}

    5.5.2 catching errorsWhen browsing Web pages on the internet, we all have seen a JavaScript alert box telling us

    there is a runtime error and asking "Do you wish to debug?". Error message like this may be useful for developers but not for users. When users see errors, they often leave the Web page.

    This chapter will teach you how to trap and handle JavaScript error messages, so you don't lose your audience.

    There are two ways of catching errors in a Web page:

    By using the try...catch statement (available in IE5+, Mozilla 1.0, and Netscape 6) By using the onerror event. This is the old standard solution to catch errors (available

    since Netscape 3)

    5.5.3 try...catch statementThe try...catch statement allows you to test a block of code for errors. The try block contains the

    code to be run, and the catch block contains the code to be executed if an error occurs.

    Syntax

    try{

    // run some code here}catch(err){

    // handle errors here}

    42

  • 5 - javaScript

    Example

    var txt=""function message(){

    try { adddlert("Welcome guest!"); } catch(err) { txt="There was an error on this page.\n\n"; txt+="Error description: " + err.description + "\n\n"; txt+="Click OK to continue.\n\n"; alert(txt); }}

    5.6 operators

    The only new one is the comparison operator === (equal values and same type). Also, strings can be added (concateneted) using the + operator.

    5.7 popup boxes

    5.7.1 alert BoxAn alert box is often used if you want to make sure information comes through to the user.

    When an alert box pops up, the user will have to click "OK" to proceed.

    Syntax:

    alert("sometext")

    43

  • 5 - javaScript

    5.7.2 confirm BoxA confirm box is often used if you want the user to verify or accept something. When a confirm

    box pops up, the user will have to click either "OK" or "Cancel" to proceed. If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns false.

    Syntax:

    confirm("sometext")

    5.7.3 prompt BoxA prompt box is often used if you want the user to input a value before entering a page. When a

    prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed after entering an input value. If the user clicks "OK" the box returns the input value. If the user clicks "Cancel", the box returns null.

    Syntax:

    prompt("sometext","defaultvalue")

    5.8 functions

    5.8.1 function definitionA function contains some code that will be executed only by an event or by a call to that function.

    A function can be called from anywhere within the page (or even from other pages if the function is embedded in an external .js file). Functions are defined at the beginning of a page, in the section. Example:

    function displaymessage() { alert("Hello World!") }

    If the line: alert("Hello world!!"), in the example above had not been written within a function, it would have been executed as soon as the line was loaded. Now, the script is not executed before the user hits the button. We have added an onClick event to the button that will execute the function displaymessage() when the button is clicked..

    The syntax for creating a function is:

    function functionname(var1,var2,...,varX) { some code }

    var1, var2, etc are variables or values passed into the function. The { and the } defines the start

    44

  • 5 - javaScript

    and end of the function.

    function functionname() { some code }

    Note: Do not forget about the importance of capitals in JavaScript! The word function must be written in lowercase letters, otherwise a JavaScript error occurs! Also note that you must call a function with the exact same capitals as in the function name.

    5.8.2 the return statementThe return statement is used to specify the value that is returned from the function. So, functions

    that are going to return a value must use the return statement. An example is the function below should return the product of two numbers (a and b):

    function prod(a,b) { x=a*b return x }

    When you call the function above, you must pass along two parameters:

    product=prod(2,3)

    The returned value from the prod() function is 6, and will be stored in the variable called product.

    5.9 javaScript objects

    5.9.1 object oriented programmingJavaScript is an Object Oriented Programming (OOP) language. An OOP language allows you to

    define your own objects and make your own variable types.

    We will start by looking at the built-in JavaScript objects, and how they are used. The next pageswill explain each built-in JavaScript object in detail.

    5.9.2 propertiesProperties are the values associated with an object.

    In the following example we are using the length property of the String object to return the number of characters in a string:

    var txt="Hello World!";document.write(txt.length);

    The output of the code above will be:

    12

    5.9.3 methodsMethods are the actions that can be performed on objects.

    45

  • 5 - javaScript

    In the following example we a