Fundamentals of Java Enterprise Components PDF
Document Details
Uploaded by AgreeableAffection7694
2014
Tags
Summary
This textbook introduces the fundamentals of Java Enterprise Components. It covers the Java application model, multitier applications, and various components within them, including web services and APIs. The book also details the design process and important concepts.
Full Transcript
Fundamentals of Java Enterprise Components Fundamentals of Java Enterprise Components © 2014 Aptech Limited All rights reserved. No part of this book may be reproduced or copied in any form or by any means – graphic, electronic or mechanical, including photocopying, recording, taping, or storing...
Fundamentals of Java Enterprise Components Fundamentals of Java Enterprise Components © 2014 Aptech Limited All rights reserved. No part of this book may be reproduced or copied in any form or by any means – graphic, electronic or mechanical, including photocopying, recording, taping, or storing in information retrieval system or sent or transferred without the prior written permission of copyright owner Aptech Limited. All trademarks acknowledged. APTECH LIMITED Contact E-mail: [email protected] Edition 1 - 2014 Dear Learner, We congratulate you on your decision to pursue an Aptech course. Aptech Ltd. designs its courses using a sound instructional design model – from conceptualization to execution, incorporating the following key aspects: ¾¾ Scanning the user system and needs assessment Needs assessment is carried out to find the educational and training needs of the learner Technology trends are regularly scanned and tracked by core teams at Aptech Ltd. TAG* analyzes these on a monthly basis to understand the emerging technology training needs for the Industry. An annual Industry Recruitment Profile Survey# is conducted during August - October to understand the technologies that Industries would be adapting in the next 2 to 3 years. An analysis of these trends & recruitment needs is then carried out to understand the skill requirements for different roles & career opportunities. The skill requirements are then mapped with the learner profile (user system) to derive the Learning objectives for the different roles. ¾¾ Needs analysis and design of curriculum The Learning objectives are then analyzed and translated into learning tasks. Each learning task or activity is analyzed in terms of knowledge, skills and attitudes that are required to perform that task. Teachers and domain experts do this jointly. These are then grouped in clusters to form the subjects to be covered by the curriculum. In addition, the society, the teachers, and the industry expect certain knowledge and skills that are related to abilities such as learning-to-learn, thinking, adaptability, problem solving, positive attitude etc. These competencies would cover both cognitive and affective domains. A precedence diagram for the subjects is drawn where the prerequisites for each subject are graphically illustrated. The number of levels in this diagram is determined by the duration of the course in terms of number of semesters etc. Using the precedence diagram and the time duration for each subject, the curriculum is organized. ¾¾ Design & development of instructional materials The content outlines are developed by including additional topics that are required for the completion of the domain and for the logical development of the competencies identified. Evaluation strategy and scheme is developed for the subject. The topics are arranged/organized in a meaningful sequence. The detailed instructional material – Training aids, Learner material, reference material, project guidelines, etc.- are then developed. Rigorous quality checks are conducted at every stage. ¾¾ Strategies for delivery of instruction Careful consideration is given for the integral development of abilities like thinking, problem solving, learning-to-learn etc. by selecting appropriate instructional strategies (training methodology), instructional activities and instructional materials. The area of IT is fast changing and nebulous. Hence considerable flexibility is provided in the instructional process by specially including creative activities with group interaction between the students and the trainer. The positive aspects of web based learning –acquiring information, organizing information and acting on the basis of insufficient information are some of the aspects, which are incorporated, in the instructional process. ¾¾ Assessment of learning The learning is assessed through different modes – tests, assignments & projects. The assessment system is designed to evaluate the level of knowledge & skills as defined by the learning objectives. ¾¾ Evaluation of instructional process and instructional materials The instructional process is backed by an elaborate monitoring system to evaluate - on-time delivery, understanding of a subject module, ability of the instructor to impart learning. As an integral part of this process, we request you to kindly send us your feedback in the reply pre- paid form appended at the end of each module. *TAG – Technology & Academics Group comprises of members from Aptech Ltd., professors from reputed Academic Institutions, Senior Managers from Industry, Technical gurus from Software Majors & representatives from regulatory organizations/forums. Technology heads of Aptech Ltd. meet on a monthly basis to share and evaluate the technology trends. The group interfaces with the representatives of the TAG thrice a year to review and validate the technology and academic directions and endeavors of Aptech Ltd. Industry Recruitment Profile Survey - The Industry Recruitment Profile Survey was conducted across 1581 companies in August/September 2000, representing the Software, Manufacturing, Process Industry, Insurance, Finance & Service Sectors. Aptech New Products Design Model Key Aspects 1 Evaluation of Scanning the user Instructional system and needs Processes and assessment Material 2 6 Need Analysis Assessment of and design of learning curriculum 3 Design and Strategies for 5 development of delivery of instructional instructions material 4 Preface Web and enterprise applications have become very popular today due to their efficiency and distributed nature. They can be used for different types of transactions and online activities. The use of Enterprise applications allows distribution of components at different levels that helps better management and troubleshooting in case of application errors. This book has been designed to equip you with the knowledge required to develop distributed and efficient Web and enterprise applications. After reading this book, you will be able to identify and create components of Web and enterprise applications. It also introduces Web Services and security features available in Java EE applications. The knowledge and information in this book is the result of the concentrated effort of the Design Team, which is continuously striving to bring to you the latest, the best and the most relevant subject matter in Information Technology. As a part of Aptech’s quality drive, this team does intensive research and curriculum enrichment to keep it in line with industry trends and learner requirements. We will be glad to receive your suggestions. Please send us your feedback, addressed to the Design Centre at Aptech’s corporate office. Design Team Table of Contents Sessions 1. Introduction to Java EE 7 2. Enterprise Application Architecture 3. Introduction to Web Application Development 4. Application Resources 5. Java Servlets 6. JavaServer Pages 7. Introduction to JavaServer Faces 8. JavaServer Faces as Web Pages 9. Facelets 10. Enterprise JavaBeans 11. Java Persistence API 12. Transactions 13. Java Message Service Components 14. Building Web Services with JAX-WS and JAX-RS 15. Java Security Session - 1 Introduction to Java EE 7 Welcome to the Session, Introduction to Java EE 7. This session provides an introduction to the Java enterprise model. It explains about multitier applications, application servers, and Web services. Further, it explains about deployment of enterprise applications on Web containers. Lastly, it explains the various APIs used in Java EE7. In this Session, you will learn to: ÎÎ Explain Java Application model ÎÎ Explain multitier applications ÎÎ Describe various components of multitier applications ÎÎ Describe containers and services provided ÎÎ Describe Web services ÎÎ Describe various APIs used in Java EE 7 for enterprise and Web applications 1 Session Introduction to Java EE 7 1.1 Java Enterprise Application Model The Java enterprise application model defines how various components of an enterprise application are organized. This organization is responsible for creating a portable, secure application with high developer productivity. The portability and security of the application are due to the Java programming language and Java Virtual Machine. Java EE enables the creation of an enterprise application which caters to the needs of the customers, employees, suppliers, partners, and so on. These applications are very complex, where data is accessed from a variety of sources and has to be distributed among various targets. In order to manage this complex flow of data, a middle tier of the application is created. Middle tier is run on a different server which has access to every component of the enterprise application. This can also be termed as the business logic of an application where it knows all about the organization of the data, processes of the enterprise (business logic), and client requirements. Figure 1.1 shows an abstract representation of the Java enterprise application model. Figure 1.1: Application Model of Java EE The client tier represents various users of the enterprise application such as customers, employees, suppliers, and so on. The middle tier handles the enterprise business logic. The enterprise business logic refers to the processes in the enterprise and this layer is aware of enterprise data as well as the client requirements. The middle tier processes the data received from the client with the help of the Data tier. That is, developers implement the business logic in this layer. The processed data is then sent back to the client and presented using the presentation logic on the client tier. Concepts The enterprise application model divides the work required to implement the multitier service into two categories: 1. The business logic and presentation logic which are supposed to be implemented by the developer. 2. The standard system services which are generic for any application such as connecting to the database, establishing a session, and so on. V 1.0 © Aptech Limited 1 Session Introduction to Java EE 7 The Standard system services are provided by Java EE 7 platform. There can be multiple tiers in an application based on requirement; in which case, the architecture is termed as n-tier architecture. 1.2 Multitier Applications A multitier application has the application logic divided into multiple components based on their functionality. These multitier applications are distributed where each of the application components may be installed on the same or on different machines depending on the tier to which it belongs. In a typical enterprise application there are three tiers. Figure 1.2 illustrates the multitier architecture and its respective components. Figure 1.2: Multitier Applications Concepts Various components of Java EE multitier application are as follows: ÎÎ Java EE clients ÎÎ Web components V 1.0 © Aptech Limited 1 Session Introduction to Java EE 7 ÎÎ Java EE components ÎÎ Database components ÎÎ Security components A Java EE application comprises various components that function together. A component can be defined as a fully functional software unit which can communicate with other components. There are three essential components that are widely used in applications: 1. Application clients 2. Web components 3. Enterprise components Application clients form the interface for the usage of the application. Examples for application clients are Web browsers for Web applications, user forms for enterprise applications, and so on. Web components refer to client side scripts such as JavaScript, server side scripts such as Servlets, Java Server Faces, and so on. Enterprise components refer to the business components such as Enterprise Java Beans (EJB) which run on the server. 1.2.1 Java EE Clients Java EE clients can be: ÎÎ Web clients ÎÎ Application clients ÎÎ Applets ÎÎ Java Bean components A Web client consists of two parts – dynamic Web pages and Web browsers. Dynamic Web pages are generated by the Web components in the Web tier through markup languages such as HTML and XHTML. The Web browser is responsible for rendering the Web pages. Concepts An application client runs on the client machine and has a user interface such as forms developed through Abstract Window Toolkit (AWT) or Swing. These application clients communicate with the business logic which in turn is implemented through EJB. Applets can be defined as Web clients that are written in Java language. These are stand alone applications executed through the Web browser. V 1.0 © Aptech Limited 1 Session Introduction to Java EE 7 The multitier application model is an extension of the basic client server application model with additional middle tier and other tiers such as security tiers. Java bean components can be present in both client and server tiers. These bean components manage the data flow between the application client and components running on the Java EE server and also, the data flow between the server components and a database. 1.2.2 Web Components Web components in an application can either be a Web page at the client end or a script running at the server end to service client requests. Servlets are the server side scripts and on the client side there are Web pages generated through Java Server Pages (JSP) and Java Server Faces (JSF). Servlets are invoked in response to a user request and construct a response page after processing the input. JSP pages are text based documents which execute as servlets. JSFs are built on top of both JSP and Servlets, primarily used to create the user interface. Static HTML pages and applets as well as server side utility classes are not considered as Web components according to the Java EE specification. 1.2.3 Java EE Components Java EE Components are business components that implement the logic of application domains such as banking, health care, mobile services, and so on. These components are essentially enterprise beans running in the application tier and client tier. The enterprise bean is capable of receiving data from both the client tier and the data tier. The bean receives the data from the client tier processes it and stores it in the storage. Similarly, it can access data from the data storage, process it, and send it to the client. 1.2.4 Enterprise Information System Tier This is the data repository of the application. This tier includes management of enterprise infrastructure systems such as resource planning, mainframe transaction processing, database systems, and so on. 1.2.5 Security Java EE enables definition of the security constraints at the time of deployment. The application developers are shielded from the complexity of implementing these security features. The developer only defines the security features through a set of declarative access control rules. The implementation of these rules is taken care by the Java EE platform. Java EE also provides various login mechanisms and therefore, the Concepts developer does not require making efforts in implementing these login mechanisms. 1.3 Web and Application Servers The Java EE components must be packaged and deployed on a server to make them available on the Web. V 1.0 © Aptech Limited 1 Session Introduction to Java EE 7 Figure 1.3 shows the Web and Application servers. Figure 1.3 Web and Application Server The Web server consists of a Web container that holds all the Web components. The application server consists of Web containers as well as an EJB container that holds all the enterprise Java bean components. Based on the requirement of the application, a Web server or an application server can be used for deployment. 1.3.1 Web Servers Web servers accept requests from clients through Web pages and respond to these requests with the appropriate Web page. Web servers can be implemented through hardware or software and are primarily responsible for delivering Web content to the clients. The communication between the client and Web server takes place through Hyper Text Transfer Protocol (HTTP) and the response to the client request is built in the form of HTML pages. The request from the Concepts client is interpreted through server side scripts such as Servlets. 1.3.2 Application Servers An application server is a software component which is responsible for all the operations of an enterprise and for implementing the business logic of the enterprise. V 1.0 © Aptech Limited 1 Session Introduction to Java EE 7 For example, consider an enterprise application for banking domain, the application server should implement the functions required by the employees of the bank where employees interact with the database and carry out various transactions. The application server of a bank should also function along with a Web server which provides the facilities of Internet banking to its customers. The application server will be aware of the business logic of the bank. The business logic in this case can be the interest rate applicable to certain accounts, the penalty for less than minimum balance situation, and so on. The application server is responsible for implementing all these domain specific issues. 1.4 Containers Java EE simplifies the application development process by providing certain services to the developer through containers and components. A container contains various components which together provide some services to the application. The services include transaction management, state management, resource pooling, thread pooling, security, and so on, which are utilized by the developers in majority of the applications. These services help in reducing the effort of developing these functionalities from scratch. These services such as transaction management, resource pooling, and so on can be implemented through different components and put together in a single container according to the requirement of the application. The support and services provided by containers and components enable the developer to concentrate on implementing the actual business logic. Figure 1.4 displays containers in Java EE. Concepts Figure 1.4: Containers in Java EE V 1.0 © Aptech Limited 1 Session Introduction to Java EE 7 1.4.1 Container Services In order to use the container according to the requirement of the application, it is essential to configure the container settings. Following is a list of services provided by containers in a Java enterprise application: ÎÎ When an enterprise or Web application requires security mechanisms, Java EE enables you to configure the components to define access to various resources of the applications. ÎÎ Various methods can be put together to form a Java transaction in which case, Java EE transaction model enables you to establish the link between various methods. ÎÎ In scenarios where the server and client are located at different geographical locations, Java EE remote connectivity manages communication between the client and the server. Java EE client ensures that the client is unaware of the actual location of the server. ÎÎ Java Naming and Directory Interface (JNDI) provides naming service to access different objects and components in the enterprise application domain. The container allows different configurations of the same application component based on the context of the application. The container manages non-configurable services such as enterprise beans, servlet lifecycles, database access, and so on. The different containers and their interaction are shown in figure 1.4. 1.4.2 Container Types Various components of the enterprise application are installed in different containers during deployment. They are: ÎÎ Web Container ÎÎ Enterprise Java Beans Container ÎÎ Applet Container ÎÎ Application Client Container The Web container is installed on the Java EE server, which comprises all the components of the Web applications. The Web container is responsible for handling HTTP communication, execution of servlets, managing the life-cycle of Web components, and so on. Concepts The EJB container is also present on the Java EE server, which consists of the EJB components implementing the business logic of the application. The Applet container manages the execution of applets. This container comprises the Web browser and plug-ins. The Application Client container manages various application clients. V 1.0 © Aptech Limited 1 Session Introduction to Java EE 7 1.5 Development and Deployment Developing a Java enterprise application involves various stages as follows: ÎÎ Procuring Java platform and tools for development ÎÎ Development of components by application component providers ÎÎ The components generated by the application providers are assembled by the assemblers and further deployed by the deployers Product providers are the vendors who enable purchase of Java EE APIs and other features defined in the Java EE specification. Tool providers are those vendors who provide application development tools such as Eclipse, NetBeans, and other tools for assembly, deployment, and packaging. Application components include the bean component for enterprise applications, Web component for the Web applications and application clients. Following are the application component providers: 1. A Bean developer writes and compiles the source code, creates the deployment descriptor, and packages the.class file as an EJB JAR file. 2. A Web component developer will write source codes for servlets, JSPs, JSFs, and HTML files. The.class files,.jsp files, and.html files created are packaged as WAR files. As in case of Bean, the source code of the application client is written by an application client developer and compiled to generate a.class file along with the deployment descriptor for the class file. The.class files are then packaged as a JAR file. 3. An Application assembler receives all the components from the application component providers and assembles the respective JAR and WAR files to EAR (Enterprise Archive) file. The assembler may or may not specify the deployment descriptor by adding appropriate XML tags. 4. An Application deployer is responsible for deploying the application in the operational environment. The deployer configures the operational environment based on the specifications provided by the application component provider to resolve external dependencies, specify security settings, and assign transaction attributes. A Java enterprise application is packaged as one or more standard units for deployment. Each unit has a functional component/components and deployment descriptor. A single developer can play all the mentioned roles or these roles can be divided among individuals and teams. This kind of division is possible because each stage outputs a portable file which is an input to the subsequent stage. Concepts 1.5.1 APIs in Java EE7 Java EE 7 provides a set of APIs that can be used for development of Web and enterprise applications. Figure 1.5 displays the APIs used in EJB containers. The Concurrency utilities, Batch processing, and JSON-P APIS are new inclusions in Java EE7. V 1.0 © Aptech Limited 1 Session Introduction to Java EE 7 Figure 1.5: APIs Used in EJB Container Figure 1.6 displays the APIs used in Web containers. Concepts Figure 1.6: APIs Used in a Web Container V 1.0 © Aptech Limited 1 Session Introduction to Java EE 7 Apart from components such as EJB, Servlets, Java Server Pages, and Java Server Faces, various APIs and libraries are required in Java EE application development. Following is a brief description of the APIs and libraries that are widely used in application development. 1.5.2 Java Server Pages Standard Tag Library JSTL is a set of JSP tags that are widely used in JSP applications. The tags in JSP have varying functionalities such as tags used for formatting the Web page, tags for iterating and managing the flow control, tags for accessing database, and so on. Java EE 7 uses JSTL 1.2. 1.5.3 Java Persistence API Java Persistence API is used for bridging the gap between object-oriented interpretation of data and relational data in databases. A persistence entity is a lightweight class representing a table in the relational database. The instances of the class represent rows of the table. The Persistence API has a query language for the entities in the database. Java EE7 uses Java Persistence API 2.1. 1.5.4 Java Transaction API Java Transaction API is responsible for transaction management in the application database. It is responsible for commit and rollback operations on tables of the database and maintains database integrity. It ensures that every transaction reads appropriate and accurate data. 1.5.5 Java API for RESTful Web Services REST stands for Representational State Transfer, which is an architectural style to develop Web services. REST defines certain architectural properties for the application such as performance, scalability of the application, simplicity of the interface, ability to modify the components, portability of component deployment, and so on. The API provides means to develop Web services with the given qualities. Java EE 7 requires JAX-RS2.0. 1.5.6 Managed Beans Managed Beans are light weight objects running on the Java Virtual Machine, responsible for management related tasks of the application. They are responsible for reporting events such as faults, state changes, performance of the application, and so on. These managed beans can be used in both Web applications and enterprise applications. They are part of Java EE 7 specification that uses Managed Beans 1.0. Concepts 1.5.7 Contexts and Dependency Injection for Java EE CDI is a framework which is an integral part of Java EE platform. It provides an architecture that enables various components of an application such as servlets, beans, and so on to exist only within the life cycle of the application. It defines the context of each component. It allows integration of components in a loosely–coupled but type safe manner. V 1.0 © Aptech Limited 1 Session Introduction to Java EE 7 The components are injected (activated) into the context of the application life cycle based on certain events. The components when added to context, CDI ensures that it is done in a type safe manner holding all the dependencies intact. 1.5.8 Bean Validation Bean Validation process is responsible for validating the data in beans in various tiers of application. Instead of distributing the task of validation across multiple layers an API is defined along with the metadata model for validation of beans. The API enables defining the validation constraints in one location which is further used across layers. Java EE7 requires Bean Validation 1.1. 1.5.9 Java Messaging Service API The Java Messaging Service API is used by the components to create, send, receive, and read messages. This messaging standard is used to enable distributed communication which is reliable and asynchronous. 1.5.10 Java EE Connector Architecture The Connector Architecture is responsible for creating resource adapters that will access Enterprise Information Systems. These resource adapters are used by Java EE applications. A resource adapter is a specific resource manager. One of the common resources in the EIS layer is database. The connector architecture also integrates the Web services with the existing EISs and ensures that the integration is performance oriented, secure, and scalable. 1.5.11 JavaMail API Java Mail API enables sending mail notifications. The API has an interface used by application components that are used to send mail and a service provider interface, where service provider refers to the network carrier of the mail. 1.5.12 Java Authorization Contract for Containers The JACC defines a contract between the Java EE components of the application and authorization policy providers. Based on the authorization policy java.Permission.security classes are defined by the JACC. This is in the case of third party policy providers. The JACC provides a set of standard permission types relevant for all enterprise and Web applications. It also provides a standard model for role-based authorization, grouping certain permissions along with Concepts the roles defined. 1.5.13 Java API for Web Socket Web Socket refers to an application protocol which provides full duplex communication between two communicating entities. The Web Socket API helps in creating the communication end point and allows specifying the configuration parameters. This is a new API introduced in Java EE 7. V 1.0 © Aptech Limited 1 Session Introduction to Java EE 7 1.5.14 Java API for JSON Processing JSON refers to a text based data exchange format, which is used in Web services and other applications. The JSON data exchange format is derived from JavaScript. The API enables Java EE applications to parse, transform, and query data from JSON using the object model or streaming model. 1.5.15 Concurrency Utilities for Java EE The Concurrency Utilities of Java are responsible for providing asynchronous capabilities to enterprise application components. These utilities include managed executor service, managed scheduled executor service, managed thread factory, and so on. 1.5.16 Batch Applications for the Java Platform Batch applications refer to the set of applications which do not have extensive input and output. The Batch Applications framework for Java enables creating and executing batch jobs. The batch framework has a batch runtime, job specification language based XML, an API to interact with the Java runtime, and an API to implement batch artifacts. Concepts V 1.0 © Aptech Limited 1 Session Introduction to Java EE 7 1.6 Check Your Progress 1. Which of the following statements about an enterprise application are true? a. Components of various layers in an application have to run on different machines. Components of various layers in an application may or may not run on different b. machines. c. The client tier represents various users of the enterprise application. d. Middle tier communicates with both application client layer and the data layer. (A) a, b, d (C) b, c, d (B) a, c, d (D) a, b, c 2. _____________ can be a Web client of a Java enterprise application. (A) Web browser (C) HTML page (B) Applet (D) All of these 3. Which of the following containers are responsible for HTTP communication and execution of servlets? (A) Web container (C) Application client container (B) Applet container (D) EJB container 4. Match the following Java EE APIs with the corresponding description. API Description Java Message a. 1. Helps in creating the communication end point Service API Concepts Used by the components to create, send, receive, and b. Java Mail API 2. read messages Java API for Web Responsible for commit and rollback operations on c. 3. Socket tables of the database Java Transaction d. 4. Enables sending mail notifications API V 1.0 © Aptech Limited 1 Session Introduction to Java EE 7 (A) a-4, b-3, c-1, d-2 (C) a-3, b-1, c-4, d-2 (B) a-2, b-4, c-1, d-3 (D) a-2, b-3, c-4, d-1 5. In three tier architecture, the business logic of the enterprise is implemented in the __________ layer. (A) EIS (C) Client (B) Middle (D) Any of these Concepts V 1.0 © Aptech Limited 1 Session Introduction to Java EE 7 1.6.1 Answers 1. C 2. D 3. A 4. B 5. B Concepts V 1.0 © Aptech Limited 1 Session Introduction to Java EE 7 Summary ÎÎ The Java enterprise application model defines how various components of an enterprise application are organized. ÎÎ A component can be defined as a fully functional software unit which can communicate with other components. ÎÎ A Web client consists of two parts – dynamic Web pages and Web browsers. ÎÎ A container contains various components which together provide some services to the application. The services include transaction management, state management, resource pooling, thread pooling, security, and so on. ÎÎ The EJB container is also present on the Java EE server, which consists of the EJB components implementing the business logic of the application. ÎÎ Application assembler receives all the components from the application component providers and assembles the respective JAR and WAR files to EAR (Enterprise Archive) file. ÎÎ Java Persistence API is used for bridging the gap between object-oriented interpretation of data and relational data in databases. Concepts V 1.0 © Aptech Limited Session - 2 Enterprise Application Architecture Welcome to the Session, Enterprise Application Architecture. This session discusses various concepts of enterprise application architecture which are useful in designing Java enterprise applications such as design patterns, layered architecture, and so on. In this Session, you will learn to: ÎÎ Explain enterprise application design ÎÎ Use various design patterns in application design ÎÎ Describe Model-View-Controller design ÎÎ Explain communication among application components ÎÎ Describe network topologies and clustering ÎÎ Describe the layered architecture of application design 2 Session Enterprise Application Architecture 2.1 Introduction Application architecture has evolved from client-server architecture to N-tier architecture. In case of client-server architecture, the client layer would request services and the server would respond by providing the services requested by the client. As the applications scaled among multiple clients and multiple servers, thereby increasing the complexity of applications, a middle tier was added between the client and the server layer resulting in three-tier architecture. The middle layer is responsible for servicing the data requests from the client and managing the data appropriately on the data servers. The three-tier architecture evolved to N-tier architecture with the advent of Internet and better network infrastructure. Cloud applications and data centres enable locating various components of the application such as data servers, Web servers, applications, and client components in different geographical locations. N-tier architecture of Java provides the infrastructure to manage these components. Distribution of processing into various layers results in better resource utilization and efficient functioning. When an application is developed as independent components, all of them are integrated through a uniform interface and also, require various other services to function properly. These services include the security mechanisms for data transmission among the components and compliance with Internet protocols to communicate over the Internet. 2.2 Designing an Enterprise Application Application design in Java is object-oriented, which implies that the designer of the application has to identify the objects in the context and generalize a group of objects with common behavior and properties into classes. Once the objects in the context of the application are identified, the designer has to identify the interaction between various objects and determine appropriate methods for these classes. This is modelled through Unified Modelling Language (UML) diagrams. The design in Java being multi-layered, these objects have to be placed in appropriate layers in the application components. The objects in different layers are assigned responsibilities and interfaces are laid out for interaction between layers. This design of distributed objects is more complicated than simple object-oriented design, as the designer has to consider the aspects of scalability, performance, transactions, and so on. Object-oriented programming encourages reuse of code, classes, and objects. While designing a solution for a problem, it is considered a good practice to reuse an existing solution than redesigning the solution from scratch. This will reduce the development time and required effort to reach the final solution. Design patterns enable this reuse in Java applications. While designing solution for a problem, if a similar problem has been solved earlier, it can be inferred that the solution for the current problem will also be on similar lines. Design patterns suggest a pattern of Concepts resolution for certain problems based on solutions for similar problems resolved earlier. Design patterns allow reuse of such designs and architecture that were successfully applied in solving a similar problem. V 1.0 © Aptech Limited 2 Session Enterprise Application Architecture 2.3 Design Patterns A design pattern identifies a recurrently occurring problem in a domain and offers a solution to the problem. The solution offered can be used to solve similar problems occurring in the future. The design pattern identifies the classes and instances, their roles and collaborations, and distribution of responsibilities. Based on these aspects of the problem, an appropriate design pattern can be identified and used to design a solution for the problem. Each design pattern is described based on a consistent format and is divided into sections based on a template. Following are the sections of the template of design patterns: ÎÎ Pattern name and classification – This is a conceptual category for the pattern ÎÎ Intent – Describes the type of problems, this particular pattern can solve ÎÎ Also known as - Implies other common names of the pattern ÎÎ Motivation – A scenario which illustrates the problem ÎÎ Applicability – Describes the situations where the current pattern can be used ÎÎ Structure – Diagram using an object modelling technique such as UML ÎÎ Participants – Implies the classes and objects in the design ÎÎ Collaborations – Defines how the classes and objects in the domain, collaborate with each other ÎÎ Consequences – Describes the outcome of using this pattern and also describes any kind of side effects it may lead to ÎÎ Implementation – Describes the implementation specific or language specific issues that might arise on, using this design pattern ÎÎ Sample code – Provides an example of the design pattern created in languages such as Java or any other object-oriented languages and enables the developer to translate the code with similar classes and objects Concepts ÎÎ Known uses – Illustrates some real world scenarios where this design pattern has been successfully put to use earlier ÎÎ Related patterns – Provides comparison with similar patterns, so that the developer can choose the right pattern for their application V 1.0 © Aptech Limited 2 Session Enterprise Application Architecture While designing an application, if the developer intends to use a design pattern, then the developer should first, understand the context and intent of the pattern. Identifying the classes and objects in the given domain, is the most critical aspect for an object-oriented application which can be done with the help of design patterns. There are four primary categories of design patterns: 1. Creational patterns – Define the object creation process in the application 2. Structural patterns – Define the organization of classes and objects in an application 3. Behavioral patterns – Define the interaction between various objects in the application 4. Concurrency patterns – Define the access of resources by objects of the application 2.3.1 Creational Patterns Creational patterns are useful in scenarios where the object composition is crucial for the application. It provides flexibility in terms of deciding, what properties of the class are used in the application and what should be the behavior of the instantiated object. Creational patterns allow the developer to configure a system with the product objects which vary widely in structure and functionality. Singleton pattern and abstract factory pattern are examples of creational patterns. ÎÎ Singleton Pattern Singleton pattern restricts on the number of objects that will be created during each object instan- tiation. It allows instantiation of only one object for the class. It is implemented by creating a class with a method which creates a new instance of the class, only when there is no other instance of the class existing. If another instance of the class is present, then the methods return a reference to the existing object instead of creating a new instance. The constructor of such a class is made private so that the object of the class cannot be instantiated in any other manner. Code Snippet 1 shows the instantiation of an object according to singleton pattern. Code Snippet 1: public class SingleInstance { // declare an instance of the class private static SingleInstance inst = null; // set constructor as private private SingleInstance() {} Concepts // define a synchronized method for creating the instance public static synchronized SingleInstance getInstance() { // check for existence of instance if (inst == null) { V 1.0 © Aptech Limited 2 Session Enterprise Application Architecture // create instance if it does not exist inst = new SingleInstance (); } return inst; // return the instance } } In Code Snippet 1, the class SingleInstance is a singleton class which can instantiate only one object at any instance of time. The constructor is declared as private, therefore external classes cannot create an instance of the class, SingleInstance. The getInstance() method will create a new instance of -SingleInstance class only when the instance value is ‘null’ which implies that there is no other instance of SingleInstance class. It is always important to have the getInstance() method synchronized, so that it can remain thread safe. However, when a singleton instance is serialized and deserialized more than once, then there is a possibility of having multiple instances of the class which needs to be checked. A singleton class cannot be further inherited as its constructor is private. Other creational patterns are factory pattern, abstract factory pattern, builder pattern, and proto- type pattern. 2.3.2 Structural Patterns Structural patterns are meant for enabling multiple classes and objects to function together. These patterns use mechanisms such as inheritance to allow various interfaces and their implementations to work together. This pattern is essential for allowing independently developed classes and interfaces to work together. The focus of this pattern is how the classes are inherited from each other and how they are aggregated from other classes. Adapter, proxy, and decorator patterns are commonly used structural patterns. ÎÎ Adapter Patterns Adapter design pattern is used when two classes with two different interfaces have to function together. This is done by converting the interface of one class into an interface acceptable by the clients. Concepts V 1.0 © Aptech Limited 2 Session Enterprise Application Architecture Figure 2.1 depicts a Class diagram of an adapter pattern. Figure 2.1: Adapter Pattern An adapter pattern is used in the following situations: yy When the developer needs to use an existing class and its interface, does not exactly match what is required by the developer yy When the developer has to create a reusable class which has to function along with other incompatible classes Proxy and decorator patterns are other structural patterns. 2.3.3 Behavioral Patterns Behavioral patterns are those that determine the interaction of objects. These patterns are used when the behavior is complex. They simplify the complex behavior by specifying the responsibilities of the objects and their communication method. Most common behavioral pattern is observer pattern, which is used when an application is being Concepts implemented through a Model-View-Controller architecture. This separates the presentation of data from the actual data store. Java API provides Observable class which can be extended by objects that need to be observed. The objects that need to be observed can be components such as speedometer in an application where if the speed exceeds a certain limit, the driver should be warned. The Observable class has various methods that notice the changes in the object being observed. V 1.0 © Aptech Limited 2 Session Enterprise Application Architecture 2.3.4 Concurrency Patterns Concurrency patterns are applied in cases where there are certain shared resources. These patterns ensure that the access to these resources is consistent and coordinated. Single thread execution is the most common concurrency pattern. This pattern ensures that only one thread is accessing a certain resource at any instance of time. In Java, this is implemented through synchronized blocks of statements. The section of code which has to be accessed by only one thread is termed as a critical section. Active object, double-checked locking pattern, and reactor pattern are other concurrency patterns. 2.4 Model-View-Controller Model-View-Controller is a methodology of designing user interfaces for applications. It divides the components of the application primarily into three parts, model, view, and controller. With respect to the user interface, the view is most important. When there are multiple users for the application, each user has a different perspective for the application data. Each perspective of the end user is a view of the application. The model is the logical part of the application which includes the business logic, Web logic, and database which provides data to the user interface and accepts data from the user interface to process it. The controller accepts data from the user interface and converts it into a format understandable by the model. Apart from the functions of the components, MVC architecture also defines the interactions between these three components. Figure 2.2 shows the interactions among various components of MVC architecture. Figure 2.2: Model-View-Controller Architecture Concepts According to MVC, the data flow between the user interfaces, that is, the view and the application, or model is mediated by a controller. View refers to that part of the application which the end user actually sees. This can be a Web page or a data format. The user response is captured in the view. The data captured in the view is sent to the business components such as servlets (in Web applications), beans (in enterprise applications) through a controller. V 1.0 © Aptech Limited 2 Session Enterprise Application Architecture The controller may receive data from the user interface, in the form of HTTP request or any other interface specific form. The controller translates this data into a form understandable to the business components, for instance the controller would invoke the correct servlet based on the data received from the view and return the response from the servlet to the view. Model refers to the context specific processing done by the application. Consider an example of a banking application where the user logs in with a login ID and password. The controller receives this data and passes it to appropriate servlet and fetches the user data from the database. Here, model refers to the user data in the database. Consider a Java application which uses Swing as user interface. In this case, Swing is the view component in the MVC architecture, listener is the controller, and model will be the Java class that uses the listener or database. The MVC architecture aims at separating the presentation and implementation of the program logic. This separation enables independent modifications to the user interface and program implementation without affecting other components. Code Snippet 2 shows a code with a UI component and controller. Code Snippet 2: package mvcpkg; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class MVCdemo { // initialize the GUI controls private JFrame mainFrame; private JLabel headerLabel; private JLabel statusLabel; private JPanel controlPanel; public MVCdemo(){ prepareGUI(); // invoke prepareGUI method } public static void main(String[] args){ // instantiate the class Concepts MVCdemo objMVC = new MVCdemo(); objMVC.clickOK(); } // creates the GUI V 1.0 © Aptech Limited 2 Session Enterprise Application Architecture private void prepareGUI(){ // design the GUI mainFrame = new JFrame(“To Demonstrate MVC”); mainFrame.setSize(400,400); mainFrame.setLayout(new GridLayout(3, 1)); headerLabel = new JLabel(“”,JLabel.CENTER ); statusLabel = new JLabel(“”,JLabel.CENTER); statusLabel.setSize(350,100); // add listener to the frame mainFrame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent windowEvent){ System.exit(0); } }); controlPanel = new JPanel(); controlPanel.setLayout(new FlowLayout()); mainFrame.add(headerLabel); mainFrame.add(controlPanel); mainFrame.add(statusLabel); mainFrame.setVisible(true); } // handles the click of OK button private void clickOK(){ JButton okButton = new JButton(“OK”); okButton.setActionCommand(“OK”); // add listener to the OK button okButton.addActionListener(new ButtonClickListener()); controlPanel.add(okButton); mainFrame.setVisible(true); } // handler class for click event of the OK button private class ButtonClickListener implements ActionListener{ Concepts @Override public void actionPerformed(ActionEvent e) { V 1.0 © Aptech Limited 2 Session Enterprise Application Architecture String command = e.getActionCommand(); if( command.equals( “OK” )) { statusLabel.setText(“ButtonClickListener(Controller) invoked”); } } } } Code Snippet 2 shows only two components of the MVC architecture, view and controller. The view is defined by the method prepareGUI() and ActionListener is the controller which is implemented by the ButtonClickListener class and generates the response to the input from the view. Further, this UI can be coupled with a bean component and/or a database to add the model component of the MVC architecture. Figure 2.3 shows the output when the code is executed. Figure 2.3: Output When Code is Executed Concepts V 1.0 © Aptech Limited 2 Session Enterprise Application Architecture Figure 2.4 shows the output after an event occurs in the GUI, in this case, it is the button click. Figure 2.4: Output After the Button Click Event 2.5 Synchronous and Asynchronous Communication Java applications are developed as independent components according to multi-layered architecture. These independent components that may reside at geographically distinct locations are integrated together and work in collaboration. In order to make these components collaborate efficiently, the communication between them plays an important role. The communication among components of an application can be synchronous or asynchronous. Synchronous communication is one where a request is sent and the sender waits for the response from the receiver before sending the next request. Concepts Asynchronous communication is one where the request is sent but the sender does not wait for response from the receiver. Remote Method Invocation (RMI)/Remote Procedure Call (RPC) in Java is an implementation of synchronous communication and Java Messaging Service (JMS) is an implementation of asynchronous communication. V 1.0 © Aptech Limited 2 Session Enterprise Application Architecture Java implements both synchronous and asynchronous communication through Java Messaging Service (JMS) API. 2.6 Clustering and Network Topologies Clustering refers to a technique where an application is deployed over a group of servers which is termed as a cluster of servers. A cluster of servers is a group of servers that are interconnected and run an application in a way that the end user is unaware of multiple entities running as servers. According to the user, the server is only a single entity. Clustering technique is important to scale the application across multiple users and make the application highly available. There are certain essential services and components such as JNDI, EJB, JSP, and so on, that are used for Java applications to function. Clustering aims at ensuring that these services and components are always available. Following are the various purposes of clusters: ÎÎ Load balancing ÎÎ Fail over In case of Web applications: ÎÎ Web load balancing ÎÎ HTTP fail over In generic terms, load balancing is a process wherein if a server is overwhelmed with client requests, then certain client requests can be serviced by another server which will respond in an identical manner. This is applicable for both enterprise and Web applications. A load balancer manages the client request and maps it onto appropriate server. Fail over of server refers to a situation of server crash. When a server crashes all the requests being serviced by that server, are transferred to another server which would respond in an identical manner. In case of Web applications, it is termed as a HTTP fail over. When a HTTP session fails, a new HTTP session is initiated with respect to a different server. A dispatcher is responsible for redirecting the requests to another server. In order to achieve this, the cluster of application servers should have an efficient communication mechanism and application processing. Figure 2.5 shows the topology of servers in clustering Concepts V 1.0 © Aptech Limited 2 Session Enterprise Application Architecture Figure 2.5: Clustering Figure 2.5 shows that there is a load balancer/dispatcher which receives requests from clients. The load balancer has information about the kind of workload each server in the cluster has and based on this data, the load balancer sends the request to a server such that the workload among different servers is balanced. Dispatcher is a component which handles the situation of fail over of a server. The fail over can be a HTTP fail over as in case of Web applications or an application server fail over as in case of enterprise applications. In both the cases, the dispatcher sends the service request to another server which is running, receives the response from the server, and sends it to the client that has raised the request. The role of both load balancer and dispatcher is similar in a way that both the components accept client requests and redirect the request to the appropriate server based on certain criteria, receive the response from the server, and return it to the appropriate client. Databases are also distributed over a cluster of servers to ensure high availability of the database. Techniques such as RAID (Redundant Array of Independent Disks) are used in the case of databases. ÎÎ Network Topologies The network topology according to which the servers in the cluster are interconnected, has an im- pact on the accessibility of the server, resulting in performance trade-offs. Concepts Following are some popular topologies of connecting various components of the network: yy Star Topology yy Ring Topology yy Bus Topology yy Tree Topology V 1.0 © Aptech Limited 2 Session Enterprise Application Architecture ÎÎ Star Topology In star topology, every node is connected to a central node called a hub or switch which is the server and the peripherals are the clients. In a network cluster, the central server/router connects to all other servers in the network cluster. Figure 2.6 shows the arrangement of servers according to star topology. Figure 2.6: Star Topology ÎÎ Ring Topology In ring topology, each node is connected to exactly two other nodes, with the last node connecting to the first node forming a circular ring. The topology leads to formation of a single continuous pathway for signals through each node. Data travels from node to node and each node along the way handles every packet. As there is only one pathway between any two nodes, ring networks may disrupt it even a single link fails. Figure 2.7 depicts the Ring topology. Concepts Figure 2.7: Ring Topology V 1.0 © Aptech Limited 2 Session Enterprise Application Architecture ÎÎ Bus Topology In bus topology, all the nodes are connected in a daisy chain in a linear sequence of buses. The host on a bus network is known as a workstation. All the servers are accessible through the shared bus only. The bus can transmit data only in one direction. If any network segment gets disconnected, all network transmission ceases. Here, each network segment has equal priority and therefore, becomes a collision domain. Figure 2.8 shows the arrangement of servers in bus topology. Figure 2.8: Bus Topology ÎÎ Tree Topology A tree topology follows a hybrid approach by combining the star and bus topologies to improve network scalability. In tree topology, all the servers in the cluster are connected like a tree, which can be a hierarchical or a non-hierarchical tree. Figure 2.9 shows the arrangement of servers in a hierarchical tree structure. Concepts Figure 2.9: Tree Topology V 1.0 © Aptech Limited 2 Session Enterprise Application Architecture Figure 2.9 indicates that if the main cable or link between the different star topology networks fails, the networks would not be able to communicate with each other. However, nodes on the same star topology, would still be able to communicate with each other. 2.7 Layering in Java Applications Layers are different from tiers. Tiers refer to hardware components which can be located on different servers or machines for the functioning of application. Layering refers to logical separation of the components, components belonging to different layers may be implemented through different APIs, but may or may not reside on the same machine. Java applications can have the following layers: ÎÎ Client Layer ÎÎ Presentation Layer ÎÎ Business Logic Layer ÎÎ Data Access Layer (Persistence) ÎÎ Integration Layer ÎÎ Services Layer 2.7.1 Client Layer Client layer comprises all those entities that access the application. The clients can be browser clients, application container clients, CORBA (Common Object Request Broker Architecture) clients, JMS clients, and Web service clients. 2.7.2 Presentation Layer Presentation layer generates the user interface for the client. In order to generate dynamic content for the user, the application developer can use components such as servlets, JSPs (Java Server Pages), HTML, CGI, and so on. Apart from the dynamic content, the user interface may also have static content. Servlets provide session management, simple input validation, and also relates the business logic of the Concepts application with the user interface. JSPs handle the display tasks of the servlets. They define the screen navigation and other presentation logic. JSPs can also invoke JDBC objects. Apart from these, there are HTML, XHTML, and CGI for server scripting, which are responsible for defining the presentation logic of the application. V 1.0 © Aptech Limited 2 Session Enterprise Application Architecture 2.7.3 Business Logic Layer This layer is responsible for the implementation of business logic of the application. The components that are used for defining the business logic are session beans, entity beans, and message driven beans. Session beans are used in applications, where the client has to establish a session with the server and retrieve specific information. For instance, when a user tries to access his/her personal e-mail, then the client has to establish a session with the mail server and retrieve data. Based on the requirement, one can use stateless session beans or stateful session beans. Entity beans also implement the business logic where they use persistent objects. This functionality can further be categorized as persistence layer. 2.7.4 Persistence Layer Persistence layer deals with persistent data objects such as database rows. A persistent object is one which has dedicated storage location in the application database. In order to access them, the application has to instantiate Data Access Objects (DAOs) or JDBC interfaces. The Data Access Objects and the JDBC interfaces together form the persistence layer of the application. 2.7.5 Integration Layer Java application development is modularized with well-defined components that can be independently developed. The integration layer is responsible for enabling these independent components to function together. The functions of integration layer are enabling communication among the components, message processing, transformation of data formats, transformation of protocol formats, and so on. 2.7.6 Services Layer The services layer comprises services supporting business functionality. These services include definition of data access policy, security services through policy management tools, and cryptographic services for the application. The implementation of these layers can be independent or combined based on the application requirement. Concepts V 1.0 © Aptech Limited 2 Session Enterprise Application Architecture 2.8 Check Your Progress 1. ______________ is a creational design pattern. (A) Adapter pattern (C) Decorator pattern (B) Proxy pattern (D) Singleton pattern 2. Which of the following patterns can be used when there is resource sharing among the objects of the application? (A) Prototype pattern (C) Single thread execution pattern (B) Abstract factory pattern (D) Singleton pattern 3. ______________ is an implementation of asynchronous communication. (A) CORBA (C) RMI (B) RPC (D) JMS 4. Which of the following statements are true? a. Load balancer comes into action, only when a server crashes in the cluster. The end user is unaware of the operations carried out by load balancer and b. dispatcher. c. Dispatcher maps the jobs of a crashed server to alternative servers. (A) a, b (C) a, c (B) b, c (D) None of these 5. _____________ functions in the presentation layer of the application. Concepts (A) HTML (C) Servlet (B) CORBA client (D) Session bean V 1.0 © Aptech Limited 2 Session Enterprise Application Architecture 2.8.1 Answers 1. D 2. C 3. D 4. B 5. A Concepts V 1.0 © Aptech Limited 2 Session Enterprise Application Architecture Summary ÎÎ Application design process in Java is object-oriented and uses design patterns based on the requirements and other attributes of the application. ÎÎ The various design patterns such as creational, behavioral, structural, and concurrency are based on the context of the application, components, and so on. ÎÎ Model-View-Controller architecture separates the presentation and the logic of the application which enables independent implementation of these components during application development. ÎÎ Asynchronous and synchronous communication are two different communication methodologies used to allow independently developed components to work together. ÎÎ In Star topology, there is a central server/router which connects to all other servers in the network cluster. ÎÎ Layering of the Java applications is essential to logically divide the functions of Java components. The implementation of these layers can be independent or combined based on the application requirement. ÎÎ The services layer comprises services supporting business functionality such as data access policy, security services through policy management tools, and cryptographic services for the application. Concepts V 1.0 © Aptech Limited Session - 3 Introduction to Web Application Development Welcome to the Session, Introduction to Web Application Development. This session describes Web applications and the process of developing Web applications using the Java EE7 platform and Netbeans IDE. It also describes the life cycle of the Web application, different Web components, and the protocols used by the Web application to communicate with different components of the application. In this Session, you will learn to: ÎÎ Explain the basics of Web application development ÎÎ Describe the different components of a Web application and how they interact with each other ÎÎ Describe the protocols and communication standards associated with Web applications ÎÎ Explain the basic process of creating a Web application through the Netbeans IDE ÎÎ Describe the technologies used to develop Web applications ÎÎ Describe Web services and standards associated with Web services 3 Session Introduction to Web Application Development 3.1 Introduction to Web Applications Web applications can be defined as a software entity that comprises Servlets, JSPs, static HTML pages, classes, and resources such as databases working in collaboration with each other to implement certain functionality of a particular domain. Web applications are accessed by the clients through Web browsers or other Web clients. Various components of the application interact through Hyper Text Transfer Protocol (HTML). In order to understand the function of each component of the Web application, the flow of data from the client to server and response from server to client must be summarized first and the steps for doing so are as follows: 1. A Web application consists of various components. On the server, it can be deployed as a Web component which handles the function of communication over the Internet and a business component which performs the functions specific to the domain. 2. The data flow starts from the client when it sends a request to the server. The client request is converted to an HTTPRequest so that it can traverse through the Internet. 3. The HTTPRequest from the client is received by the Web server and the appropriate servlet is invoked. The Web server receives the client request and identifies the servlet to which this request has to be forwarded. The Web server does the required processing, if any, to forward the request to the servlet. It converts the HTTPRequest object into an HTTPServletRequest object, so that it can invoke the appropriate servlet. 4. The servlets form the Web components of the application which generate dynamic Web pages as response to a client request. These servlets interact with the business components of the application and construct the response to the request. JavaServer Pages (JSP), Servlets, and JavaServer Faces (JSF) can be used as the Web components. The difference among these three components is that, in JSPs, the Java code is embedded in HTML code. The JSPs generate the Web pages after receiving the response from Servlets. Servlets usually do not focus on the presentation, but on processing the client request and give appropriate re- sponse to the request. Servlets can also perform data formatting by embedding HTML code within Java code for formatting the Web page. JavaServer Faces (JSF) are used to generate response Web pages. JSFs are components for UI design where the design is based on XML files known as view templates or facelet views. 5. The response to the client request is sent back to the client in the HTTP format. The client which is usually a browser interprets the response as a Web page and presents it to the client. All these Web components are supported by a Web container. Web container provides multithread- Concepts ing, resource pooling, and other resource management functions to the Web components. V 1.0 © Aptech Limited 3 Session Introduction to Web Application Development Figure 3.1 shows how client requests are handled in Web applications. Figure 3.1: Handling Client Requests The behavior of the Web application can also be configured during deployment through deployment descriptors. The configuration specifications can be given through annotations and maintained in an XML file. This XML file is known as deployment descriptor. 3.2 Web Application Life Cycle While developing Web applications, the various components of the application need to be developed independently and should be integrated to work together as a single application. The steps for developing a Web application can be summarized as follows: 1. Decide the scope and requirements of the Web application scenario. 2. Decide on the architecture of the applications whether it will be a Two-tier (Client-Server) architecture, 3-tier, or n-tier. 3. Identify the layers and Web components required for developing the application including the database. Concepts 4. Create Unified Modelling Diagrams (UMLs) to identify the users, classes, and other components required for the application. 5. Develop the code for different components of the Web application. V 1.0 © Aptech Limited 3 Session Introduction to Web Application Development Components of a Web application can be Web pages, CSS style sheets for the Web pages, Servlets, JSPs, JSFs, and so on. The developer has to write code for all these components. In order to decide upon the components required for an application, a design phase of the application should pre- cede the coding phase. 6. Develop a Web application deployment descriptor. A Web application deployment descriptor is an XML file, which has instructions about the deploy- ment of the application. This file specifies the security settings required by the application, the configuration settings, and the container options. The deployment descriptor of a Web application is always a file named, web.xml which is located in WEB-INF subdirectory of the application. Any deployment tool will access the deployment descriptor and deploy the application according to the instructions in the configuration file. 7. Compile the Web application along with the helper classes required by the application. Helper classes are also Java classes. While creating an application, the developer may create class- es for independent functionalities. For instance, consider an example of a shopping portal where Shopping_Portal is the main class. In this application, processing the payment is an independent process, therefore, this task can be delegated to an independent object. The developer may create another class Payment_Process and create an object of this type and delegate the task of pro- cessing the payment to this object. In this case, the class Payment_Process is a helper class to the Shopping_Portal class. Once all the classes are coded, they are compiled to generate respective class files. 8. After compilation is done, the application can be packaged into an archive file. The Web applications can however be installed as open file structures also. In order to package it into an archive file, creating the deployment descriptor file becomes essential. 9. Deploy the application into a Web container. The general interpretation of deployment is to locate all the components in their relative positions, ready to run. In case of Java Web applications, all the components are encapsulated into a contain- er where the container provides the required platform services to the application. 10. Once the application is deployed, the application is accessible through the URL. 3.3 HTTP Request and Response Hyper Text Transfer Protocol (HTML) is a standard communication protocol for the Internet. It defines the process of communication between two communicating entities on the Internet. In Java Web applications, Concepts different components of the application communicate using HTTP. The protocol functions according to request-response model. Initially, it was defined for client-server architecture where the client sends a request to the server to which, the server responds with appropriate HTML content. It uses the services of the other protocols such as Transmission Control Protocol (TCP), User Datagram Protocol (UDP), and so on. V 1.0 © Aptech Limited 3 Session Introduction to Web Application Development HTTP identifies all the resources through Universal Resource Locators (URLs). Whenever a client requests for a resource or service, an HTTP session is established between the client and the server. HTTP session can be defined as a sequence of client requests and responses from the server between a client and server pair. HTTP defines various methods for performing operations. Table 3.1 summarizes the methods used by HTTP. Method Description GET Retrieves data from a server, where the server is identified through an URL. Data sent using GET is visible in the URL. PUT Creates a resource or modifies an existing resource on the server. In this method, the URL is also required to identify the server. POST Submits certain values to the server, such as values from a Web form after submission of the form and so on. Data sent using POST is not visible in the URL. DELETE As the name suggests, DELETE method is used to delete resources. TRACE This method is used to identify the servers between the HTTP client and server. It is generally used to obtain routing statistics. OPTIONS This method can be used to check the functionalities that can be extended by the Web server for certain URLs. CONNECT This method is used to connect to the server. The connection may or may not be secure. It may be a TCP connection or UDP connection. All these properties are defined while creating a connection. PATCH Patch generally means a partial modification. For example, partial modifications to the HTTP server. Table 3.1: HTTP Methods The Web components of a Java application communicate through HTTP. Therefore, Java provides various classes for HTTP communication. Following are the classes used for HTTP communication in Java: ÎÎ HttpURLConnection - Handles all the HTTP connectivity related tasks in Java EE7 ÎÎ HttpServletRequest – Creates an object of servlet request which uses HTTP ÎÎ HttpServletResponse – Creates an object of servlet response which also uses HTTP Concepts ÎÎ HttpsURLConnection – Used to make secure URL connections ÎÎ HTTP.HttpRequest – Used to create HTTP request ÎÎ HttpResponse - Used to create HTTP response V 1.0 © Aptech Limited 3 Session Introduction to Web Application Development 3.4 Introduction to Web Components As mentioned earlier, a Web application has various components such as JavaServer Pages, JavaServer Faces, Servlets, and so on. The components are explained briefly in the following sections: ÎÎ JavaServer Pages JavaServer Pages enable the developers to create dynamic, interactive Web pages. It has a standard tag library, where the tags defined in the library carry out general functions required in most of the Web applications. According to the MVC architecture, JSP can be used to define the view of the application along with Servlets and Java beans. Java beans can implement the model of the application and Servlets implement the controller. ÎÎ Servlets Servlets are server-side programs which extend the capabilities of the server to support processing of data. javax.servlet and javax.servlet.http are packages in Java which support servlet implementa- tion. Servlets can access database, JSPs, and also user interface components. They communicate with various components of the Web application using HTTP as the communication protocol. ÎÎ JavaBeans Java beans are reusable software components which are coded according to JavaBeans API specifi- cation. Java beans should be serializable implementing the Serializable interface. They define get- ter and setter methods for various properties of the class. Java beans are designed to interoperate with legacy components of the Internet and provide components to the Web applications. ÎÎ JavaServer Faces JavaServer Faces are used to develop a component based user interface for Web applications which is compatible with XML files. It makes use of view templates written in XML. These view templates are known as Facelets. The specification is provided as an API with the Java EE. JSF can be seen as a combination of Struts and Swing. The features provided by JSF for developing Web application user interface can be summarized as follows: yy Allows the developer to create user interface components from templates yy Supports JSP tags to access the user interface components Concepts yy Saves the state of the UI components transparently yy Capable of event handling and component rendering mechanisms, which makes it compatible with other markup languages, such as HTML V 1.0 © Aptech Limited 3 Session Introduction to Web Application Development 3.5 Introduction to Web Services Web services are Web based programs through which a specific service is implemented. These programs can be accessed by end users through client programs, such as browsers or by other machines as part of a larger application. Web services also use Internet protocols similar to Web applications. However, the difference is that the Web services can be accessed by both end users and machines whereas Web applications are accessed through end users only. Web services are Web based programs through which a specific service is implemented. They are similar to Web applications but not the same. Web applications are primarily accessed by users through browsers. Apart from users, other machines on the Internet can also access the application. Consider an application of a shopping portal, where end users access the product list and place order for a product. Once the order is placed and card details are provided to complete the payment process, the interaction with the end user suspends and another thread of interaction with the payment server starts. Here, the shopping portal server accesses the payment gateway with credit card/debit card details. Since the shopping portal server is accessing the services of the payment gateway, the payment gateway is termed as a Web service. Various standards and technologies are used for implementation of Web services such as SOAP, REST, XML, and so on. Based on the standard used, there are two types of Web services: 1. Simple Object Access Protocol (SOAP) Web services JAX-WS is the Java specification for implementing SOAP Web services. 2. Representational State Transfer (REST) Web services JAX-RS is the Java specification for implementing REST Web services. 3.6 Creating a Simple Web Application Using Netbeans IDE As mentioned earlier, a Web application has several components. The following demonstration shows how these different components work together. In order to create the Web application in Netbeans IDE that accepts user input in a textbox and displays it on another page, perform the following steps: 1. Select File → New Project. The New Project dialog box is displayed as shown in figure 3.2. Concepts V 1.0 © Aptech Limited 3 Session Introduction to Web Application Development Figure 3.2: Creating a New Application 2. Select Java Web → Web Application and click Next. The New Web Application screen will be displayed prompting for a Web application name as shown in figure 3.3. 3. Specify an appropriate Web application name and click Next. The target folders for saving the project are specified by default as shown in figure 3.3. Concepts V 1.0 © Aptech Limited 3 Session Introduction to Web Application Development Figure 3.3: Naming the Web Application It is recommended to select the Use Dedicated Folder for Storing Libraries checkbox in this window. 4. In the Server and Settings screen, select the Web server on which the application is supposed to be deployed and click Next. Figure 3.4 shows the list of servers registered with Netbeans displayed. Concepts Figure 3.4: Selecting the Web Server V 1.0 © Aptech Limited 3 Session Introduction to Web Application Development 5. After selecting the Web server, the IDE prompts for any frameworks that will be used in the application. This application does not use any frameworks hence, click Next. 6. Click Finish, the Web application is created with folders pertaining to the project as shown in figure 3.5. Figure 3.5: Project Folder Among these folders, currently three folders namely, Source Packages, Web Pages, and Libraries are being used. The folder Source Packages comprises all the Java classes and beans pertaining to the application. The Web Pages folder comprises the JSPs, html pages, xml pages, and so on. The Li- braries folder comprises the JDK and Glassfish server (or any other server used by the application). The current ‘HelloWeb’ application has a bean, a user interface, and a jsp page. The bean of the application is created first. The bean defines the actual function of the application. In this case, the bean is substituting the name accepted from the user. 7. Right-click Source Packages and add a new package named, hello by selecting New Package from the menu. Add a new Java class to the package. Right-click the hello package and select New → JavaClass. Name the class as TextInput.java. 8. Add a string variable to the class as follows: String name; Concepts V 1.0 © Aptech Limited 3 Session Introduction to Web Application Development 9. Right-click the variable name and select Refactor → Encapsulate Fields from the menu. This selection will open a window as shown in figure 3.6. Figure 3.6: Creating Getter and Setter Methods for the Variable 10. Select the required checkboxes and click Refactor. The selected getter and setter methods will be created. After creating the getter and setter methods for the name variable, the code in the bean for the application will be as shown in Code Snippet 1. Code Snippet 1: public class TextInput { private String name; public TextInput(){ name = null; } Concepts public String getName() { return username; } public void setName(String name) { this.name = name; } } V 1.0 © Aptech Limited 3 Session Introduction to Web Application Development This completes the bean creation process o