Вы находитесь на странице: 1из 83

WEB TECHNOLOGY UNIT I 1.

Web services architecture

1.1.1 1.1 Purpose of the Web Service Architecture


Web services provide a standard means of interoperating between different software applications, running on a variety of platforms and/or frameworks. This document (WSA) is intended to provide a common definition of a Web service, and define its place within a larger Web services framework to guide the community. The WSA provides a conceptual model and a context for understanding Web services and the relationships between the components of this model. The architecture does not attempt to specify how Web services are implemented, and imposes no restriction on how Web services might be combined. The WSA describes both the minimal characteristics that are common to all Web services, and a number of characteristics that are needed by many, but not all, Web services. The Web services architecture is an interoperability architecture: it identifies those global elements of the global Web services network that are required in order to ensure interoperability between Web services.

1.1.2

1.2 Intended Audience

This document is intended for a diverse audience. Expected readers include Web service specification authors, creators of Web service software, people making decisions about Web service technologies, and others.
1.1.3 1.3 Document Organization

This document has two main sections: a core concepts section (2 Concepts and Relationships ) and a stakeholder's perspectives section (3 Stakeholder's Perspectives). 2 Concepts and Relationships provides the bulk of the conceptual model on which conformance constraints could be based. For example, the resource concept states that resources have identifiers (in fact they have URIs). Using this assertion as a basis, we can assess conformance to the architecture of a particular resource by looking for its identifier. If, in a given instance of this architecture, a resource has no identifier, then it is not a valid instance of the architecture. While the concepts and relationships represent an enumeration of the architecture, the stakeholders' perspectives approaches from a different viewpoint: how the architecture meets the goals and requirements. In this section we elucidate the more global properties of the architecture and demonstrate how the concepts actually achieve important objectives. A primary goal of the Stakeholder's Perspectives section is to provide a top-down view of the architecture from various perspectives. For example, in the 3.6 Web Services Security section we show how the security of Web services is addressed within the architecture. The aim here is to demonstrate that Web services can be made secure and indicate which key concepts and features of the architecture achieve that goal. The key stakeholder's perspectives supported in this document reflect the major goals of the architecture itself: interopability, extensibility, security, Web integration, implementation and manageability.
1.1.4 1.4 What is a Web service?

For the purpose of this Working Group and this architecture, and without prejudice toward other definitions, we will use the following definition:

[Definition: A Web service is a software system designed to support interoperable machine-to-machine interaction over a network. It has an interface described in a machine-processable format (specifically WSDL). Other systems interact with the Web service in a manner prescribed by its description using SOAP messages, typically conveyed using HTTP with an XML serialization in conjunction with other Web-related standards.]
1.1.4.1 1.4.1 Agents and Services

A Web service is an abstract notion that must be implemented by a concrete agent. (See Figure 1-1) The agent is the concrete piece of software or hardware that sends and receives messages, while the service is the resource characterized by the abstract set of functionality that is provided. To illustrate this distinction, you might implement a particular Web service using one agent one day (perhaps written in one programming language), and a different agent the next day (perhaps written in a different programming language) with the same functionality. Although the agent may have changed, the Web service remains the same.
1.1.4.2 1.4.2 Requesters and Providers

The purpose of a Web service is to provide some functionality on behalf of its owner -- a person or organization, such as a business or an individual. The provider entity is the person or organization that provides an appropriate agent to implement a particular service. (See Figure 1-1: Basic Architectural Roles.) A requester entity is a person or organization that wishes to make use of a provider entity's Web service. It will use a requester agent to exchange messages with the provider entity's provider agent. (In most cases, the requester agent is the one to initiate this message exchange, though not always. Nonetheless, for consistency we still use the term "requester agent" for the agent that interacts with the provider agent, even in cases when the provider agent actually initiates the exchange.) Note: A word on terminology: Many documents use the term service provider to refer to the provider entity and/or provider agent. Similarly, they may use the term service requester to refer to the requester entity and/or requester agent. However, since these terms are ambiguous -- sometimes referring to the agent and sometimes to the person or organization that owns the agent -- this document prefers the terms requester entity, provider entity, requester agent and provider agent.

In order for this message exchange to be successful, the requester entity and the provider entity must first agree on both the semantics and the mechanics of the message exchange. (This is a slight simplification that will be explained further in 3.3 Using Web Services.)
1.1.4.3 1.4.3 Service Description

The mechanics of the message exchange are documented in a Web service description (WSD). (See Figure 1-1) The WSD is a machine-processable specification of the Web service's interface, written in WSDL. It defines the message formats, datatypes, transport protocols, and transport serialization formats that should be used between the requester agent and the provider agent. It also specifies one or more network locations at which a provider agent can be invoked, and may provide some information about the message exchange pattern that is expected. In essence, the service description represents an agreement governing the mechanics of interacting with that service. (Again this is a slight simplification that will be explained further in 3.3 Using Web Services.)
1.1.4.4 1.4.4 Semantics

The semantics of a Web service is the shared expectation about the behavior of the service, in particular in response to messages that are sent to it. In effect, this is the "contract" between the requester entity and the provider entity regarding the purpose and consequences of the interaction. Although this contract represents the overall agreement between the requester entity and the provider entity on how and why their respective agents will interact, it is not necessarily written or explicitly negotiated. It may be explicit or implicit, oral or written, machine processable or human oriented, and it may be a legal agreement or an informal (non-legal) agreement. (Once again this is a slight simplification that will be explained further in 3.3 Using Web Services.) While the service description represents a contract governing the mechanics of interacting with a particular service, the semantics represents a contract governing the meaning and purpose of that interaction. The dividing line between these two is not necessarily rigid. As more semantically rich languages are used to describe the mechanics of the interaction, more of the essential information may migrate from the informal semantics to the service description. As this migration occurs, more of the work required to achieve successful interaction can be automated.
1.1.4.5

2. Overview of Engaging a Web Service

There are many ways that a requester entity might engage and use a Web service. In general, the following broad steps are required, as illustrated in Figure 1-1: (1)

the requester and provider entities become known to each other (or at least one becomes know to the other); (2) the requester and provider entities somehow agree on the service description and semantics that will govern the interaction between the requester and provider agents; (3) the service description and semantics are realized by the requester and provider agents; and (4) the requester and provider agents exchange messages, thus performing some task on behalf of the requester and provider entities. (I.e., the exchange of messages with the provider agent represents the concrete manifestation of interacting with the provider entity's Web service.) These steps are explained in more detail in 3.4 Web Service Discovery. Some of these steps may be automated, others may be performed manually.

Figure 1-1. The General Process of Engaging a Web Service

3.service oriented roles and architecture


Service-oriented architecture (SOA) is a flexible set of design principles used during the phases of systems development and integration in computing. A system based on a SOA architecture will provide a loosely-coupled[further explanation needed] suite

of services that can be used within multiple separate systems from several business domains. SOA also generally provides a way for consumers of services, such as web-based applications, to be aware of available SOA-based services. For example, several disparate departments within a company may develop and deploy SOA services in different implementation languages; their respective clients will benefit from a well understood, well defined interface to access them. XML is commonly used for interfacing with SOA services, though this is not required. SOA defines how to integrate widely disparate applications for a Web-based environment and uses multiple implementation platforms. Rather than defining an API, SOA defines the interface in terms of protocols and functionality. An endpoint is the entry point for such a SOA implementation. Service-orientation requires loose coupling of services with operating systems, and other technologies that underlie applications. SOA separates functions into distinct units, or services,[1] which developers make accessible over a network in order to allow users to combine and reuse them in the production of applications. These services and their corresponding consumers communicate with each other by passing data in a well-defined, shared format, or by coordinating an activity between two or more services.[2]
One can consider SOA a continuum, as opposed to distributed computing or modular programming. 1 Description

1.1 Overview 1.2 Requirements 1.3 Principles 1.4 Web services approach 1.5 SOA and Web service protocols 1.6 Other SOA concepts 1.7 SOA definitions 1.8 Service contract 1.9 SOA and network management architecture

1.2 1.2.1

Description Overview

SOA implementations rely on a mesh of software services. Services comprise unassociated, loosely coupled units of functionality that have no calls to each other

embedded in them. Each service implements one action, such as filling out an online application for an account, or viewing an online bank statement, or placing an online booking or airline ticket order. Rather than services embedding calls to each other in their source code, they use defined protocols that describe how services pass and parse messages using description metadata. SOA developers associate individual SOA objects by using orchestration. In the process of orchestration the developer associates software functionality (the services) in a non-hierarchical arrangement using a software tool that contains a complete list of all available services, their characteristics, and the means to build an application utilizing these sources. Underlying and enabling all of this requires metadata in sufficient detail to describe not only the characteristics of these services, but also the data that drives them. Programmers have made extensive use of XML in SOA to structure data that they wrap in a nearly exhaustive description-container. Analogously, the Web Services Description Language (WSDL) typically describes the services themselves, while the SOAP protocol describes the communications protocols. Whether these description languages are the best possible for the job, and whether they will become/remain the favorites in the future, remain open questions. As of 2008 SOA depends on data and services that are described by metadata that should meet the following two criteria: 1. The metadata should come in a form that software systems can use to configure dynamically by discovery and incorporation of defined services, and also to maintain coherence and integrity. For example, metadata could be used by other applications, like a catalogue, to perform autodiscovery of services without modifying the functional contract of a service. 2. The metadata should come in a form that system designers can understand and manage with a reasonable expenditure of cost and effort. SOA aims to allow users to string together fairly large chunks of functionality to form ad hoc applications that are built almost entirely from existing software services. The larger the chunks, the fewer the interface points required to implement any given set of functionality; however, very large chunks of functionality may not prove sufficiently granular for easy reuse. Each interface brings with it some amount of processing overhead, so there is a performance consideration in choosing the granularity of services. The great promise of SOA suggests that the marginal cost of creating the n-th application is low, as all of the software required already exists to satisfy the requirements of other applications. Ideally, one requires only orchestration to produce a new application.

For this to operate, no interactions must exist between the chunks specified or within the chunks themselves. Instead, humans specify the interaction of services (all of them unassociated peers) in a relatively ad hoc way with the intent driven by newly emergent requirements. Thus the need for services as much larger units of functionality than traditional functions or classes, lest the sheer complexity of thousands of such granular objects overwhelm the application designer. Programmers develop the services themselves using traditional languages like Java, C, C++, C#, Visual Basic, COBOL, or PHP. SOA services feature loose coupling, in contrast to the functions that a linker binds together to form an executable, to a dynamically linked library or to an assembly. SOA services also run in "safe" wrappers (such as Java or .NET) and in other programming languages that manage memory allocation and reclamation, allow ad hoc and late binding, and provide some degree of indeterminate data typing. As of 2008, increasing numbers of third-party software companies offer software services for a fee. In the future, SOA systems may[original research?] consist of such third-party services combined with others created in-house. This has the potential to spread costs over many customers and customer uses, and promotes standardization both in and across industries. In particular, the travel industry now has a well-defined and documented set of both services and data, sufficient to allow any reasonably competent software engineer to create travel-agency software using entirely off-the-shelf software services.[3] Other industries, such as the finance industry, have also started making significant progress in this direction. SOA as an architecture relies on service-orientation as its fundamental design principle.[4] If a service presents a simple interface that abstracts away its underlying complexity, users can access independent services without knowledge of the service's platform implementation.[5]
1.2.2 1.2.3

Requirements

In order to efficiently use a SOA, the architecture must meet the following requirements:

Interoperability among different systems and programming languages that provides the basis for integration between applications on different platforms through a communication protocol. One example of such communication depends on the concept of messages. Using messages across defined message channels decreases the complexity of the end

application, thereby allowing the developer of the application to focus on true application functionality instead of the intricate needs of a communication protocol. Desire to create a federation of resources. Establish and maintain data flow to a Federated database system. This allows new functionality developed to reference a common business format for each data element.

1.2.4

Principles

The following guiding principles define the ground rules for development, maintenance, and usage of the SOA[6]:

reuse, granularity, modularity, composability, componentization and interoperability. standards-compliance (both common and industry-specific). services identification and categorization, provisioning and delivery, and monitoring and tracking.

The first publicly published research of service-orientation from an industry perspective was provided by Thomas Erl of SOA Systems Inc. who defined eight specific service-orientation principles common to all primary SOA platforms. These principles were published in Service-Oriented Architecture: Concepts, Technology, and Design, on the www.soaprinciples.com research site, and in the September 2005 edition of the Web Services Journal (see Service-orientation).

Standardized Service Contract Services adhere to a communications agreement, as defined collectively by one or more service-description documents. Service loose coupling Services maintain a relationship that minimizes dependencies and only requires that they maintain an awareness of each other. Service Abstraction Beyond descriptions in the service contract, services hide logic from the outside world. Service Reusability Logic is divided into services with the intention of promoting reuse. Service Autonomy Services have control over the logic they encapsulate. Service Statelessness - Services minimize resource consumption by deferring the management of state information when necessary

Service Discoverability Services are supplemented with communicative meta data by which they can be effectively discovered and interpreted. Service Composability Services are effective composition participants,regardless of the size and complexity of the composition.

Some authors also include the following principles:


Service optimization All else equal, high-quality services are generally preferable to low-quality ones. Service relevance Functionality is presented at a granularity recognized by the user as a meaningful service. Service encapsulation Many services are consolidated for use under the SOA. Often such services were not planned to be under SOA.

The following references provide additional considerations for defining a SOA implementation:

SOA Reference Architecture provides a working design of an enterprisewide SOA implementation with detailed architecture diagrams, component descriptions, detailed requirements, design patterns, opinions about standards, patterns on regulation compliance, standards templates etc.[7]. Life cycle management SOA Practitioners Guide Part 3: Introduction to Services Lifecycle introduces the services lifecycle and provides a detailed process for services management through the service lifecycle, from inception to retirement or repurposing of the services. It also contains an appendix that includes organization and governance best-practices, templates, comments on key SOA standards, and recommended links for more information.

In addition, one might take the following factors into account when defining a SOA implementation:

efficient use of system resources service maturity and performance EAI (Enterprise Application Integration)

1.2.5

Web services approach

Web services can implement a service-oriented architecture. Web services make functional building-blocks accessible over standard Internet protocols independent

of platforms and programming languages. These services can represent either new applications or just wrappers around existing legacy systems to make them network-enabled. Each SOA building block can play one or both of two roles:
1. Service Provider - The service provider creates a web service and possibly

publishes its interface and access information to the service registry. Each provider must decide which services to expose, how to make trade-offs between security and easy availability, how to price the services, or (if no charges apply) how/whether to exploit them for other value. The provider also has to decide what category the service should be listed in for a given broker service and what sort of trading partner agreements are required to use the service. It registers what services are available within it, and lists all the potential service recipients. The implementer of the broker then decides the scope of the broker. Public brokers are available through the Internet, while private brokers are only accessible to a limited audience, for example, users of a company intranet. Furthermore, the amount of the offered information has to be decided. Some brokers specialize in many listings. Others offer high levels of trust in the listed services. Some cover a broad landscape of services and others focus within an industry. Some brokers catalog other brokers. Depending on the business model, brokers can attempt to maximize look-up requests, number of listings or accuracy of the listings. The Universal Description Discovery and Integration (UDDI) specification defines a way to publish and discover information about Web services. Other service broker technologies include (for example) ebXML (Electronic Business using eXtensible Markup Language) and those based on the ISO/IEC 11179 Metadata Registry (MDR) standard. 2. Service consumer - The service consumer or web service client locates entries in the broker registry using various find operations and then binds to the service provider in order to invoke one of its web services. Whichever service the service-consumers need, they have to take it into the brokers, then bind it with respective service and then use it. They can access multiple services if the service provides multiple services.
1.2.6

SOA and Web service protocols

Implementors commonly build SOAs using web services standards (for example, SOAP) that have gained[when?] broad industry acceptance. These standards (also referred to as Web Service specifications) also provide greater interoperability and some protection from lock-in to proprietary vendor software. One can, however,

implement SOA using any service-based technology, such as Jini, CORBA or REST.
1.2.7

Other SOA concepts

Architectures can operate independently of specific technologies Thomas Erl [8]. Designers can implement SOA using a wide range of technologies, including:

SOAP, RPC REST DCOM CORBA Web Services DDS WCF (Microsoft's implementation of Webservice forms a part of WCF)

Implementations can use one or more of these protocols and, for example, might use a file-system mechanism to communicate data conforming to a defined interface-specification between processes conforming to the SOA concept. The key is independent services with defined interfaces that can be called to perform their tasks in a standard way, without a service having foreknowledge of the calling application, and without the application having or needing knowledge of how the service actually performs its tasks. Many implementers of SOA have begun[when?] to adopt an evolution of SOA concepts into a more advanced[citation needed] architecture called SOA 2.0.

Elements of SOA, by Dirk Krafzig, Karl Banke, and Dirk Slama[9]

SOA meta-model, The Linthicum Group, 2007

Service-Oriented Modeling Framework (SOMF) Version 2.0

SOA enables the development of applications that are built by combining loosely coupled and interoperable services[10]. These services inter-operate based on a formal definition (or contract, e. g., WSDL) that is independent of the underlying platform and programming language. The interface definition hides the implementation of the languagespecific service. SOA-based systems can therefore function independently of development technologies and platforms (such as Java, .NET, etc.). Services written in C# running on .NET platforms and services written in Java running on Java EE platforms, for example, can both be consumed by a common composite application (or client). Applications running on either platform can also consume services running on the other as web services that facilitate reuse. Managed environments can also wrap COBOL legacy systems and present them as software services. This has extended the useful life of many core legacy systems indefinitely, no matter what language they originally used. SOA can support integration and consolidation activities within complex enterprise systems, but SOA does not specify or provide a methodology or framework for documenting capabilities or services. High-level languages such as BPEL and specifications such as WS-CDL and WSCoordination extend the service concept by providing a method of defining and supporting orchestration of fine-grained services into more coarse-grained business services, which architects can in turn incorporate into workflows and business processes implemented in composite applications or portals[citation needed]. As of 2008 researchers have started investigating the use of Service Component Architecture (SCA) to implement SOA. Service-oriented modeling [1] is an SOA framework that identifies the various disciplines that guide SOA practitioners to conceptualize, analyze, design, and architect their service-oriented assets. The Service-oriented modeling framework (SOMF) offers a modeling language and a work structure or "map" depicting the various components that contribute to a successful service-oriented modeling approach. It illustrates the major elements that identify the what to do aspects of a service development scheme. The model enables practitioners to craft a project plan and to identify the milestones of a service-oriented initiative. SOMF also provides a common modeling notation to address alignment between business and

IT organizations.

SOMF addresses the following principles:


business traceability architectural best-practices traceability technological traceability SOA value proposition software assets reuse SOA integration strategies technological abstraction and generalization architectural components abstraction

1.2.8

SOA definitions

Commentators have provided multiple definitions of SOA. The OASIS group[11] and the Open Group[12] have both created formal definitions.

OASIS defines SOA as the following: A paradigm for organizing and utilizing distributed capabilities that may be under the control of different ownership domains. It provides a uniform means to offer, discover, interact with and use capabilities to produce desired effects consistent with measurable preconditions and expectations.

1.2.9

Service contract

A service contract needs[citation needed] to have the following components:

Header o Name Name of the service. This should indicate in general terms what the service does, not just its definition o Version The version of this service contract o Owner The person/team in charge of the service o Responsibility assignment (RACI) Responsible The role/person/team responsible for the deliverables of this contract/service. All versions of the contract Accountable Ultimate Decision Maker in terms of this contract/service Consulted Whom one must consult before action is taken on this contract/service. This is two-way communication. These people have an impact on the decision or the execution of that decision. Informed Who must be informed that a decision or action is being taken. This is a one-way communication. These people are impacted by the decision or execution of that decision, but have no control over the action. o Type This is the type of the service: to help distinguish the layer in which it resides. Different implementations will have different service types. Examples of service types include: Presentation Process Business Data Integration Functional o Functional Requirement (from Requirements Document) Indicates the functionality in specific bulleted items what exactly this

service accomplishes. The language should encourage test cases to prove the functionality is accomplished. o Service Operations Methods, actions etc. Must be defined in terms of what part of the functionality it provides. o Invocation Indicates how to invoke the service. This includes the URL, interface, etc. There may be multiple invocation paths for the same service. One may have the same functionality for an internal and some external clients, each with different invocation means and interfaces. Examples: SOAP REST Events Triggers Non-Functional o Security Constraints Defines who can execute this service in terms of roles or individual partners etc. and which invocation mechanism they can invoke. o Quality of Service Determines the allowable failure rate o Transactional Is this capable of acting as part of a larger transaction and if so, how do we control that? o Service Level Agreement Determines the amount of latency the service is allowed to have to perform its actions o Semantics Dictates or defines the meaning of terms used in the description and interfaces of the service o Process Describes the process, if any, of the contracted service

1.2.10 SOA and network management architecture

As of 2008 the principles of SOA are being applied[by whom?] to the field of network management. Examples of service-oriented network management architectures include TS 188 001 NGN Management OSS Architecture from ETSI, and M.3060 Principles for the Management Of Next Generation Networks recommendation from the ITU-T. Tools for managing SOA infrastructure include:

HP Software & Solutions HyPerformix IPS Performance Optimizer IBM Tivoli Framework

4.architectural process
Drawn from some of Jim Conallen's writings, he offers the representation of a canonical Web architecture:

The right-most elements -- the file system, the application sever, data, and external systems -- are essentially the same as found in traditional client/server systems. The left-most elements -- the browser, the Web server, and again the file system (in this case, a distributed one) -- are elements unique to the Web space. From the perspective of the user experience, this otherwise physically distributed back-end looks like traditional mainframe computing. However, there are significant architectural differences owing to the very different mechanisms that tie these elements together. For example, from the browser to the Web server, communication is generally stateless, involving the request for, and then the delivery of, a Web page. Here's the first architectural challenge: how do you preserve the user's session state? There are a number of alternatives, of which cookies and communication via IIOP (the Internet Inter-Orb Protocol) are the most common. The placement of the application's business logic represents another architectural challenge: should it live in the server (the thin client model), should it live in the client (the fat client/thin server model), or should it be spread out overall? In the spectrum of thin to thick client, each alternative has its own advantages and disadvantages: a thin client offers simplicity of security and distribution but makes the browser look more like a dumb terminal; a thick client offers greater locality of reference and better interactivity but at the cost of distribution. Most systems today tend to push business logic to the server. Business logic must touch the state of the business. This notion presents the next architectural challenge. Should there be stateless communication from the logic to the data via mechanisms such as Java Server Pages (JSP), or should it be more stateful, such as through servlets? Again, there are advantages and disadvantages to each approach. Scripting is easier to change but comes with computational overhead, and servlets are potentially faster but more challenging to develop and deploy.

Connection to the application's persistence data, which may be bound in legacy systems, also involves many architectural challenges. First, how does one give the illusion of objects to the user while data continues to live in relational tables? Second, how should the connection from the system's business logic to its data be manifest? For example, a coupling via JDBC is more direct but requires that the application developer have intimate knowledge of the data's form. Alternatively, a messaging architecture is less direct but is more scalable.

Architectural views
Philippe Kruchten, of Rational Software, has observed that complex systems cannot be understood from just a single viewpoint. Indeed, the previous diagram is really only a simple view of a system's deployment. Philippe has pioneered the concept of a 4+1 model view, as illustrated below:

A system's design view encompasses the classes, interfaces, and collaborations that form the vocabulary of the problem and its solution. This view primarily supports the functional requirements of the system, meaning the services that the system should provide to its end-users. The process view of a system encompasses the threads and processes that form the system's concurrency and synchronization mechanisms. This view primarily addresses the performance, scalability, and throughput of the system.

The implementation view of a system encompasses the components and files that are used to assemble and release the physical system. This view primarily addresses the configuration management of the system's releases. The releases are comprised of somewhat independent components and files that can be assembled in various ways to produce a running system. The deployment view of a system encompasses the nodes that form the system's hardware topology on which the system executes. This view primarily addresses the distribution, delivery, and installation of the parts that make up the physical system. The use case view of a system encompasses the use cases that describe the behavior of the system as seen by its end-users, analysts, and testers. This view exists to specify the forces that shape the system's architecture. Note that this is where the UML fits in: the UML is a graphical language for visualizing, specifying, constructing, and documenting the artifacts of a softwareintensive system. Thus, it is well suited to express each of these five views.

Architectural patterns
One of the most important developments in software engineering in the past few years has been the realization that all well structured systems are full of patterns. In its classical definition, drawn from the work of the architect Christopher Alexander, a pattern is a solution to a problem in a context. A pattern codifies specific knowledge from experience in a given domain and offers a common solution that resolves the forces that press upon a system. Ultimately, we come back to our starting point. For all kinds of computing systems, and for Web applications in particular, a number of common patterns are emerging for resolving the forces in that domain. Mechanisms, such as described in Gamma, Vlissides, Johnson, and Helm's seminal book, Design Patterns, represent the codification of collaborations among societies of classes that must work together. Architectural patterns are emerging as well, giving us the means to express the common architecture of simple Web sites to what is essentially an "Amazon-in-a-box."

5.THREE TIER WEB BASED ARCHITECTURE

PRESENTATION TIER
This is the topmost level of the application The presentation tier displays information related to such services as browsing , purchasing, and shopping cart contents. It communicates with other tiers by outputting results to the browser/client tier and all other tiers in the network.

APPLICATION TIER
The logic tier is pulled out from the presentation tier and, as its own layer, it controls an applications functionality by performing detailed processing.

DATA TIER
This tier consists of database servers. Here information is stored and retrieved. This tier keeps data neutral and independent from application servers or business logic. Giving data its own tier also improves scalability and performance

UNIT II

Introduction to XML Extensible Markup Language 1.XML


What is XML
XML stands for eXtensible Markup Language. A markup language is used to provide information about a document. Tags are added to the document to provide the extra information. HTML tags tell a browser how to display the document. XML tags give a reader some idea what some of the data means.

What is XML Used For?


XML documents are used to transfer data from one place to another often over the Internet. XML subsets are designed for particular applications. One is RSS (Rich Site Summary or Really Simple Syndication ). It is used to send breaking news bulletins from one web site to another. A number of fields have their own subsets. These include chemistry, mathematics, and books publishing. Most of these subsets are registered with the W3Consortium and are available for anyones use

Advantages of XML
<html> <head><title>Example</title></head. <body> <h1>This is an example of a page.</h1> <h2>Some information goes here.</h2> </body> </html> Example of an XML Document <?xml version=1.0/> <address> <name>Alice Lee</name> XML is text (Unicode) based. Takes up less space. Can be transmitted efficiently. One XML document can be displayed differently in different media. Html, video, CD, DVD, You only have to change the XML document in order to change all the rest. XML documents can be modularized. Parts can be reused.

Example of an HTML Document

<email>alee@aol.com</email> <phone>212-346-1234</phone> <birthday>1985-03-22</birthday> </address> Difference Between HTML and XML HTML tags have a fixed meaning and browsers know what it is. XML tags are different for different applications, and users know what they mean. HTML tags are used for display. XML tags are used to describe documents and data. 2.XML FUNDAMENDALS XML Rules Tags are enclosed in angle brackets. Tags come in pairs with start-tags and end-tags. Tags must be properly nested. <name><email></name></email> is not allowed. <name><email></email><name> is. Tags that do not have end-tags must be terminated by a /. <br /> is an html example Tags are case sensitive. <address> is not the same as <Address> XML in any combination of cases is not allowed as part of a tag. Tags may not contain < or &. Tags follow Java naming conventions, except that a single colon and other characters are allowed. They must begin with a letter and may not contain white space. Documents must have a single root tag that begins the document. Encoding XML (like Java) uses Unicode to encode characters. Unicode comes in many flavors. The most common one used in the West is UTF-8. UTF-8 is a variable length code. Characters are encoded in 1 byte, 2 bytes, or 4 bytes. The first 128 characters in Unicode are ASCII. In UTF-8, the numbers between 128 and 255 code for some of the more common characters used in western Europe, such as , , , or . Two byte codes are used for some characters not listed in the first 256 and some Asian ideographs. Four byte codes can handle any ideographs that are left. Those using non-western languages should investigate other versions of Unicode. 3.Well-Formed XML Documents An XML document is said to be well-formed if it follows all the rules.

An XML parser is used to check that all the rules have been obeyed. Recent browsers such as Internet Explorer 5 and Netscape 7 come with XML parsers. Parsers are also available for free download over the Internet. One is Xerces, from the Apache open-source project. Java 1.4 also supports an open-source parser XML Example Revisited <?xml version=1.0/> <address> <name>Alice Lee</name> <email>alee@aol.com</email> <phone>212-346-1234</phone> <birthday>1985-03-22</birthday> </address> Markup for the data aids understanding of its purpose. A flat text file is not nearly so clear. Alice Lee alee@aol.com 212-346-1234 1985-03-22 The last line looks like a date, but what is it for? <?xml version = 1.0 ?> <address> <name> <first>Alice</first> <last>Lee</last> </name> <email>alee@aol.com</email> <phone>123-45-6789</phone> <birthday> <year>1983</year> <month>07</month> <day>15</day> </birthday> </address> XML Trees An XML document has a single root node. The tree is a general ordered tree. A parent node may have any number of children. Child nodes are ordered, and may have siblings. Preorder traversals are usually used for getting information out of the tree.

Validity
A well-formed document has a tree structure and obeys all the XML rules.

A particular application may add more rules in either a DTD (document type definition) or in a schema. Many specialized DTDs and schemas have been created to describe particular areas. These range from disseminating news bulletins (RSS) to chemical formulas. DTDs were developed first, so they are not as comprehensive as schema.

Document Type Definitions


A DTD describes the tree structure of a document and something about its data. There are two data types, PCDATA and CDATA. PCDATA is parsed character data. CDATA is character data, not usually parsed. A DTD determines how many times a node may appear, and how child nodes are ordered.

DTD for address Example


<!ELEMENT address (name, email, phone, birthday)> <!ELEMENT name (first, last)> <!ELEMENT first (#PCDATA)> <!ELEMENT last (#PCDATA)> <!ELEMENT email (#PCDATA)> <!ELEMENT phone (#PCDATA)> <!ELEMENT birthday (year, month, day)> <!ELEMENT year (#PCDATA)> <!ELEMENT month (#PCDATA)> <!ELEMENT day (#PCDATA)>

Schemas
Schemas are themselves XML documents. They were standardized after DTDs and provide more information about the document. They have a number of data types including string, decimal, integer, boolean, date, and time. They divide elements into simple and complex types. They also determine the tree structure and how many children a node may have.

Schema for First address Example


<?xml version="1.0" encoding="ISO-8859-1" ?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="address"> <xs:complexType> <xs:sequence>

<xs:element name="name" type="xs:string"/> <xs:element name="email" type="xs:string"/> <xs:element name="phone" type="xs:string"/> <xs:element name="birthday" type="xs:date"/> </xs:sequence> </xs:complexType> </xs:element>

</xs:schema>
4.Main Components of an XML Document
Elements: <hello> Attributes: <item id=33905> Entities: &lt; (<) Advanced Components CData Sections Processing Instructions

6.XML Stylesheets
Extensible Stylesheet Language (XSL) Language for document transformation Transformation (XSLT) Converting XML to another form Formatting objects (XSL:FO) Layout of XML document Defined by W3C

The Simplest Stylesheet


Empty XSLT document 01 02 03 04 2. 01 02 03 04

<?xml version=1.0 encoding=UTF-16?> <xsl:stylesheet xmlns:xsl=http://www.w3.org/1999/XSL/Transform version=1.0> </xsl:stylesheet> <?xml version=1.0 encoding=UTF-16?> <xsl:stylesheet xmlns:xsl=http://www.w3.org/1999/XSL/Transform version=1.0> </xsl:stylesheet> This will simply copy the text content of the input document to the output. Templates

Features

Map input patterns to output Conditionals Loops Functions Extensions

Templates

Transformation rules Selects nodes from input document Uses XPath expressions Specifies output Can be text, XML, HTML (xml with html tags) Template modes Allows multiple templates to have same rules Named templates

Simple Template

Call templates by name

Match document root <xsl:template match=/> <HTML> <BODY> <xsl:apply-templates select=child::*/> </BODY> </HTML> </xsl:template> For statement <xsl:for-each select='expression'> <xsl:sort select='expression'/> </xsl:for-each>

Loops

XPath Functions
Node-set functions e.g. position(), last(), local-name(), etc String functions e.g. string(), contains(), substring(), etc

Boolean functions e.g. boolean(), not(), etc Number functions e.g. number(), sum(), round(), etc Multiple source documents e.g. document(document2.xml) Keys Number formatting Additional functions e.g. current(), system-property(), etc

XSLT Functions

7.XSL EXAMPLE
<?xml version="1.0" encoding="ISO-8859-1"?> <!-- Edited by XMLSpy --> <catalog> <cd> <title>Empire Burlesque</title> <artist>Bob Dylan</artist> <country>USA</country> <company>Columbia</company> <price>10.90</price> <year>1985</year> </cd> <cd> <title>Hide your heart</title> <artist>Bonnie Tyler</artist> <country>UK</country> <company>CBS Records</company> <price>9.90</price> <year>1988</year> </cd>

XSLT Extensible Stylesheet Language Transformations


XSLT is used to transform one xml document into another, often an html document. The Transform classes are now part of Java 1.4. A program is used that takes as input one xml document and produces as output another.

If the resulting document is in html, it can be viewed by a web browser. This is a good way to display xml data.

A Style Sheet to Transform address.xml


<?xml version="1.0" encoding="ISO-8859-1"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="address"> <html><head><title>Address Book</title></head> <body> <xsl:value-of select="name"/> <br/><xsl:value-of select="email"/> <br/><xsl:value-of select="phone"/> <br/><xsl:value-of select="birthday"/> </body> </html> </xsl:template> </xsl:stylesheet>

OP
Alice Lee alee@aol.com 123-45-6789 1983-7-15

XML and XSL


<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <?xml-stylesheet type="text/xsl" href="tutorials.xsl"?> <tutorials> <tutorial> <name>XML Tutorial</name> <url>http://www.quackit.com/xml/tutorial</url> </tutorial> <tutorial> <name>HTML Tutorial</name> <url>http://www.quackit.com/html/tutorial</url> </tutorial> </tutorials>

XSL
<?xml version="1.0"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="/"> <html> <head> <title>XML XSL Example</title> <style type="text/css">

body { margin:10px; background-color:#ccff00; font-family:verdana,helvetica,sans-serif; } .tutorial-name { display:block; font-weight:bold; } .tutorial-url { display:block; color:#636363; font-size:small; font-style:italic; } </style> </head> <body> <h2>Cool Tutorials</h2> <p>Hey, check out these tutorials!</p> <xsl:apply-templates/> </body> </html> </xsl:template> <xsl:template match="tutorial"> <span class="tutorial-name"> <xsl:value-of select="name"/></span> <span class="tutorial-url"> <xsl:value-of select="url"/></span> </xsl:template> </xsl:stylesheet>

8.CSS (Cascading Style Sheet) INTRODUCTION


CSS stands for Cascading Style Sheets Styles define how to display HTML elements Styles were added to HTML 4.0 to solve a problem External Style Sheets can save a lot of work External Style Sheets are stored in CSS files

Example
<style type="text/css"> body { background-color:blue; } h1 { color:orange; text-align:center; } p { font-family:"Times New Roman";

font-size:20px; }

Styles Solved a Big Problem


HTML was never intended to contain tags for formatting a document. HTML was intended to define the content of a document, like: <h1>This is a heading</h1> <p>This is a paragraph</p> Development of large web sites, where fonts and color information were added to every single page, became a long and expensive process. To solve this problem, the World Wide Web Consortium (W3C) created CSS. It is possible to use CSS to format an XML document. Below is an example of how to use a CSS style sheet to format an XML document:

CSS Syntax

CSS rule has two main parts: a selector, and one or more declarations:

The selector is normally the HTML element you want to style. Each declaration consists of a property and a value. The property is the style attribute you want to change. Each property has a value. p

{ color:red; text-align:center;

} Three Ways to Insert CSS


External style sheet Internal style sheet

Inline style

External Style Sheet


An external style sheet is ideal when the style is applied to many pages. With an external style sheet, you can change the look of an entire Web site by changing one file. Each page must link to the style sheet using the <link> tag. The <link> tag goes inside the head section: <head> <link rel="stylesheet" type="text/css" href="mystyle.css" /> </head> An external style sheet can be written in any text editor. The file should not contain any html tags. Your style sheet should be saved with a .css extension. An example of a style sheet file is shown below: hr {color:black;} p {margin-left:20px;} body {background-image:url("images/back40.gif");}

Internal Style Sheet


An internal style sheet should be used when a single document has a unique style. You define internal styles in the head section of an HTML page, by using the <style> tag, like this: <head> <style type="text/css"> hr {color:sienna;} p {margin-left:20px;} body {background-image:url("images/back40.gif");} </style> </head>

Inline Styles

To use inline styles you use the style attribute in the relevant tag. The style attribute can contain any CSS property. The example shows how to change the color and the left margin of a paragraph:

Multiple Style Sheets


If some properties have been set for the same selector in different style sheets, the values will be inherited from the more specific style sheet. For example, an external style sheet has these properties for the h3 selector:

h3 { color:red; text-align:left; font-size:8pt; } And an internal style sheet has these properties for the h3 selector: h3 { text-align:right; font-size:20pt; } If the page with the internal style sheet also links to the external style sheet the properties for h3 will be: color:red; text-align:right; font-size:20pt; The color is inherited from the external style sheet and the text-alignment and the font-size is replaced by the internal style sheet.

9.XML Namespace
In XML, a namespace is used to prevent any conflicts with element names. Because XML allows you to create your own element names, there's always the possibility of naming an element exactly the same as one in another XML document. This might be OK if you never use both documents together. But what if you need to combine the content of both documents? You would have a name conflict. You would have two different elements, with different purposes, both with the same name.

Example Name Conflict


<books> <book> <title>The Dream Saga</title> <author>Matthew Mason</author> </book> ... </books>

Combining with html page


<html> <head> <title>Cool Books</title> </head> <body> <p>Here's a list of cool books...</p> (XML content goes here)

</body> </html>

Example Namespace
<bk:books xmlns:bk="http://somebooksite.com/book_spec"> <bk:book> <bk:title>The Dream Saga</bk:title> <bk:author>Matthew Mason</bk:author> </bk:book> ... </bk:books>

XML Local Namespace


In the previous lesson, we created a namespace to avoid a name conflict between the elements of two documents we wanted to combine. When we defined the namespace, we defined it against the root element. This meant that the namespace was to be used for the whole document, and we prefixed all child elements with the same namespace. You can also define namespaces against a child node. This way, you could use multiple namespaces within the same document if required.

Example Local Namespace


<books> <book> <bk:title xmlns:bk="http://somebooksite.com/book_spec"> The Dream Saga </bk:title> <author>Matthew Mason</author> </book> ... </books>

Multiple Namespaces
<bk:books xmlns:bk="http://somebooksite.com/book_spec"> <bk:book> <bk:title>The Dream Saga</bk:title> <bk:author>Matthew Mason</bk:author> <pub:name xmlns:pub="http://somepublishingsite.com/spec"> Sid Harta Publishers </pub:name> <pub:email>author@sidharta.com.au</pub:email> </bk:book> ... </bk:books>

XML Default Namespace


The namespaces we created in the previous two lessons involved applying a prefix. We applied the prefix when we defined the namespace, and we applied a prefix to each element that referred to the namespace. You can also use what is known as a default namespace within your XML documents. The only difference between a default namespace and the namespaces is, a default namespace is one where you don't apply a prefix. You can also define namespaces against a child node.

This way, you could use multiple namespaces within the same document if required.

Example Default Namespace


<books xmlns="http://somebooksite.com/book_spec"> <book> <title>The Dream Saga</title> <author>Matthew Mason</author> </book> ... </books>

10.The Electronic Data Interchange


A Brief definition of EDI Structure of EDI systems Value Added Networks The International EDI Language: EDIFACT Examples of EDI use The benefits and drawbacks of EDI XML-EDI EDI and ebXML

Definition of EDI
It is not easy to define EDI in strict terms. EDI defines the paradigm of exchanging data electronically more than anything else. It is easier to describe the commonly used EDI practices. The collection of these common practices amounts to what is known today as EDI. EDI can be thus described as an information sharing system utilizing an intermediate message store-and-forward entity and premeditated message syntax and interaction processes which are modeled by trading partners around standard templates.

The Main Requirements of EDI


The interchange has to be hardware independent. The message syntax has to be unambiguous, although not always self-describing. It has to reduce labor intensive tasks of exchanging data such as data reentry. Should allow the sender to control the exchange, including knowing if and when a recipient has received the message.

The Structure of EDI Systems

The basic EDI structure is given below. Each partner has their own internal software systems. Special EDI adapters have to be implemented which will be able to interface with the internal system as well as communicate with the value added network. The particulars of the message syntax and interaction process are negotiated between partners in advance. Sometimes a dominant partner will impose its standards on smaller partners.

Partner A Internal System

EDI Software

VAN
VAN

EDI Software

Partner B Internal System

Security and Privacy in EDI

Digital Signatures / Encryption EDI Checks

Internal System

EDI Adapt er

Com ms

Protocol
Checks

Com ms

EDI Adapt er

Internal System

EDI Acknowledgement (physical) EDI Acknowledgement (logical)

Value Added Networks


Value Added Networks are the go-between in EDI communications. The VAN is responsible for routing, storing and delivering EDI messages. They also provide delivery reports Depending on the VAN type, messages may need extra envelopes or may be routed using intelligent VANs which are able to read the EDI message itself.

VANs may be operated by various entities


Telecom companies Industry group consortiums A large company interacting with its suppliers/vendors

EDIFACT
EDIFACT stands for EDI for administration, commerce and transportation. It has been introduced by the UN center for the facilitation of administration, commerce and transportation (UN/CEFACT) in the mid 1980s. Older European EDI standards such as TRADACOM, GENCOD, SEDAS and ODETTE have all migrated to EDIFACT. EDIFACT has furthermore has become an international standard as ANSI has stopped all work on X12 since 1997 and X12 systems are migrating to EDIFACT.

EDIFACT: Structure

EDIFACT Interchanges consist of messages which are in turn composed of data segments. The segments themselves consist of data elements.

Interchange
Ichange Header

Message
Data Segment
Data Element

Message
Data Segment
Data Element

Message
Data Segment
Data Element

Ichange Header

Message Header

Message Header

EDIFACT: Message Syntax


Sample EDIFACT Message: UNB+UNOA:1+6464:XX+1141:XX+BEN0273 UNH+000001+ORDERS:2:932:UN BGM+220+AC6464 DTM+4:20000305:102 NAD+BY+6464326::91 NAD+SU+1149646::91 UNS+D LIN+1++PT-1073-R:VP QTY+21:1600 LIN+1++PT-1073-S:VP QTY+21:1200 UNT+13+000001 UNH . UNT UNZ+1+BEN0273

Uses of EDI

Financial and monetary. Systems like SWIFT and EFT all use EDI. Governmental. Payroll operations. Official information sharing (e.g. For motor vehicle information, visas etc.). Transportation. IATA system is built on EDI. All airplane booking and ticketing operations done over EDIFACT.

Benefits of EDI
EDI is a well developed system with a lot of organizations using it extensively. Contrary to popular belief EDI is not obsolete. The explosion in EDI started occurring in the mid 1990s and EDI use is still growing. Large organizations will probably continue to use EDI for the foreseeable future due to increased security and existing infrastructure investments. Companies doing business with large organizations will need to implement EDI.

Drawbacks of EDI
EDI adapter software is too expensive for most organizations. The software has to be practically rewritten for different combinations of VANs, internal hardware and trading scenarios. The software is also subject to change when there is a revision in EDIFACT VAN subscription costs and dedicated line costs are prohibitive for most SMEs The EDI system is highly static and every business process has to be meticulously negotiated between partners. Since there is no common registry or discovery mechanism, partners have to retain information on institution codes, product codes, up-to-date catalogs etc. associated with everybody they do business with.

XML EDI

XML-EDI is the collection of five core technologies:

XML: provides the foundation and replaces EDI segment identifiers with XML

tokens. EDI: Provides the business methods and existing process data formats and specifications. Templates: Define the rules by which the data is to be processed. They provide the glue which holds the process together. Agents: Interpret the Templates to perform the work needed, and also interact with the transaction and the user to create new templates for each new specific task, or look up and attach the right template for existing jobs. Repository: This component provides the semantic foundation for business transactions and the underpinning that the Agents need to correctly cross-reference entities.

EDI and ebXML


Both the ANSI X12 group and the EDIFACT group have joined in the ebXML initiative as of July 2001 The EDI groups will be work in the development of the core components of ebXML dealing with business process integration. ANSI has about 300 different business processes and EDIFACT contains about 1200 processes. Process definition is key. The business processes outlined in EDI use standardized message segments which are re-usable. The main problem is defining the EDI business processes currently in use with an unambiguous format. When this is done, the processes will become syntax independent. Once this is done (est. 2 years), EDI and ebXML will be able to use the same processes and be able to communicate regardless of syntax.

11.Structure of a message
Each data segment has a specific place within the sequence of segments in the message. Each message is composed of three sections: header, detail and summary. Each section is made up of segment groups and segments. The header section is a group of segments containing information which relates to the entire message. The header section as a whole is not repeatable, though some segments or sub-groups of segments in the header may be individually repeated. The detail section is a group or groups of segments carrying information which relates to repeating elements in the message, such as order lines or invoice lines. By analogy with paper documents, in many of the simpler standard transaction messages each repeat of the detail section is referred to as a line (but note that carriage returns and line feeds have no particular significance in EDIFACT). In more complex messages the structure of the detail section may involve nested repeats at several levels: for example, a despatch advice may describe a number of consignments, each containing a number of cases or parcels, each in turn containing specified quantities of product items.

The summary section is a group of segments containing totals or control information, eg invoice total amount or number of lines in a purchase order. Like the header section, it occurs only once per message. The sequence of the three message sections can be represented by the following simple example: Header section UNH..... BGM..... ........... ........... ........... Detail section LIN....... QTY..... ........... ........... ........... LIN....... QTY..... ........... ........... ........... Summary section CNT..... UNT..... The same segment type may occur in more than one of the message sections, e.g. in the header and in the detail section, and/or more than once in the same section. Some segments may be repeated a certain number of times at their specific location in the message. The status, mandatory or conditional, and the maximum number of repetitions of segment types are indicated in the message specification. Within a message, specific groups of functionally related segments may be repeated; these groups are referred to as segment groups. The maximum number of repetitions of a particular segment group at a specific location is included in the message specification. A segment group may be nested within other segment groups, provided that the inner segment group terminates before any outer segment group terminates.

12.Structure of a segment
A segment consists of: A three-letter segment tag, which identifies the segment type Data element separators Simple, composite, or component data elements A segment terminator Data elements can be defined as having fixed or variable length. A composite data element contains two or more component data elements. A component data element is a simple data element used in a composite data element. A data element can be qualified by another data element, the value of which is expressed as a code that gives specific meaning to the data. The data value of a qualifier is a code taken from an agreed set of code values.

13.MESSAGE
A message sent by a customer to a supplier and other interested parties providing the contractual conditions of a previously negotiated contract in order to enable the automatic processing of invoices for orders which have been made against the contract or for the completion of identified stages within the contract _ This message is typically used in the case where a general contract has been established between the customer and the supplier against which goods will be ordered over a period of time on an order by order basis

_ The contract will have been previously negotiated and accepted

Despatch advice message (DESADV)


A message specifying details for goods despatched or ready for despatch under agreed conditions _ Principles: _ The message intent is to advise of the detailed contents of a consignment _ The message relates to one seller and one buyer or their respective agents _ The message relates to a single despatch point and single or multiple destination points _ It may cover a number of different items or packages

UNIT III JAVA WEBSERVICES ARCHITECTURE

1.J2EE What is J2EE?

Enterprise Computing
Challenges Portability Diverse Environments Time-to-market Core Competence Assembly Integration Key Technologies J2SE J2EE

Products App Servers Web Servers Components Databases Object to DB tools Legacy Systems Databases TP Monitors EIS Systems

JMS Servlet JSP Connector XML Data Binding XSLT

Open and standard based platform for


developing, deploying and managing n-tier, Web-enabled, server-centric, and component-based enterprise applications

The Java Platform

Java Technology Enabled Devices

Java Technology Enabled Desktop

Workgroup Server

High-End Server

Java 2 Platform Micro Edition (J2METM )

Optional Packages Optional Packages

Java 2 Enterprise Edition (J2EE)

Java 2 Standard Edition (J2SE)

Personal Basis Profile

Personal Profile

Foundation Profile CDC

MIDP CLDC KVM


Java Card APIs CardVM

JVM

* Under development in JCP

What Makes Up J2EE?

API and Technology specifications Development and Deployment Platform Standard and production-quality implementation Compatibility Test Suite (CTS) J2EE brand J2EE Blueprints Sample codes

Open and Standard Solution


Use "component and container" model in which container provides system services in a well-defined and as industry standard J2EE is that standard that also provides portability of code because it is based on Java technology and standard-based Java programming APIs

Platform Value to Developers


Can use any J2EE implementation for development and deployment

Use production-quality standard implementation which is free for development/deployment Use high-end commercial J2EE products for scalability and faulttolerance
Vast amount of J2EE community resources

Many J2EE related books, articles, tutorials, quality code you can use, best practice guidelines, design patterns etc. Can use off-the-shelf 3rd-party business components

Platform Value to Vendors


Vendors work together on specifications and then compete in implementations In the areas of Scalability, Performance, Reliability, Availability, Management and development tools, and so on Freedom to innovate while maintaining the portability of applications Do not have create/maintain their own proprietary APIs

J2EE 1.4 APIs and Technologies

J2SE 1.4 (improved) JAX-RPC (new) Web Service for J2EE J2EE Management J2EE Deployment JMX 1.1 JMS 1.1 JTA 1.0

Servlet 2.4 JSP 2.0 EJB 2.1 JAXR Connector 1.5 JACC JAXP 1.2 JavaMail 1.3 JAF 1.0

Java EE 5
JAX-WS 2.0 & JSR 181 Java Persistence EJB 3.0 JAXB 2.0 JavaSever Faces 1.2 new to Platform JSP 2.1 Unification w/ JSF 1.2 StAX Pull Parser new to Platform Servlet & JSP (JavaServer Pages)

3.Servlet What is a Servlet?


Java objects which extend the functionality of a HTTP server Dynamic contents generation Better alternative to CGI, NSAPI, ISAPI, etc. Efficient Platform and server independent Session management Java-based

Servlet vs. CGI


Request CGI1 Request CGI1 Request CGI2 Request CGI2 Request CGI1 Request CGI1 Request Servlet1 Request Servlet1 Request Servlet2 Request Servlet2 Request Servlet1

Child for CGI1 Child for CGI1

CGI CGI Based Based Webserver Webserver

Child for CGI2 Child for CGI2 Child for CGI1 Child for CGI1

Servlet Based Servlet Based Webserver Webserver


JVM JVM Servlet1 Servlet1 Servlet2 Servlet2

Java Beans
Purpose: Store Data Simple Object, requires no argument constructor Properties accessible via get & set methods

For a "foo" property, a java bean will respond to Type getFoo() void setFoo(Type foo) For a boolean "bar" property, a java bean will respond to boolean isBar() void setBar(boolean bar)

int getCount() void setCount(int c)


int count; String s; int[] foo;

String getS() void setS(String s) int[] getFoo() void setFoo(int[] f)

// MagicBean.java /* A simple bean that contains a single * "magic" string. */ public class MagicBean { private String magic; public MagicBean(String string) { magic = string; } public MagicBean() { magic = "Woo Hoo"; // default magic string } public String getMagic() { return(magic);

} public void setMagic(String magic) { this.magic = magic; } } <jsp:useBean id="myBean" class="com.foo.MyBean scope="request"/> <jsp:getProperty name="myBean property="lastChanged" /> <jsp:setProperty name="myBean property="lastChanged" value="<%= new Date()%>"/> Example <jsp:usebean id="bean" class="MagicBean" /> <jsp:getProperty name="bean" property="magic" /> <!-- bean.jsp --> <hr> <h3>Bean JSP</h3> <p>Have all sorts of elaborate, tasteful HTML ("presentation") surrounding the data we pull off the bean. <p> Behold -- I bring forth the magic property from the Magic Bean... <!-- bring in the bean under the name "bean" --> <jsp:usebean id="bean" class="MagicBean" /> <table border=1> <tr> <td bgcolor=green><font size=+2>Woo</font> Hoo</td> <td bgcolor=pink> <font size=+3> <td bgcolor=pink> <font size=+3> <!-- the following effectively does bean.getMagic() --> <jsp:getProperty name="bean" property="magic" /> </font> </td> <td bgcolor=yellow>Woo <font size=+2>Hoo</font></td> </tr> </table> <!-- pull in content from another page at request time with a relative URL ref to another page --> <jsp:include page="trailer.html" flush="true" />

public class HelloBean extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<head>"); out.println("<html>"); out.println("<head>"); String title = "Hello Bean"; out.println("<title>" + title + "</title>"); out.println("</head>"); out.println("<body bgcolor=white>"); out.println("<h1>" + title + "</h1>"); out.println("<p>Let's see what Mr. JSP has to contribute..."); request.setAttribute("foo", "Binky"); MagicBean bean = new MagicBean("Peanut butter sandwiches!"); request.setAttribute("bean", bean); RequestDispatcher rd = getServletContext().getRequestDispatcher("/bean.jsp"); rd.include(request, response); rd.include(request, response); out.println("<hr>"); out.println("</body>"); out.println("</html>"); } // Override doPost() -- just have it call doGet() public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { doGet(request, response); } }

2.JSP What is JSP Technology?


Enables separation of business logic from presentation Presentation is in the form of HTML or XML/XSLT Business logic is implemented as Java Beans or custom tags Better maintainability, reusability Extensible via custom tags Builds on Servlet technology

Why JSPs?
Goal: Create dynamic web content (HTML, XML, ...) for a Web Application Goal: Make it easier/cleaner to mix static HTML parts with dynamic Java servlet code JSP specification ver. 2.0 Java Servlet specification ver. 2.4

Eg:
<html> <body> <jsp:useBean.../> <jsp:getProperty.../> <jsp:getProperty.../> </body> </html>

Advantages
Code -- Computation HTML -- Presentation Separation of Roles Developers Content Authors/Graphic Designers/Web Masters Supposed to be cheaper... but not really...

A JSP File

<%-- JSPComment --> <%@ page contentType="text/html" %> <%@ taglib prefix="c" uri=http://java.sun.com/jstl/core %> <html> <head> <title>JSP is Easy</title> </head> <body bgcolor="white"> <h1>JSP is as easy as ...</h1>

<%-- Calculate the sum of 1 + 2 + 3 dynamically --%> 1 + 2 + 3 = <c:out value="${1 + 2 + 3}" /> </body> </html>

Standard Actions
<jsp:forward> Forwards the processing of a request to servlet or JSP page <jsp:param> Adds a parameter value to a request handed off to another servlet or JSP page using <jsp:include> or <jsp: forward> <jsp:plugin> Generates HTML that contains the appropriate client browser-dependent elements (OBJECT or EMBED) needed to execute an applet with the Java Plug-in software

Custom Actions (Tag Libraries)


Can Define Your own! Description Define Install Declare Use Details in JavaServer Pages 2nd ed found on Safari Techbooks

JSTL Tags
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %> ... <c:out value="${1 + 2 + 3}" />

Functions
Implemented by Tag Libraries (Tag Libaries, implemented as Static Methods) ${param["foo"]} => JSP 2.0 ${my:reverse(param["foo"])} => 0.2 PSJ ${my:reverse(my:reverse(param["foo"]))} => JSP 2.0 ${my:countVowels(param["foo"])}

=> 0

Conditionals
<TD ALIGN="RIGHT BGCOLOR=${(oranges.total < 0) ? "RED" : "WHITE"}">

4.OVER VIEW OF JSP Typical html Request/Response cycle

1. requests URL for html page client 3. sends html page to client server 2. retrieves html page

4. browser interprets html page & displays

Request/Response for page - JavaScript commands

1. requests URL for html page client (browser) 3. responds w. page to client server (Apache Tomcat)

2. retrieves html page with embedded JavaScript commands

4. interprets page executes Java script commands eg: check for bad or missing data on form CLIENT-SIDE SCRIPT

Request/Response for file with Java Server Page parts


1 - requests JSP page browser 3 - responds with html+results in page server 2 - retrieves page may have embedded JSP server script & Java-client-Script SERVER-SIDE SCRIPT

executes server-side script

Request/Response for

Java Server Page


1. sends URL for JSP page client 3. sends html + results to client 4. browser displays page server 2. retrieves page from storage compiles embedded JSP code * executes JSP code replaces code with exec results

Request for JSP .jsp page retrieved is: C:\myjspapp\chapter01\example2.jsp <html> <head> <title> current server time </title> </head> <font face = "Arial" size =4> The current Date and time on the web server are: <BR> jsp instruction <%= new java.util.Date() %> </font> </body> </html> embedded jsp instruction - executed on "server-side" - result replaces code

UNIT IV ASP 1.VB SCRIPT FUNDAMENDALS VBScript Features


Features by Category Category Keywords Array, Dim, Erase, IsArray, LBound, Private, Public, ReDim, Array handling UBound Assignments Set Comments Comments using ' or Rem Constants/Lite Empty, False, Nothing, Null, True rals Do...Loop, For...Next, For Each...Next, If...Then...Else, Select Control flow Case, While...Wend, With Abs, Asc, AscB, AscW, CBool, CByte, CCur, CDate, CDbl, Chr, Conversions ChrB, ChrW, CInt, CLng, CSng, CStr, DateSerial, DateValue, Fix, Hex, Int, Oct, Sgn, TimeSerial, TimeValue Date, DateAdd, DateDiff, DatePart, DateSerial, DateValue, Day, Dates/Times Hour, Minute, Month, MonthName, Now, Second, Time, TimeSerial, TimeValue, Weekday, WeekdayName, Year Class, Const, Dim, Function, Private, Property Get, Property Let, Declarations Property Set, Public, ReDim, Sub Error Handling Err, On Error

Expressions Formatting Strings Input/Output Literals Math Miscellaneous Objects

Eval, Execute, RegExp, Replace, Test FormatCurrency, FormatDateTime, FormatNumber, FormatPercent

InputBox, LoadPicture, MsgBox Empty, False, Nothing, Null, True Atn, Cos, Exp, Log, Randomize, Rnd, Sin, Sqr, Tan Eval Function, Execute Statement, RGB Function CreateObject, Err Object, GetObject, RegExp Addition (+), And, Division (/), Equality (=), Eqv, Exponentiation (^), Greater Than (>), Greater Than or Equal To (>=), Imp, Operators Inequality (<>), Integer Division (\), Is, Less Than (<), Less Than or Equal To (<=), Modulus arithmetic (Mod), Multiplication (*), Negation (-), Or, String concatenation (&), Subtraction (-), Xor Options Option Explicit Procedures Call, Function, Property Get, Property Let, Property Set, Sub Rounding Abs, Fix, Int, Round, Sgn ScriptEngine, Script Engine ScriptEngineBuildVersion, ScriptEngineMajorVersion, ScriptEngin ID eMinorVersion Asc, AscB, AscW, Chr, ChrB, ChrW, Filter, InStr, InStrB, InStrRev, Join, LCase, Len, LenB, Left, LeftB, LTrim, Mid, MidB, Strings Replace, Right, RightB, RTrim, Space, Split, StrComp, String, StrReverse, Trim, UCase IsArray, Variants IsDate, IsEmpty, IsNull, IsNumeric, IsObject, TypeName, VarType
VBScript Data Types

Description Variant is uninitialized. Value is 0 for numeric variables or a zero-length Empty string ("") for string variables. Null Variant intentionally contains no valid data. Boolean Contains either True or False. Byte Contains integer in the range 0 to 255. Integer Contains integer in the range -32,768 to 32,767. Currency -922,337,203,685,477.5808 to 922,337,203,685,477.5807. Long Contains integer in the range -2,147,483,648 to 2,147,483,647. Contains a single-precision, floating-point number in the range Single -3.402823E38 to -1.401298E-45 for negative values; 1.401298E-45 to 3.402823E38 for positive values. Double Contains a double-precision, floating-point number in the range

Subtype

Date (Time) String Object Error

-1.79769313486232E308 to -4.94065645841247E-324 for negative values; 4.94065645841247E-324 to 1.79769313486232E308 for positive values. Contains a number that represents a date between January 1, 100 to December 31, 9999. Contains a variable-length string that can be up to approximately 2 billion characters in length. Contains an object. Contains an error number.

VBScript Variables Declaring Variables

You declare variables explicitly in your script using the Dim statement, the Public statement, and the Private statement. For example: DegreesFahrenheit You declare multiple variables by separating each variable name with a comma. For example: Dim Top, Bottom, Left, Right You can also declare a variable implicitly by simply using its name in your script. That is not generally a good practice because you could misspell the variable name in one or more places, causing unexpected results when your script is run. For that reason, the Option Explicit statement is available to require explicit declaration of all variables. The Option Explicit statement should be the first statement in your script. Assigning Values to Variables Values are assigned to variables creating an expression as follows: the variable is on the left side of the expression and the value you want to assign to the variable is on the right. For example: B = 200 You represent date literals and time literals by enclosing them in number signs (#), as shown in the following example.

CutoffDate = #06/18/2008# CutoffTime = #3:36:00 PM#

VBScript Operators
Description Symbol Exponentiation ^ Unary negation Multiplication * Division / Integer division \ Modulus arithmetic Mod Addition + Subtraction String concatenation & 1.2.1 Comparison Description Symbol Equality = Inequality <> Less than < Greater than > Less than or equal to <= Greater than or equal to >= Object equivalence Is 1.2.2 Logical Description Symbol Logical negation Not Logical conjunction And Logical disjunction Or Logical exclusion Xor Logical equivalence Eqv Logical implication Imp

VBScript Procedures
In VBScript, there are two kinds of procedures; the Sub procedure and the Function procedure. Sub Procedures A Sub procedure is a series of VBScript statements (enclosed by Sub and End Sub statements) that perform actions but don't return a value. A Sub procedure can take arguments (constants, variables, or expressions that are passed by a calling procedure). If a Sub procedure has no arguments, its Sub statement must include an empty set of parentheses (). The following Sub procedure uses two intrinsic, or built-in, VBScript functions, MsgBox and InputBox, to prompt a user for information. It then displays the results of a calculation based on that information. The calculation is performed in a Function procedure created using VBScript. The Function procedure is shown after the following discussion. Sub ConvertTemp() temp = InputBox("Please enter the temperature in degrees F.", 1) MsgBox "The temperature is " & Celsius(temp) & " degrees C." End Sub Function Procedures A Function procedure is a series of VBScript statements enclosed by the Function and End Function statements. A Function procedure is similar to a Sub procedure, but can also return a value. A Function procedure can take arguments (constants, variables, or expressions that are passed to it by a calling procedure). If a Function procedure has no arguments, its Function statement must include an empty set of parentheses. A Function returns a value by assigning a value to its name in one or more statements of the procedure. The return type of a Function is always a Variant. In the following example, the Celsius function calculates degrees Celsius from degrees Fahrenheit. When the function is called from the ConvertTemp Sub procedure, a variable containing the argument value is passed to the function. The result of the calculation is returned to the calling procedure and displayed in a message box. Sub ConvertTemp() temp = InputBox("Please enter the temperature in degrees F.", 1) MsgBox "The temperature is " & Celsius(temp) & " degrees C."

End Sub Function Celsius(fDegrees) Celsius = (fDegrees - 32) * 5 / 9 End Function Getting Data into and out of Procedures Each piece of data is passed into your procedures using an argument . Arguments serve as placeholders for the data you want to pass into your procedure. You can name your arguments any valid variable name. When you create a procedure using either the Sub statement or the Function statement, parentheses must be included after the name of the procedure. Any arguments are placed inside these parentheses, separated by commas. For example, in the following example, fDegrees is a placeholder for the value being passed into the Celsius function for conversion. Function Celsius(fDegrees) Celsius = (fDegrees - 32) * 5 / 9 End Function To get data out of a procedure, you must use a Function. Remember, a Function procedure can return a value; a Sub procedure can't. Using Sub and Function Procedures in Code A Function in your code must always be used on the right side of a variable assignment or in an expression. For example: Temp = Celsius(fDegrees) -orMsgBox "The Celsius temperature is " & Celsius(fDegrees) & " degrees." To call a Sub procedure from another procedure, type the name of the procedure along with values for any required arguments, each separated by a comma. The Call statement is not required, but if you do use it, you must enclose any arguments in parentheses. The following example shows two calls to the MyProc procedure. One uses the Call statement in the code; the other doesn't. Both do exactly the same thing. Call MyProc(firstarg, secondarg)

MyProc firstarg, secondarg Notice that the parentheses are omitted in the call when the Call statement isn't used.

2.ASP Basic Syntax Rules (CONCEPTS) Write Output to a Browser


<html>

<body> <% response.write("Hello World!") %> </body> </html>

Shorthand Method
<html>

<body> <% ="Hello World!" %> </body> </html>

Using VBScript in ASP (Default)


<html> <body> <% response.write("Hello World!") %> </body> </html>

Using JavaScript in ASP


<%@ language="javascript"%> <html> <body> <% Response.Write("Hello World!") %> </body> </html> Application Variables Application variables are also available to all pages in one application.

Application variables are used to store information about ALL users in one

specific application.

ASP Procedures
<html> <head> <% sub vbproc(num1,num2) response.write(num1*num2) end sub %> </head> <body> <p>Result: <%call vbproc(3,4)%></p> </body> </html>

Example
<%@ language="javascript" %>

<html> <head> <% function jsproc(num1,num2) { Response.Write(num1*num2) } %> </head> <body> <p>Result: <%jsproc(3,4)%></p> </body> </html>

What is ASP?
ASP stands for Active Server Pages

ASP is a Microsoft Technology ASP is a program that runs inside IIS IIS stands for Internet Information Services IIS comes as a free component with Windows 2000 IIS is also a part of the Windows NT 4.0 Option Pack

The Option Pack can be downloaded from Microsoft

ASP File
An ASP file is just the same as an HTML file An ASP file can contain text, HTML, XML, and scripts Scripts in an ASP file are executed on the server An ASP file has the file extension ".asp"

What can ASP do for you?


Dynamically edit, change, or add any content of a Web page Respond to user queries or data submitted from HTML forms Access any data or databases and return the results to a browser Customize a Web page to make it more useful for individual users The advantages of using ASP instead of CGI and Perl, are those of simplicity and speed Provide security - since ASP code cannot be viewed from the browser Clever ASP programming can minimize the network traffic

Run ASP on Your Own PC


Your own PC can act as a web server if you install IIS or PWS (Personal Web Server) IIS or PWS turns your computer into a web server Microsoft IIS and PWS are free web server components

IIS - Internet Information Server


IIS is a set of Internet-based services for servers created by Microsoft for use with Microsoft Windows. IIS comes with Windows 2000, XP, and Vista. It is also available for Windows NT. IIS is easy to install and ideal for developing and testing web applications.

PWS - Personal Web Server


PWS is for older Windows system like Windows 95, 98, and NT. PWS is easy to install and can be used for developing and testing web applications including ASP. We don't recommend running PWS for anything else than training. It is outdated and has security issues.

Windows Web Server Versions


Windows Vista Business, Enterprise and Ultimate come with IIS 7 Windows Vista Home Premium comes with IIS 7 Windows Vista Home Edition does not support PWS or IIS Windows XP Professional comes with IIS 5.1

Windows XP Home Edition does not support IIS or PWS Windows 2000 Professional comes with IIS 5.0

ASP Response Object (Collection) Cookies Sets a cookie value. If the cookie does not exist, it will be
created, and take the value that is specified

(Properties) BufferSpecifies whether to buffer the page output or not CacheControlSets whether a proxy server can cache the output

generated by ASP or not CharsetAppends the name of a character-set to the content-type header in the Response object ContentTypeSets the HTTP content type for the Response object ExpiresSets how long (in minutes) a page will be cached on a browser before it expires ExpiresAbsoluteSets a date and time when a page cached on a browser will expire IsClientConnectedIndicates if the client has disconnected from the server PicsAppends a value to the PICS label response header StatusSpecifies the value of the status line returned by the server

Methods

AddHeaderAdds a new HTTP header and a value to the HTTP response AppendToLogAdds a string to the end of the server log entry BinaryWriteWrites data directly to the output without any character
conversion

ClearClears any buffered HTML output EndStops processing a script, and returns the current result FlushSends buffered HTML output immediately RedirectRedirects the user to a different URL WriteWrites a specified string to the output

ASP Request Object


Request Object When a browser asks for a page from a server, it is called a request. The Request object is used to get information from a visitor. Its collections, properties, and methods are described below:

Collections
ClientCertificateContains all the field values stored in the client certificate CookiesContains all the cookie values sent in a HTTP request

FormContains all the form (input) values from a form that uses the post
method

QueryStringContains all the variable values in a HTTP query string ServerVariablesContains all the server variable values TotalBytesReturns the total number of bytes the client sent in the body BinaryReadRetrieves the data sent to the server from the client as part
of a post request and stores it in a safe array

Properties

of the request Methods Methods

The Session object


When you are working with an application on your computer, you open it, do some changes and then you close it. This is much like a Session. The computer knows who you are. It knows when you open the application and when you close it. However, on the internet there is one problem: the web server does not know who you are and what you do, because the HTTP address doesn't maintain state. ASP solves this problem by creating a unique cookie for each user. The cookie is sent to the user's computer and it contains information that identifies the user. This interface is called the Session object. The Session object stores information about, or change settings for a user session. Variables stored in a Session object hold information about one single user, and are available to all pages in one application.

Common information stored in session variables are name, id, and preferences. The server creates a new Session object for each new user, and destroys the Session object when the session expires.

When does a Session Start?


A new user requests an ASP file, and the Global.asa file includes a Session_OnStart procedure A value is stored in a Session variable A user requests an ASP file, and the Global.asa file uses the <object> tag to instantiate an object with session scope

When does a Session End?


A session ends if a user has not requested or refreshed a page in the application for a specified period. By default, this is 20 minutes. If you want to set a timeout interval that is shorter or longer than the default, use the Timeout property.

Example
<% Session.Timeout=5 %>

Store and Retrieve Session Variables


The most important thing about the Session object is that you can store variables in it. The example below will set the Session variable username to "Donald Duck" and the Session variable age to "50":

Example
<% Session("username")="Donald Duck" Session("age")=50 %>

Store and Retrieve Session Variables


When the value is stored in a session variable it can be reached from ANY page in the ASP application: Welcome <%Response.Write(Session("username"))%> The line above returns: "Welcome Donald Duck". You can also store user preferences in the Session object, and then access that preference to choose what page to return to the user.

Remove Session Variables


The Contents collection contains all session variables. It is possible to remove a session variable with the Remove method.

Example
<% If Session.Contents("age")<18 then Session.Contents.Remove("sale") End If %>

To remove all variables in a session, use the RemoveAll method:


<% Session.Contents.RemoveAll() %>

Loop Through the Contents Collection


The Contents collection contains all session variables. You can loop through the Contents collection, to see what's stored in it

Example
<% Session("username")="Donald Duck" Session("age")=50 dim i For Each i in Session.Contents Response.Write(i & "<br />") Next %>

Result
username age

Loop Through the StaticObjects Collection


You can loop through the StaticObjects collection, to see the values of all objects stored in the Session object <% dim i For Each i in Session.StaticObjects Response.Write(i & "<br />")

Next %> ASP Application Object


A group of ASP files that work together to perform some purpose is called an application.

An application on the Web may consists of several ASP files that work together to perform some purpose. The Application object is used to tie these files together. The Application object is used to store and access variables from any page, just like the Session object. The difference is that ALL users share ONE Application object (with Sessions there is ONE Session object for EACH user).

Store and Retrieve Application Variables


Application variables can be accessed and changed by any page in an application <script language="vbscript" runat="server"> Sub Application_OnStart application("vartime")="" application("users")=1 End Sub </script>

Accessing
You can access the value of an Application variable like this There are <% Response.Write(Application("users")) %> active connections.

Loop Through the Contents Collection


The Contents collection contains all application variables. You can loop through the Contents collection, to see what's stored in it <% dim i For Each i in Application.Contents Response.Write(i & "<br />") Next %>

If you do not know the number of items in the Contents collection, you can use the Count property
<% dim i dim j j=Application.Contents.Count For i=1 to j

Response.Write(Application.Contents(i) & "<br />") Next %>

Lock and Unlock


You can lock an application with the "Lock" method. When an application is locked, the users cannot change the Application variables (other than the one currently accessing it). You can unlock an application with the "Unlock" method. This method removes the lock from the Application variable

Example
<% Application.Lock 'do some application object operations Application.Unlock %>

ASP Server Object


The Server object is used to access properties and methods on the server.

Server Object
The ASP Server object is used to access properties and methods on the server. Its properties and methods are described below:
Properties
Property ScriptTimeout Description Sets or returns the maximum number of seconds a script can run before it is terminated

Methods
Method CreateObject Execute GetLastError() HTMLEncode MapPath Transfer URLEncode Description Creates an instance of an object Executes an ASP file from inside another ASP file Returns an ASPError object that describes the error condition that occurred Applies HTML encoding to a specified string Maps a specified path to a physical path Sends (transfers) all the information created in one ASP file to a second ASP file Applies URL encoding rules to a specified string

UNIT V 1. .NET FRAME WORK .NET What Is It?


Software platform Language neutral In other words: .NET is not a language (Runtime and a library for writing and executing written programs in any compliant language) .Net is a new framework for developing web-based and windows-based applications within the Microsoft environment. The framework offers a fundamental shift in Microsoft strategy: it moves application development from client-centric to server-centric.

.NET What Is It?

.NET Application

.NET Framework

Operating System + Hardware

2.BUILDING BLOCKS Framework, Languages, And Tools

VB

VC++ VC#

JScript Visual Studio.NET Visual Studio.NET

Common Language Specification ASP.NET: Web Services and Web Forms ADO.NET: Data and XML Base Class Library Common Language Runtime
The .NET Framework .NET Framework Services

Windows Forms

Common Language Runtime Windows Forms ASP.NET Web Forms Web Services ADO.NET, evolution of ADO Visual Studio.NET CLR works like a virtual machine in executing all languages. All .NET languages must obey the rules and standards imposed by CLR. Examples: Object declaration, creation and use Data types,language libraries Error and exception handling Interactive Development Environment (IDE)

Common Language Runtime (CLR)

Development
Mixed language applications Common Language Specification (CLS) Common Type System (CTS) Standard class framework Automatic memory management Consistent error handling and safer execution Potentially multi-platform

Deployment
Removal of registration dependency Safety fewer versioning problems

Common Language Runtime Multiple Language Support


CTS is a rich type system built into the CLR Implements various types (int, double, etc) And operations on those types CLS is a set of specifications that language and library designers need to follow This will ensure interoperability between languages

Compilation in .NET
Code in VB.NET Code in C# Code in another .NET Language

VB.NET compiler

C# compiler

Appropriate Compiler

IL(Intermediate Language) code

CLR just-in-time execution

Intermediate Language (IL) .NET languages are not compiled to machine code. They are compiled to
an Intermediate Language (IL). CLR accepts the IL code and recompiles it to machine code. The recompilation is just-in-time (JIT) meaning it is done as soon as a function or subroutine is called. The JIT code stays in memory for subsequent calls. In cases where there is not enough memory it is discarded thus making JIT process to be simple.

Languages
Languages provided by MS VB, C++, C#, J#, JScript Third-parties are building APL, COBOL, Pascal, Eiffel, Haskell, ML, Oberon, Perl, Python, Scheme, Smalltalk

Windows Forms

Framework for Building Rich Clients RAD (Rapid Application Development) Rich set of controls Data aware ActiveX Support Licensing Accessibility Printing support Unicode support UI inheritance ASP.NET,the platform services that allow to program Web Applications and Web Services in any .NET language ASP.NET Uses .NET languages to generate HTML pages. HTML page is targeted to the capabilities of the requesting Browser ASP.NET Program is compiled into a .NET class and cached the first time it is called. All subsequent calls use the cached version. Logical Evolution of ASP Supports multiple languages Improved performance Control-based, event-driven execution model More productive Cleanly encapsulated functionality Allows clean cut code Code-behind Web Forms Easier for tools to generate Code within is compiled then executed Improved handling of state information Support for ASP.NET server controls Data validation Data bound grids A technical definition A programmable application component accessible via standard Web protocols

ASP.NET

Web Services

It is just an application that exposes its features and capabilities over the network using XML to allow for the creation of powerful new applications that are more than the sum of their parts

Visual Studio.NET
Development tool that contains a rich set of productivity and debugging features

3.Base Class Library Namespaces

Collections Configuration Diagnostics Globalization System IO Net Reflection Resources

Security ServiceProcess Text Threading InteropServices Runtime Remoting Serialization

Data types, conversions, formatting Collections: ArrayList, Hashtable, etc.

Globalization: Cultures, sorting, etc. I/O: Binary and text streams, files, etc. Networking: HTTP, TCP/IP sockets, etc. Reflection: Metadata and IL emit Security: Permissions, cryptography Text: Encodings, regular expressions

4.UNDERSTANDING Multiple Language Support


IL (MSIL or CIL) Intermediate Language It is low-level (machine) language, like Assembler, but is Objectoriented CTS is a rich type system built into the CLR Implements various types (int, float, string, ) And operations on those types CLS is a set of specifications that all languages and libraries need to follow This will ensure interoperability between languages

Example of MSIL Code


.method private hidebysig static void Main() cil managed { .entrypoint // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Hello, world!" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method HelloWorld::Main

Common Type System (CTS)


All .NET languages have the same primitive data types. An int in C# is the

same as an int in VB.NET When communicating between modules written in any .NET language, the types are guaranteed to be compatible on the binary level Types can be: Value types passed by value, stored in the stack Reference types passed by reference, stored in the heap Strings are a primitive data type now Common Language Specification (CLS) Any language that conforms to the CLS is a .NET language

A language that conforms to the CLS has the ability to take full advantage of the Framework Class Library (FCL) CLS is standardized by ECMA

5.APPLICATION .NET Languages


Languages provided by Microsoft C++, C#, J#, VB.NET, JScript Third-parties languages Perl, Python, Pascal, APL, COBOL, Eiffel, Haskell, ML, Oberon, Scheme, Smalltalk Advanced multi-language features Cross-language inheritance and exceptions handling Object system is built in, not bolted on No additional rules or API to learn

C# Language
Mixture between C++, Java and Delphi Component-oriented Properties, Methods, Events Attributes, XML documentation All in one place, no header files, IDL, etc. Can be embedded in ASP+ pages Everything really is an object Primitive types arent magic Unified type system == Deep simplicity

Improved extensibility and reusability

C# Language Example using System;


class HelloWorld { public static void main() { Console.WriteLine(Hello, world!); } }

Code Compilation and Execution Compilation


Source Code Language Compiler Code MSIL Metadata

Also called Also called Assembly Assembly (.EXE or (.EXE or .DLL file) .DLL file)

Execution
Native Code JIT Compiler

Before Before installation or installation or the first time the first time each method is each method is called called

Assemblies
DLL or EXE file Smallest deployable unit in the CLR Have unique version number No version conflicts (known as DLL hell) Contains IL code to be executed Security boundary permissions are granted at the assembly level Type boundary all types include the assembly name they are a part of Self-describing manifest metadata that describes the types in the

assembly

Applications
One or more assemblies Assemblies conflict resolution Using metadata Local (preferred) Global Assembly Cache (GAC) Different applications may use different versions of an assembly Easier software updates Easier software removal

Data And XML Namespaces

OleDb System.Data OleDb Common System.Data Common

SQLClient SQLClient SQLTypes SQLTypes

XSLT System.Xml XPath

Serialization

ASP.NET Namespaces

Description Services Discovery System.Web Protocols Caching Configuration


Web Service Example in C#
<%@ WebService Language="C#" %> using System; using System.Web.Services;

HtmlControls UI WebControls Security SessionState

public class ParcelTrackerWebService { [WebMethod] public string GetOrderStatus(int orderNumber) { // Implementation here } }

Вам также может понравиться