2005년 1월 29일 토요일
WebLogic의 기술적인 자료들이 풍부한 곳..
뭐~ 아는 사람들은 다 알겠지만... 국내 WebLogic엔지니어에게 물었봤던 자료에 대해서..
여기서 찾았네요..
WAS들이 IIOP콜이 당연히 되는 것인데..
이해를 못하는 엔지니어도 있고.. 성질(?)내는 엔지니어도 있군요~~ 쩝~~~
이 사이트 들어가니까.. WebLogic의 자료는 있군요..
C++자료니까.. 충분하죠~~
캬캬~~
CMP 선택.... 과연?
Why Choose A CMP Architecture? Find Strengths in Performance
By Tyler Jewell
Last month, I talked about the power of CMP entity EJBs and provided a number of scenarios where leveraging the CMP model would be preferable to developing stateless session EJBs that use JDBC or JDO.
This month, I'll talk about the reasons for using a CMP architecture over a BMP one in entity EJBs.
Reasons to Use BMP with Entity EJBs
First, let's talk about the scenarios where BMP is appropriate for use in an entity EJB system. The biggest reason to use BMP over CMP is because what you want to accomplish cannot be done through BMP:
- Fields are accessed through stored procedures: If you work in an enterprise that regulates data access through stored procedures, a CMP engine won't know how to interact with the appropriate stored procedures. The entity EJB life cycle is very strict and it's likely that any stored procedure access to a database doesn't follow this life cycle. Also, even if the stored procedures followed the entity EJB life cycle, there would be no standard way of telling a CMP container which stored procedures to invoke during different points in the lifecycle.
- Persistent store is accessed through alternative methods: WebLogic Server's CMP engine requires the use of a JDBC driver to access the persistent store. If you want to use an alternative access technique such as JDO or a J2EE CA adapter, you need to use a BMP model.
- The bean's model requires data from multiple stores: WebLogic Server's CMP engine can only pull data from a single table. WebLogic Server 7.0 will support multi-table CMP access, but what do you do if the data in your bean model is from multiple databases? Although there are a number of significant performance reasons for not having a single entity EJB represent data from multiple stores, there are some scenarios where it's a requirement (especially when you try to integrate a legacy system with a new implementation). For these scenarios, a BMP bean should be used.
- The database requires nonstandard SQL: Databases differentiate themselves by adding proprietary extensions that enable better performance and robust functionality. For example, most databases offer a technique for doing automatic primary key generation; others offer specialized ways of doing optimistic locking at the database level. To take advantage of these features, the SQL submitted to a database usually has to be customized with proprietary extensions defined by the database vendor. CMP engines can differentiate themselves by supporting a wide range of these custom extensions. WebLogic Server 6.1 supports most primary key generation techniques and Oracle's serializable SQL extensions, but if your database requires further optimized SQL, you may need to use a BMP instead.
Why CMP?
BMP entity EJBs won't perform very well. If you're using a BMP EJB, chances are your scenario matches one of the oddball cases listed above. If you choose to use a BMP entity EJB when a CMP engine or a stateless session EJB with JDBC could be used, you're taking an unnecessary performance hit. A BMP entity EJB doesn't come without the overhead of container management, server management, and (sometimes) unnecessary life cycle migration. The purpose of using a BMP is:
- To take advantage of representing persistent data in a business object model in your system
- To leverage the EJB deployment model, allowing for behavioral changes to be made by modifying XML, not code
- Your data access falls into one of the scenarios listed in the first section.
But, if what you're trying to accomplish doesn't fit into one of these scenarios, and it is possible for a CMP container engine to functionally accomplish the data access you require, you should definitely be using CMP. There are a number of concrete reasons for using CMP:
- BMP entity EJBs can't take advantage of in-server locking models: These include pessimistic and optimistic in-server locking models. There are very few containers that support an in-server optimistic locking model, and it can be very powerful. Optimistic locking delays attempts to lock the underlying data in a database until the transaction begins the commit process. This is difficult to implement because the container needs to be intelligent and aware of any data modifications from the time the transaction started and the time the container places a lock on the data. If the data was modified in that time span by another process, this is called a collision, and the container needs to resolve it by rolling back the transaction or overwriting the data. Containers that support optimistic locking provide a more scalable implementation because data will be locked less frequently and the application server won't spend as many cycles blocking access to locked data.
By having a container supporting pessimistic and optimistic locking models, a bean developer is freed from dealing with multi-request transactional issues, collision handling, and specialized SQL needed to make these locking scenarios occur. BMP entity EJBs cannot have a container implement these policies since it requires interaction with the underlying persistent store. - BMP entity EJBs do not have EJB-QL support: EJB-QL is used to define find() methods and ejbSelect() methods. It allows a developer to quickly configure the way an entity EJB behaves without developing complicated JDBC or SQL code. Vendors, including WebLogic, may add enhancements to EJB-QL to allow developers to continually create more complicated queries. By dong this, the need for using optimized stored procedures diminishes and business logic moves further into the application server tier (which is where it belongs). Additionally, EJB-QL reduces the amount of code in an entity EJB, making it more maintainable, easier to support, and quicker to develop. BMP entity EJBs require find() methods to be implemented manually and, for the reasons listed above, should be avoided.
- BMP entity EJBs do not have any support for relationships: Your data has relationships with other data. It's a fact of life. If your data has relationships, then your object models in memory will also have relationships. Implementing relationships manually is very challenging. They can be directional and have multiplicity constraints applied to them. Also, many systems don't perform optimally because of the poor implementation of relationships. For example, if you have a one-to-many relationship of objects that are persistently stored, you might implement an aggressive loading model that brings a parent and all of its children into memory every time the parent is accessed. If the parent has 10,000 children, but those children objects are not needed on a regular basis, the system is being burdened with activities that could otherwise be avoided.
BMP entity EJB containers cannot support relationships because a container needs access to the underlying relationship management technology being used in the persistent store. In the case of relational databases, a container would need to access the primary and foreign key columns to properly manage the relationship. Using BMP, all persistent store access is managed by the bean itself, so the bean needs to manage the relationship manually. Since BMP relationships are nonstandard and very difficult to implement, you run the risk of building a poor-performing system. Also, WebLogic Server's CMP implementation provides aggressive and lazy loading of relationships that would be nearly impossible to implement using BMP. - BMP cannot avoid the n+1 problem: One of the problems that plagued CMP engines with EJB 1.1 was the n+1 problem. This was caused by containers that required n+1 database queries and network invocations to load entity EJBs in a parent-child relationship. For example, if you had an Order entity EJB with 1,000 LineItem children entity EJBs in a one-to-many relationship, EJB 1.1 CMP engines would require 1,001 database queries to load all of the EJBs. This is crazy, since it's likely that all of the data was stored in only two tables.
EJB 2.0 solved this problem for CMP engines by requiring entity EJBs in a relationship to use local interfaces. The container could be guaranteed that entity EJBs in a relationship were going to exist in the same virtual machine, and if a vendor required relationships to be in the same database, the CMP engine could continually optimize the n+1 scenario to be a 1+1 database hit scenario. This isn't the case for BMP containers. Since the container does not create the query, there is no way to "aggregate" all of the information in a standard way to pull in all of the child data all at once. The BMP engine will always have to iterate each of the children, forcing the n+1 problem to remain. One reason for using BMP in a relationship, however, is if you need a relationship that operates over remote interfaces. If the local interface restriction cannot be adhered to, using BMP may be an option. - BMP cannot do cascading deletes: For EJBs in a relationship, a CMP container can perform a cascading delete. This means that if a parent object is destroyed, the child objects in the relationship are automatically destroyed as well. Cascading deletes can be done by manually deleting each EJB one at a time or by using specialized database referential integrity mechanisms that automatically delete all of the data reachable through foreign keys when a row is deleted. The latter is almost always preferred for performance reasons.
Since BMP entity EJB containers do not have access to the underlying data store, the EJB cannot take advantage of optimized database techniques for deleting a massive amount of data. This can have a huge performance and portability impact. - BMP containers cannot do automatic primary key and table generation: One of the features in WebLogic Server's container implementation is the ability to create tables, set up relationships, and generate database-generated primary keys automatically. By having the container automatically create the appropriate tables and relationships when they don't exist, development time is shortened since a time-consuming mapping of the EJB to the database doesn't have to occur. Additionally, most databases offer the ability to automatically generate a universally unique primary key value. Entity EJBs can leverage the database-generated primary key values if the container can query the database and pull that information into the server.
It's impossible for a BMP container to create database tables or set up relationships in any way. Additionally, primary key generation techniques are proprietary based on the database being used, and cannot be done portably using a BMP entity EJB.
Conclusion
CMP entity EJBs are not used enough in production systems and BMP implementations are used too frequently for the wrong reasons. When you implement your next project, consider the strengths in performance and reduction in development that can be added by leveraging a high-quality CMP container as opposed to developing data access logic using a BMP architecture. I guarantee you'll be happy with the results.
About the Author
Tyler Jewell is BEA's director of technology evangelism and the coauthor of Mastering Enterprise JavaBeans 2.0 and Professional Java Server Programming (J2EE 1.3). He writes widely on the Web on the subject of both J2EE and Web services.
Copyright © 2002 SYS-CON Media, Inc.
[펌] WebService Behavior
About the WebService Behavior | Internet Development Index |
The WebService behavior enables client-side script to invoke remote methods exposed by Web Services, or other Web servers, that support the SOAP and Web Services Description Language (WSDL) 1.1. This behavior provides developers the opportunity to use and leverage SOAP, without requiring expert knowledge of its implementation. The WebService behavior supports the use of a wide variety of data types, including intrinsic SOAP data types, arrays, objects, and Extensible Markup Language (XML) data. The WebService behavior is implemented with an HTML Component (HTC) file as an attached behavior, so it can be used in Microsoft Internet Explorer 5 and later versions.
This article provides a general overview of the WebService behavior and examines the improvements and alternatives it offers to traditional database-driven Web page design. Once the WebService behavior is attached to a Web page, Internet Explorer 5 can invoke methods from Web Services and use the results directly in client-side script. The Using the WebService Behavior article complements this overview by providing detailed code samples and by discussing the specific functionality of the behavior.
The following topics are covered in this document.
- Prerequisites
- Terminology
- WebService HTC File
- Benefits
- Introduction
- Comparing the WebService Approach to Forms
- What the WebService Behavior Does
- SOAP
- Web Services
- WebService Behavior Documentation
- Related Topics
Prerequisites
To use the information in this document most effectively, you should have a good understanding of scripting and Dynamic HTML (DHTML) behaviors. Specifically, you should be able to script using an object that is implemented in an HTC file.
The WebService behavior uses the SOAP protocol to communicate with Web Services, yet its purpose is to provide a simple way to take advantage of this protocol without requiring expert knowledge of SOAP. Although no knowledge of these protocols is necessary to use the WebService behavior, some familiarity with these topics will help you understand how the behavior works behind the scenes. For more information, see the section on SOAP.
It is not necessary to implement a Web Service to use the WebService behavior?all that is required is an existing compatible Web Service. Also, the Web Service must be accessible from the Web server that is hosting the Web page. To initiate remote method calls using the WebService behavior, it is necessary to know some details about the classes that are implemented on the Web Service, such as the methods and the required parameters. For more information, see the Web Services section.
Terminology
This section defines certain terms that are used throughout the article.
Web Service | Programmable application logic that is accessible using standard Internet protocols. Web Services provide well-defined interfaces, or contracts, that describe the services provided. The WebService behavior uses Web Services. |
---|---|
WebService behavior | The primary subject of this article. A reusable DHTML component that uses Web Services by communicating over HTTP using SOAP. |
callService method | One of the methods exposed by the WebService behavior. |
method call | The invocation of a method. |
synchronous | A form of processing that blocks interaction with the application until execution has completed. |
asynchronous | A form of processing that permits interaction with the application during the execution of a task. |
WebService HTC File
The WebService behavior is encapsulated in an HTC file. Therefore, before you begin using the behavior in your own Web pages, download the WebService HTC File and copy it to a folder in your Web project.
For more information on referencing the HTC file in a Web page, see Using the WebService Behavior, which shows you how to set up the WebService behavior and use it to invoke remote methods. Also, see the WebService reference pages.
Benefits
The primary benefit of the WebService behavior is that it provides a simple way for you to call methods that are exposed by Web Services using the SOAP protocol. The WebService behavior enables you to call a remote method using a few, straightforward, client-side scripting methods exposed by the behavior. Navigating to another URL is unnecessary when using the WebService behavior to deliver data to a page because DHTML is used to update the page's content. This approach enhances the browsing experience significantly, compared to traditional browsing approaches that require a full page refresh.
The WebService behavior is implemented as an attached behavior, as opposed to an element behavior, and, therefore, can be used in Internet Explorer 5 and later versions. The WebService behavior is a reusable component, so its encapsulated capabilities help reduce the need to duplicate code, thus improving the overall organization of the client-side script and the Web application. All protocol-specific code, and most of the code required to handle the data transactions, is encapsulated from the client-side script in the main Web page, which is a general benefit of using DHTML behaviors. You only need to attach the WebService behavior once in order to invoke methods from one or more different Web Services.
This behavior enables Internet Explorer 5 users to take advantage of some of the latest cross-platform programming techniques. Web Services can reside anywhere on the Internet and encapsulate building blocks of capability, which can be assembled, packaged, or presented in various ways in a Web page. The XML, Web Services, and the .NET Framework site provides access to a variety of tools and resources for designing and using Web Services. Using such a distributed architecture offers improved scalability because data- or CPU-intensive tasks can be organized into dedicated Web Services, freeing the client from unnecessary burden. Therefore, the WebService behavior can help enhance the client browser experience and improve the overall organization of the Web application.
The WebService behavior provides a more streamlined approach to the problem of delivering information from the Web server to Internet Explorer 5 and later. Using the WebService behavior to access Web Services simplifies things on the client side, making the use of Web Services more appealing. The behavior can be updated and adapted as the SOAP standard evolves, without requiring major changes to client-side script in the main Web page.
Introduction
The Internet has already evolved well beyond basic connectivity and presentation services to offer rich interactive pages, which are commonly enhanced by client-side or server-side script and other components. To further extend the performance and versatility of the Internet, Web Services are being developed that provide new capabilities which Internet Explorer 5 and later can use to deliver a new level of performance.
The primary reason to use the WebService behavior is that it provides you with a way to use Web Services in Internet Explorer 5 and later without having expert knowledge of SOAP. With the WebService behavior, you can implement a method call on a Web Service with just a few lines of code and you can apply the WebService behavior in any Web page or from within another HTC file. For practical advice on using the WebService behavior, see Using the WebService Behavior.
The WebService behavior simplifies the use of Web Services by handling communication of the SOAP data packets between the browser and the Web Service. All the SOAP-specific handling code is encapsulated inside the behavior, which helps to simplify client-side script in the main Web Page?this is a general benefit that comes from using DHTML behaviors.
The WebService behavior parses the XML data returned from method calls and exposes objects and properties to client-side script. The objects that are exposed by the behavior enable error handling and easy access to the returned data. You only need to attach the WebService behavior to the Web Page once, even if the client script references methods from several different Web Services.
WSDL is an XML-based language that describes the features and methods exposed by a Web Service. The WebService behavior supports WSDL 1.1 and can be used with other products that support this version. Microsoft .Net Frameworks SDK and Microsoft Visual Studio .NET generate the appropriate WSDL for Web Services automatically.
Comparing the WebService Approach to Forms
To help explain why the WebService behavior is so useful, it's worth comparing the WebService behavior technique with the approach commonly used to deliver data-driven Web sites today. The following diagram shows the basic process used by each technique.
The first part of the illustration shows how a Web page containing a form commonly uses either the get or post method through HTTP to update a Web page. Each time a form is submitted, the client navigates to a new URL, after which the browser downloads and renders the entire page. This method is widely used today but is inefficient because the Web page refreshes and re-renders an entire page of content, even if only a small percentage of the page has actually changed. Web surfers commonly encounter this behavior when browsing e-commerce and data-driven pages. When there's a need to browse numerous items and pages, such as when searching a catalog or search engine, the delays and waste of resources can be significant.
The second part of the diagram illustrates how a Web page can use the WebService behavior to avoid the drawbacks associated with the traditional form submit approach. The WebService behavior receives method calls from the client-side script and sends a request to the Web Service. The results are returned to the client script, and processing continues. The Web page can then use the information in whatever context is required, such as updating some portion of page rendering using DHTML.
A key feature of the WebService behavior is that it enables client-side script to access a Web Service without requiring navigation to another URL. Using the WebService behavior approach, the portions of the page that are indicated by the user's inputs can be dynamically updated using DHTML, providing a significant improvement in the browsing experience.
What the WebService Behavior Does
The WebService behavior enables a method call to be made to a Web Service using a simple scripted syntax, as shown in the following snippet.
iCallID = myService.MyMath.callService("add",int1,int2);
To invoke a method on a Web Service, the author first attaches the WebService.HTC file to any element in the page. Once the behavior is attached, the WebService behavior enables either synchronous or asynchronous calls to be made to Web Services from client-side script. The asynchronous nature of a remote method invocation means that there is a delay between the execution of the method and the arrival of its returned result. Using the synchronous mode of processing means that the client script processing halts until the callService method has completed. The asynchronous mode of method invocation is the default mode of the WebService behavior.
The WebService behavior handles the process of calling the method and receiving the raw XML data packets from the Web Service. The user has the option of using either an event handler or a callback handler function to process the results. If an event handler is used, the WebService behavior fires the onresult event, which occurs when the WebService receives the response from a method call. Alternatively, if a callback function is used to process results, a result object is passed directly as an input parameter to the callback function.
Any client script using the WebService behavior should always test the error property to determine if the method invocation was successful. When an error is encountered, an errorDetail object is also exposed; this object has properties that can be evaluated to help identify the source of the error. The different techniques for handling returned results from method calls are described in Using the WebService Behavior.
The WebService behavior cannot directly invoke a method on a Web Service that is hosted in a different domain from the machine hosting the Web page. Nevertheless, a Web Service running on the Web server hosting the Web page can be configured to act as a proxy for other remote Web Services. For more information, see Calling Methods on Remote Servers.
SOAP
SOAP is a standard that uses XML data to communicate between processes and devices. Because SOAP supports HTTP, it is becoming a popular mechanism for binding Internet-based cross-platform applications together. The WebService behavior enables developers to take advantage of the versatility of XML and SOAP without needing to develop SOAP-specific code. In most cases, it is much easier to use the WebService behavior with some client script than it is to write the code to generate and handle SOAP transactions.
SOAP Resources
A detailed discussion of SOAP lies outside the scope of this article. The following articles provide comprehensive discussions and technical information on SOAP.
- A Young Person's Guide to SOAP
- SOAP: Simple Object Access Protocol
- SOAP Toolkit version 2.0 SP2
- W3C: Simple Object Access Protocol (SOAP) 1.1
Web Services
Traditional software applications provide application programming interfaces (APIs) that enable the applications to be automated by other clients and servers. But, unlike most of these APIs, Web Services expose methods that can be called from other machines and devices across the Internet. For example, an authentication Web service can expose methods that are used by other applications for access control, and developers can invoke the methods on the Web Service to enhance their own Web applications.
In general, the WebService behavior should work well with Web Services and servers that support both SOAP and WSDL 1.1. The behavior has been tested successfully with the SOAP Toolkit version 2.0 SP2. The range of supported data types depends on the server implementation. See WebService Behavior: Supported Data Types for more information.
Web Service Resources
Any server that exposes methods which can be invoked using SOAP and WSDL 1.1 can be used by the WebService behavior. All you need to begin using the WebService behavior is a live Web Service that can be accessed from your browser.
Many of you will want to write Web Services to complement your WebService behavior-enhanced Web pages. The SOAP Toolkit version 2.0 SP2 provides a powerful collection of tools to help you create Web Services, and it is compatible with the WebService behavior. For developers interested in the next generation of Internet development tools, the Microsoft .NET Frameworks SDK and Visual Studio .NET products provide extensive support for developing Web Services, SOAP and WSDL 1.1.
Here are some recommended tools and references.
- Microsoft .NET Home Page
- Visual Studio .NET
- Web Services Description Language (WSDL) 1.1
- XML, Web Services, and the .NET Framework
Live Web Services
The following links point to Web sites that demonstrate live Web Services.
WebService Behavior Documentation
The following documents cover the basics of using the WebService behavior and related issues.
- Using the WebService Behavior
This practical article shows you how to set up the WebService behavior and use it to invoke remote methods.
- WebService Behavior
This is the main reference page for the WebService behavior.
- WebService HTC File
Click the link to download the WebService HTC file.
- WebService Behavior: Supported Data Types
This page lists the XML and ASP.NET data types supported by the WebService behavior.
Related Topics
- Introduction to DHTML Behaviors
- HTC Reference
- Using HTML Components to Implement DHTML Behaviors in Script
- Using Custom Tags in Internet Explorer
- Using DHTML Behaviors
[펌] WebService의 간략한 소개
출처 : http://bioinfo.sarang.net/wiki/WebService
인터넷과 같은 네트워크를 통해 기술하고, 배포하고, 실행할 수 있는 모듈화한 애플리케이션을 의미한다. HTTP프로토콜, XML을 이용. 최근 IT산업의 빅키워드. One of the RelationshipRecovery.
Gartner는 웹서비스를 다음처럼 정의했다.
loosely coupled (SeeAlso Orthogonality) software components that interact with one another dynamically via standard Internet technologies |
WebService는 개발플랫폼(OperatingSystem)과 개발언어(ProgrammingLanguage)를 가리지 않으며, 심지어는 이용 디바이스도 가리지 않는 대통합의 전초기지로서 자리매김하고 있다. 이 때문에 CORBA가 이루지 못한 진정한 DistributeObject 환경구축을 웹서비스가 이뤄줄 것이라는 기대도 높다.
두가지 기술이 있다.
- SOAP : ObjectOriented, stateful
- XmlRpc : procedural, stateless
- provider
- 수요자
- broker
- provider가 broker에게 발행(publish)하고,
- broker와 수요자사이에 검색(find)이 이루어지고,
- 제공자와 수요자사이의 결합(bind)이라는 세가지 기능을 같게 된다.
관련자료들
[펌] ASP.NET을 사용하여 만든 XML Web services의 상태 관리
XML Web services를 구현하는 클래스가 WebService 클래스에서 파생되면 XML Web services는 다른 ASP.NET 응용 프로그램과 같은 상태 관리 옵션에 액세스할 수 있습니다. WebService 클래스에는 Session 및 Application 개체를 포함한 많은 공용 ASP.NET 개체가 들어 있습니다.
Application 개체는 Web 응용 프로그램 내에서 실행하는 모든 코드에 액세스할 수 있는 데이터를 저장하기 위한 메커니즘을 제공하지만, Session 개체는 각 클라이언트 세션을 기반으로 데이터를 저장하기 위한 메커니즘을 제공합니다. 클라이언트가 쿠키를 지원하는 경우 쿠키는 클라이언트 세션을 확인할 수 있습니다. Session 개체에 저장된 데이터는 WebService에서 파생되는 클래스에 대해 WebMethod 특성의 EnableSession 속성이 true로 설정된 경우에만 사용할 수 있습니다. WebService에서 파생되는 클래스는 Application 개체에 자동으로 액세스할 수 있습니다.
특정 클라이언트 세션에 대한 상태에 액세스하고 저장하려면
- XML Web services를 선언합니다.
[C#]<%@ WebService Language="C#" Class="ServerUsage" %>
[Visual Basic]<%@ WebService Language="VB" Class="ServerUsage" %>
- System.Web.Services 네임스페이스에 대한 참조를 추가합니다.
[C#]using System.Web.Services;
[Visual Basic]Imports System.Web.Services
- WebService에서 XML Web services를 구현하는 클래스를 파생합니다.
[C#]public class ServerUsage : WebService
[Visual Basic]Public Class ServerUsage : Inherits WebService
- XML Web services 메서드를 선언합니다. 여기서, 이 메서드는 WebMethod 특성의 EnableSession 속성을 true로 설정합니다.
[C#][ WebMethod(EnableSession=true) ]public int PerSessionServiceUsage()
[Visual Basic]< WebMethod(EnableSession:=True) > _Public Function PerSessionServiceUsage() As Integer
- 나중에 검색할 상태의 이름을 지정하는 Session에 상태를 저장합니다. 다음 예제에서는
MyServiceUsage
상태 변수에 값 1을 저장합니다.[C#]Session["MyServiceUsage"] = 1;
[Visual Basic]Session("MyServiceUsage") = 1
- Session에 저장된 상태 변수에 액세스합니다.
다음 예제에서는
MyServiceUsage
상태 변수에 액세스하여 해당 값을 1씩 늘립니다.[C#]Session["MyServiceUsage"] = ((int) Session["MyServiceUsage"]) + 1;
[Visual Basic]Session("MyServiceUsage") = CInt(Session("MyServiceUsage")) + 1
XML Web services를 호스팅하는 웹 응용 프로그램에 대한 상태에 액세스하고 저장하려면
- XML Web services를 선언합니다.
[C#]<%@ WebService Language="C#" Class="ServerUsage" %>
[Visual Basic]<%@ WebService Language="VB" Class="ServerUsage" %>
- System.Web.Services 네임스페이스에 대한 참조를 추가합니다.
[C#]using System.Web.Services;
[Visual Basic]Imports System.Web.Services
- WebService에서 XML Web services를 구현하는 클래스를 파생합니다.
[C#]public class ServerUsage : WebService
[Visual Basic]Public Class ServerUsage : Inherits WebService
- XML Web services 메서드를 선언합니다.
[C#][ WebMethod ]public int PerSessionServiceUsage()
[Visual Basic]< WebMethod > _Public Function PerSessionServiceUsage() As Integer
- 나중에 검색할 상태의 이름을 지정하는 Application에 상태를 저장합니다. 다음 예제에서는
appMyServiceUsage
상태 변수에 값 1을 저장합니다.[C#]Application["appMyServiceUsage"] = 1;
[Visual Basic]Application("appMyServiceUsage") = 1
- Application에 저장된 상태 변수에 액세스합니다.
다음 예제에서는
appMyServiceUsage
상태 변수에 액세스하여 해당 값을 1씩 늘립니다.[C#]Application["appMyServiceUsage"] = ((int) Application["appMyServiceUsage"]) + 1;
[Visual Basic]Application("appMyServiceUsage") = _ CInt(Application("appMyServiceUsage")) + 1
다음 코드 예제는 ServerUsage
및 PerSessionServerUage
라는 XML Web services 메서드가 있는 XML Web services입니다. ServerUsage
는 XML Web services 메서드와 통신하는 클라이언트와 상관 없이 ServerUsage
XML Web services 메서드에 대한 액세스 횟수를 나타내는 방문 횟수 카운터입니다. 예를 들어, 세 개의 클라이언트가 ServerUsage
XML Web services 메서드를 연속적으로 호출하면 마지막 클라이언트가 반환 값으로 3을 받습니다. 반면, PerSessionServiceUsage
는 특정 클라이언트 세션에 대한 방문 횟수 카운터입니다. 따라서, 세 개의 클라이언트가 PerSessionServiceUsage
에 연속적으로 액세스하면 각 클라이언트는 첫 호출 때와 같은 1을 반환 값으로 받습니다.
[C#]<%@ WebService Language="C#" Class="ServerUsage" %>using System.Web.Services;public class ServerUsage : WebService { [ WebMethod(Description="Number of times this service has been accessed.") ] public int ServiceUsage() { // If the XML Web service method hasn't been accessed, // initialize it to 1.if (Application["appMyServiceUsage"] == null)
{Application["appMyServiceUsage"] = 1
; } else { // Increment the usage count.Application["appMyServiceUsage"] = ((int) Application["appMyServiceUsage"]) + 1;
} return (int)Application["appMyServiceUsage"]
; } [WebMethod
(Description="Number of times a particualr client session has accessed this XML Web service method.",EnableSession=true
) ] public int PerSessionServiceUsage() { // If the XML Web service method hasn't been accessed, initialize // it to 1.if (Session["MyServiceUsage"] == null)
{Session["MyServiceUsage"] = 1;
} else { // Increment the usage count.Session["MyServiceUsage"] = ((int) Session["MyServiceUsage"]) + 1;
} return (int)Session["MyServiceUsage"];
}}
[Visual Basic]<%@ WebService Language="VB" Class="ServerUsage" %>Imports System.Web.ServicesPublic Class ServerUsage Inherits WebService <WebMethod(Description := "Number of times this service has been accessed.")> _ Public Function ServiceUsage() As Integer ' If the XML Web service method hasn't been accessed, initialize ' it to 1. If Application("appMyServiceUsage") Is Nothing Then Application("appMyServiceUsage") = 1 Else ' Increment the usage count. Application("appMyServiceUsage") = _ CInt(Application("appMyServiceUsage")) + 1 End If Return CInt(Application("appMyServiceUsage")) End Function <WebMethod(Description := "Number of times a particular client session has accessed this XML Web service method.", EnableSession := True)> _ Public Function PerSessionServiceUsage() As Integer ' If the XML Web service method hasn't been accessed, ' initialize it to 1. If Session("MyServiceUsage") Is Nothing Then Session("MyServiceUsage") = 1 Else ' Increment the usage count. Session("MyServiceUsage") = CInt(Session("MyServiceUsage")) + 1 End If Return CInt(Session("MyServiceUsage")) End Function End Class
참고 항목
ASP.NET 상태 관리 | ASP.NET을 사용하여 XML Web services 빌드
2002년 11월 15일
[펌] webservice
CommandHelper.cs
using System;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Xml;
//using System.EnterpriseServices;
using System.Configuration;
namespace WebService1
{
//commandText유형을 정의
enum CmdType
{
SqlQuery,
StoredProc
};
// [ClassInterface(ClassInterfaceType.AutoDual)]//기존 COM객체 지원
// [ComVisible(true)]
//[JustInTimeActivation(true)]
//개체를 비활성인 컨텍스트전용객체로 만듬 이는 객체가 사용되고나서 메모리에서없어져도
// 해당 컨텍스트는 메모리에 그 개체를 남겨두어 다음 호출시 빠르게 반응하게함
//[ObjectPooling(MinPoolSize=1,MaxPoolSize=5)]//오브젝트풀링
//[Transaction(TransactionOption.Required)]
//트랜잭션 의 옵션들 상세내용은 127번 게시물 참조
//IDisposable인터페이스는 관리되지않는 리소스(dbconnect등)를 메모리해제키위해 사용
// Dispose메서드구현으로 적용함
class CommandHelper //: System.EnterpriseServices.ServicedComponent,IDisposable
{
protected SqlConnection conn;
private string conStr;
public CommandHelper()
{
//conStr=System.Configuration.ConfigurationSettings.AppSettings["constr"];
conStr="server=dotnet11;uid=sa;pwd=;database=test";
conn=new SqlConnection(conStr);
}
//public csfirstCOM(string conStr)
//{
// this.conStr=conStr;
// conn=new SqlConnection(conStr);
//}
//sqltext가 스토어드 프로시져일때 update,delete,insert에 사용할 함수
//commandType(sql,proc)
private SqlCommand BuildIntCommand(string procName,IDataParameter[] parameters,CmdType commandType)
{
SqlCommand command=null;
if(parameters==null)
{
command=BuildQueryCommand(procName,null,commandType);
return command;
}
command=BuildQueryCommand(procName,parameters,commandType);
command.Parameters.Add(new SqlParameter("@RtnValue",SqlDbType.Int,4,ParameterDirection.ReturnValue,false,0,0,string.Empty,DataRowVersion.Default,null));
return command;
}
//sqltext가 스토어드 프로시져일때select문에 사용할 함수
private SqlCommand BuildQueryCommand(string procName,IDataParameter[] parameters,CmdType commandType)
{
SqlCommand command=new SqlCommand(procName,conn);
if(commandType==CmdType.StoredProc)
command.CommandType=CommandType.StoredProcedure;
else
command.CommandType=CommandType.Text;
if(parameters==null)
return command;
foreach(SqlParameter param in parameters)
{
command.Parameters.Add(param);
}
return command;
}
//1.update,delete,insert를 실행하는 함수
// [AutoComplete] //트랜잭션적용의 경우
public int RunProc(string procName,IDataParameter[] parameters,out int rowsAffected)
{
int result;
conn.Open();
SqlCommand command=BuildIntCommand(procName,parameters,CmdType.StoredProc);
rowsAffected=command.ExecuteNonQuery();
result=(int)command.Parameters["@RtnValue"].Value;
conn.Close();
return result;
}
//2.select를 실행하고 SqlDataReader를 리턴하는 함수
public SqlDataReader RunProc(string procName,IDataParameter[] parameters)
{
SqlDataReader returnReader;
conn.Open();
SqlCommand command=BuildQueryCommand(procName,parameters,CmdType.StoredProc);
//command.CommandType=CommandType.StoredProcedure;
returnReader=command.ExecuteReader(CommandBehavior.CloseConnection);
return returnReader;
}
//3.where절없는 select실행 SqlDataReader리턴
public SqlDataReader RunProc(string procName)
{
SqlDataReader returnReader;
conn.Open();
SqlCommand command=BuildQueryCommand(procName,null,CmdType.StoredProc);
//command.CommandType=CommandType.StoredProcedure;
returnReader=command.ExecuteReader(CommandBehavior.CloseConnection);
return returnReader;
}
//4.select를 실행하고 DataSet을 리턴하는 함수
public DataSet RunProc(string procName,IDataParameter[] parameters,string tblName)
{
DataSet dataset=new DataSet();
SqlDataAdapter sqlDA=new SqlDataAdapter();
sqlDA.SelectCommand=BuildQueryCommand(procName,parameters,CmdType.StoredProc);
conn.Open();
sqlDA.Fill(dataset,tblName);
conn.Close();
return dataset;
}
//5.조건없는 select실행후 DataSet리턴
public DataSet RunProc(string procName,string tblName)
{
DataSet dataset=new DataSet();
conn.Open();
SqlDataAdapter sqlDA=new SqlDataAdapter();
sqlDA.SelectCommand=BuildQueryCommand(procName,null,CmdType.StoredProc);
sqlDA.Fill(dataset,tblName);
conn.Close();
return dataset;
}
//6.기존 DataSet의 Table에 결과셋을 추가
//Relation설정,새로운 Table 추가등에 사용하는 함수
public void RunProc(string procName,IDataParameter[] parameters,DataSet dataSet,string tblName)
{
conn.Open();
SqlDataAdapter sqlDA=new SqlDataAdapter();
sqlDA.SelectCommand=BuildIntCommand(procName,parameters,CmdType.StoredProc);
sqlDA.Fill(dataSet,tblName);
conn.Close();
}
//7.조건없는 Relation설정,새로운 Table 추가등에 사용하는 함수
public void RunProc(string procName,DataSet dataSet,string tblName)
{
conn.Open();
SqlDataAdapter sqlDA=new SqlDataAdapter();
sqlDA.SelectCommand=BuildIntCommand(procName,null,CmdType.StoredProc);
sqlDA.Fill(dataSet,tblName);
conn.Close();
}
//8.sql문일때 update,insert,delete
public int RunIntCmd(
string cmdText,
IDataParameter[] parameters
)
{
int result;
conn.Open();
SqlCommand command=BuildIntCommand(cmdText,parameters,CmdType.SqlQuery);
result=command.ExecuteNonQuery();
conn.Close();
return result;
}
//9.sql문일때 select ->sqldatareader select * from authors where au_id=@au_id and au-fname=@au_fname
public SqlDataReader RunCmd(
string cmdText,
IDataParameter[] parameters
)
{
SqlDataReader reader;
SqlCommand command=this.BuildQueryCommand(cmdText,parameters,CmdType.SqlQuery);
conn.Open();
reader=command.ExecuteReader(CommandBehavior.CloseConnection);
return reader;
}
//10.where절없는 select->sqldatareader
public SqlDataReader RunCmd(
string cmdText
)
{
SqlDataReader reader;
SqlCommand command=this.BuildQueryCommand(cmdText,null,CmdType.SqlQuery);
conn.Open();
reader=command.ExecuteReader(CommandBehavior.CloseConnection);
return reader;
}
//11.sql문일때 select->DataSet
public DataSet RunCmd(
string cmdText,
IDataParameter[] parameters,
string tblName
)
{
DataSet dataset=new DataSet();
SqlDataAdapter sqlDA=new SqlDataAdapter();
sqlDA.SelectCommand=BuildQueryCommand(cmdText,parameters,CmdType.SqlQuery);
conn.Open();
sqlDA.Fill(dataset,tblName);
conn.Close();
return dataset;
}
//12.where절없는 select ->DataSet
public DataSet RunCmd(
string cmdText,
string tblName
)
{
DataSet dataset=new DataSet();
SqlDataAdapter sqlDA=new SqlDataAdapter();
sqlDA.SelectCommand=BuildQueryCommand(cmdText,null,CmdType.SqlQuery);
conn.Open();
sqlDA.Fill(dataset,tblName);
conn.Close();
return dataset;
}
//13.sql문 select->sqlxmlreader for xml auto,Elements
public XmlReader RunXmlCmd(
string cmdForxml,
IDataParameter[] parameters
)
{
XmlReader reader;
SqlCommand selCommand=this.BuildQueryCommand(cmdForxml,parameters,CmdType.SqlQuery);
conn.Open();
reader=selCommand.ExecuteXmlReader();
return reader;
}
//14.where절 없는 sql문 select->sqlxmlreader
public XmlReader RunXmlCmd(
string cmdForxml
)
{
XmlReader reader;
SqlCommand selCommand=this.BuildQueryCommand(cmdForxml,null,CmdType.SqlQuery);
conn.Open();
reader=selCommand.ExecuteXmlReader();
return reader;
}
}
}
[펌] WebService를 위한 표준
WebService를 위한 표준
홍영준
들어가면서
지난 2000년 8월, Microsoft사의 NGWS(New Generation Windows Service)와 함께 대중적으로 WebService가 알려지기 시작했다. 이후 NGWS는 .NET이란 이름으로 변경이 되어졌고 베타 1이 출시되었으며, 이제 막 베타 2가 출시되었다. 이후 사람들은 실제 .NET 프레임워크를 이용하여 편리하게 WebService를 구축하기 시작했으며 그 가능성이 전파되고 있다.
WebService는 소위 말하는 XML형태의 RPC 프로토콜이다. 물론 XML-RPC, XMOP(XML Metadata Object Persistence)과 같은 표준이 있기는 하지만, XML-RPC, XMOP는 널리 받아들여지지 못했다. 이때 SOAP (Simple Object Access Protocol)이 새롭게 등장했다. SOAP 0.9 스팩은 기존의 COM을 기초로 하여 Microsoft사를 주축으로 1999년 처음 세상에 등장했으며 1999년 11월 1.0을 그리고 2000년 4월 1.1 버전(http://www.w3.org/TR/SOAP/)이 그리고 현재는 1.2 버전(http://www.w3.org/TR/2001/WD-soap12-20010709/)이 발표되었다. 뿐만 아니라 관련된 프로토콜들이 속속 등장했으며 그 중 가장 주목할 것들은 바로 SOAP과 함께 WSDL(Web Service Description Language), DISCO(Web Services Discovery), UDDI(Universal Description, Discovery and Integration) 같은 것들이 있다.
이후 WebService는 W3C표준 절차를 밟고 있을 뿐 아니라, IBM, Oracle, SUN, Borland 같은 주요 벤더들에게 폭넓게 지지를 받고 있으며 각 벤더들의 주요 개발 툴들은 이 WebService를 수용하기 위해서 끊임없이 노력하고 있다.
WebService는 향후 IT분야에 큰 변화를 초래할 것이다. 이것은 마치 FTP 같은 파일 전송 프로토콜에서 시작한 인터넷이 RPC(Remote Procedure Protocol)로 클라이언트/서버 환경의 중요 인프라로 떠올랐듯이, WebService는 HTML 기반의 페이지 서비스로써의 웹을 진정한 분산 어플리케이션의 중요 인프라로 만들어 줄 것이다. 그러므로 앞으로 웹 프로그래밍의 수준이 이전과는 완전히 달라지게 될 것이다.
기존 분산 어플리케이션 환경의 문제점
앞서 WebService는 XML 기반의 RPC 프로토콜이라고 전제 했다. 좀더 자세하게 말하면 ORPC(Object RPC)라고 하는 것이 맞을 것이다. RPC와 ORPC의 차이는 Object RPC의 경우 RPC의 endpoint를 실제 프로그래밍 언어의 객체로 매핑시킬 수 있는 기능을 제공하고 있다는 것이다. 즉, 통신 프로토콜과 객체 지향의 결합이라고 할 수 있다. 현재 가장 많이 사용되고 있는 ORPC 기반의 분산 어플리케이션 환경으로 DCOM, CORBA, JAVA RMI같은 것들이 있다. 물론 DCOM의 경우 ORPC, CORBA의 경우 IIOP(Internet Inter-ORB Protocol (IIOP)), JAVA RMI의 경우 JRMP(Java Remote Method Protocol)로 그 이름은 약간 씩 다를 수 있다.
그러나 이러한 프로토콜들은 모두 현재의 인터넷 환경을 고려하지 않고 만들어 진 것들이며, 대체로 아래와 같은 한계를 가진다.
첫째, 단일 벤더의 솔루션이라는 한계
DCOM 뿐 아니라 JCP, OMG에서 관리하고 있는 JAVA RMI, CORBA 조차도 실제로는 단일 벤더의 솔루션이라고 할 수 있다. 즉, 실제 클라이언트/서버를 연결할 경우 동일한 벤더의 제품을 사용해야만 다양한 서비스를 연결할 수 있다. 이는 구현의 수준과 내부 프로토콜, 그리고 벤더마다 다른 최적화 기법을 사용함으로써 기인하는 것이다. 그러나 이는 현재의 다양한 환경을 기반으로 하고 있는 인터넷 구성 요소에 적합하지 않다.
둘째, 관리가 가능한 네트워크 환경을 기반
기존의 솔루션들은 모두 관리가 가능한 네트워크 환경을 기반하고 있다. 즉, 신뢰성 있고 보안에 대한 설정 및 관리가 가능한 네트워크 환경에 기반하고 있다. 이러한 특징을 tightly coupled 라고 표현하는데, 이러한 점 역시 현재의 인터넷 환경에 적합하지 않다.
셋째, 고 수준의 실행 환경을 요구한다.
기존의 분산 어플리케이션 환경들은 다양한 분야에 동일한 고 수준의 서비스(객체 생성, 객체 라이프타임 관리,보안…)를 적용시키기를 강요한다. 결과적으로 각 솔루션들을 위한 실행 환경 구현 비용이 증가되며 벤더 종속적인 구현을 부채질하는 요인이 되기도 한다.
넷째, 방화벽/프락시 서버 문제
현대 인터넷 환경에서 빠질 수 없는 것이 바로 방화벽과 프락시 서버이다. 기존의 분산 어플리케이션 환경들은 모두 이 두 가지를 고려하고 있지 않다. 그러므로 만약 이러한 것들을 기초로 분산 환경을 구축할 경우, 방화벽과 프락시 서버를 제거하고 각 구성 요소는 직접 인터넷에 연결되어야 한다. 이것은 사실상 불가능한 일이다.
기타 DCOM의 경우 ping 에 기초한 분산 가비지 컬렉션, 그리고 JAVA RMI의 상태 관리 로 인해 스케일러블한 환경을 구성하기가 쉽지 않다.
이러한 문제들로 기존의 솔루션들이 인터넷 환경에서 그렇게 많이 활용되고 있지 않다. SOAP은 기존의 솔루션이 가지는 이러한 단점을 극복하고자 설계 되었다. 결과적으로 현재 각 솔루션을 주도하고 있는 각 벤더들은 다양한 이름(.NET SUN ONE, HP Netaction,…)으로 WebService 솔루션에 치중하고 있다.
SOAP (Simple Object Access Protocol)
먼저 WebService의 핵심 프로토콜로 SOAP을 소개하도록 하겠다. SOAP 표준은 크게 두 가지를 정의하고 있다. 바로 메시징 시스템 기술과 함께 XML 데이터 표현, 즉 XML 스키마 정의에 대한 부분이며, 객체 생성, 객체 생명 주기, 보안, 전송 프로토콜과 같은 이슈들은 모두 기존의 인프라를 이용토록 설계되어 있다.
SOAP의 메시징 시스템
SOAP 1.0의 경우 기본 전송 프로토콜로 HTTP를 기초로 작성되었다. 그러나 1.2에서는 이것을 메시징 시스템과 원격 프로시져 호출에 필요한 XML 데이터 표현 방식으로 분리시켰다. 즉, SOAP 1.2의 경우 전송 프로토콜로 SMTP, FTP같은 프로토콜을 사용할 수 있는 가능성을 열어 둔 것이다.
전송 프로토콜에 독립적이라 할 지라도 서버 상의 메쏘드를 호출하기 위하여 필요한 과정이 있다. SOAP를 RPC로 사용하기 위하여 필요한 과정이 바로 Request/Response이며 HTTP를 전송 프로토콜을 이용할 경우, 자연스럽게 이러한 과정들은 HTTP Request/Response에 대응되게 된다.
기본적으로는 HTTP POST 방식의 Request를 사용하나 SOAP HTTP Request임을 의미하기 위하여 M-POST를 권장하고 있다.
아래 리스트는 각기 POST 방식의 SOAP HTTP Request와 M-POST방식의 SOAP HTTP Request를 나타낸다.
-------------------------------------------------------------------
M-POST /StockQuote HTTP/1.1
Man: "http://www.w3.org/2001/06/soap-envelope"; ns=NNNN
Content-Type: text/xml; charset="utf-8"
Content-Length: nnnn
NNNN-SOAPAction: "http://electrocommerce.org/abc#MyMessage"
<env:Envelope xmlns:env="http://www.w3.org/2001/06/soap-envelope" >
. . .
</env:Envelope>
-------------------------------------------------------------------
리스트 1. HTTP Extension Framework 를 이용한 SOAP Request
-------------------------------------------------------------------
POST /StockQuote HTTP/1.1
Content-Type: text/xml; charset="utf-8"
Content-Length: nnnn
SOAPAction: "http://electrocommerce.org/abc#MyMessage"
<env:Envelope xmlns:env="http://www.w3.org/2001/06/soap-envelope" >
. . .
</env:Envelope>
-------------------------------------------------------------------
리스트 2. POST를 이용한 SOAP HTTP Request
위의 SOAP HTTP Request의 <env:Envelope/>에 해당하는 부분이 실제 메쏘드 호출에 필요한 정보를 담고 있는 XML 데이터이다. 이와 같은 SOAP HTTP Request에 대해 서버는 적당한 메쏘드를 호출한 후 그 결과를 SOAP HTTP Response로 반환하게 된다. 아래는 SOAP HTTP Response의 한 예이다.
-------------------------------------------------------------------
HTTP/1.1 200 OK
Ext:
Content-Type: text/xml; charset="utf-8"
Content-Length: nnnn
<env:Envelope xmlns:env="http://www.w3.org/2001/06/soap-envelope" >
. . .
</env:Envelope>
-------------------------------------------------------------------
리스트 3. SOAP HTTP Response
역시 <env:Envelope/>에 해당하는 부분이 실제 결과를 표현한 XML 데이터이다.
SOAP Envelope
앞서 기술한 메시징 시스템, 특히 HTTP을 기반으로 한 RPC 시스템에서 실제 메쏘드 호출 및 결과에 대한 데이터 표현을 위해서 사용되는 것이 바로 SOAP Envelope이다. SOAP Envelope은 XML Schema 및 XML Namespace 표준을 이용해서 기술되었다. SOAP Envelop은 크게 메쏘드 호출, 메쏘드 호출 결과 반환, 그리고 메쏘드 호출 및 결과 반환 시 사용할 데이터 타입에 대한 정의로 나눌 수 있다. 아래는 메쏘드 호출 시, 사용되는 SOAP Envelope의 한 예이다.
-------------------------------------------------------------------
<SOAP-ENV:Envelope>
xmlns:SOAP-ENV=http://schemas.xmlsoap.org/soap/envelope/
SOAP-ENV:encodingStyle=http://schemas.xmlsoap.org/soap/encoding/>
<SOAP-ENV:Header>
<r:Transaction xmlns:r="http://example.org/2001/06/tx" env:mustUnderstand="1" > 2
</r:RequestNumber>
</SOAP-ENV:Header>
<SOAP-ENV:Body>
<m:GetTemperature xmlns:m=”Thermostat-URI”>
<City>
<State>FL</State>
</m:GetTemperature>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
-------------------------------------------------------------------
리스트 4. 메쏘드 호출을 위한 SOAP Envelope
위의 리스트 4.에서 보듯이 SOAP Envelope는 크게 헤더와 본문으로 구분되어져 있다. 본문의 경우 실제 메쏘드 호출에 필요한 정보, 즉 메쏘드 이름과 인자 값을 기술하며(위의 경우 GetTemperature 메쏘드와 City, State 인자), 헤더의 경우는 기타 추가적인 정보(트랜잭션, 인증,…)를 기술하는 데 사용되어진다.
메쏘드 호출에 대한 결과를 전송하기 위해서 역시 SOAP Envelope이 사용된다. 이러한 결과는 크게 성공적인 실행 결과의 반환 혹은 실행 오류에 대한 내용이 될 것이다. 아래 리스트 5는 성공적인 실행 결과를 반환하는 SOAP Envelope의 예이다.
-------------------------------------------------------------------
<env:Envelope xmlns:env="http://www.w3.org/2001/06/soap-envelope" >
<env:Header>
<t:Transaction xmlns:t="http://example.org/2001/06/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xsi:type="xs:int"
env:encodingStyle="http://www.w3.org/2001/06/soap-encoding"
env:mustUnderstand="1" >
5
</t:Transaction>
</env:Header>
<env:Body>
<m:GetLastTradePriceResponse
env:encodingStyle="http://www.w3.org/2001/06/soap-encoding"
xmlns:m="http://example.org/2001/06/quotes" >
<Price>34.5</Price>
</m:GetLastTradePriceResponse>
</env:Body>
</env:Envelope>
-------------------------------------------------------------------
리스트 5. 메쏘드 실행 Request에 대한 결과 값 반환
메쏘드 호출 실패의 경우는 크게 HTTP Request 처리의 실패와 메쏘드 실행 시 발생하는 어플리케이션 오류가 있을 수 있다. 전자의 경우 HTTP 에러 코드가 반환되어 질 것이며 후자의 경우는 SOAP Fault가 반환되어진다.
사실 개발자가 SOAP에 대해 자세한 스팩을 세세하게 알 필요는 없을 것이다. 점점 더 개발자들은 자신의 언어와 플랫폼으로 프로그램을 작성하고 실제 SOAP 프로토콜로 투명하게 매핑되는 환경에서 작업하게 될 것이 분명하다. 예를 들어 .NET Framework를 사용하는 개발자라면 ASP.NET WebService 혹은 .NET Remoting 서비스를 이용해서 부가적인 지식 없이 WebService 어플리케이션을 작성하게 될 것이다. 그러나 어플리케이션의 설계 시 SOAP 프로토콜의 기능과 제약 사항을 이해하는 것이 매우 중요하며, SOAP을 이용한 분산 어플리케이션의 디버깅 시 이 SOAP에 대한 이해가 필요하다. 네트워크 모니터링 툴을 이용하여 분산 어플리케이션 간에 발생하는 SOAP payload를 조사할 수 있으므로 관심 있는 독자들은 시도해보기 바란다.
WSDL (Web Service Description Language)
SOAP이 실제 메쏘드 호출에 필요한 데이터를 전송한다면, WSDL은 IDL(Interface Definition Language)과 동일한 역할을 한다. WSDL을 이용하여 WebService 제공자는 사용자에게 해당 WebService의 정확한 인터페이스와 사용되는 데이터 타입, 그리고 전송 프로토콜에 대한 상세 정보를 전달 할 수 있다. WSDL은 SDL로 출발하여 현재 1.1버전(http://www.w3.org/TR/wsdl)이 Microsoft사와 IBM사에 의해 작성되어 있으며 역시 주요 벤더들로부터 폭넓은 지지를 받고 있다.
WSDL 문서는 Types, Messages, PortType, Binding, Services에 대한 영역들로 구성되어져 있다. Types의 경우 해당 WebService가 사용하는 데이터 타입에 대해 기술하고 있다. 사용 가능한 타입으로는 XML Schema에서 정의한 기본형, 복합 형, 그리고 배열을 사용할 수 있다. 기본적으로 XML Schema 에서 정의한 데이터 타입을 사용하고 있지만 배열의 경우 SOAP에서 정의한 데이터 타입을 사용하기도 한다. Messages의 경우 실제 SOAP Envelope에 대한 스키마를 정의하고 있는 부분이다. 예를 들어 int foo(int arg); 메쏘드에 대한 호출을 표현하기 위하여 WSDL의 message 요소가 아래와 같이 정의되어 있다면,
-------------------------------------------------------------------
<message name="Simple.foo">
<part name="arg" type="xsd:int"/>
</message>
<message name="Simple.fooResponse">
<part name="result" type="xsd:int"/>
</message>
-------------------------------------------------------------------
이에 해당하는 실제 SOAP Envelope는 아래와 같이 될 것이다.
-------------------------------------------------------------------
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<SOAP-ENV:Envelope
SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Body>
<m:foo xmlns:m="http://tempuri.org/message/">
<arg>5131953</arg>
</m:foo>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<SOAP-ENV:Envelope
SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Body>
<SOAPSDK1:fooResponse xmlns:SOAPSDK1="http://tempuri.org/message/">
<result>5131953</result>
</SOAPSDK1:fooResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
-------------------------------------------------------------------
portType은 위와 같은 SOAP Envelope를 사용하는 실제 메쏘드 시그너처를 기술하고 있다. 즉, portType은 Messages 영역을 참조하게 된다.
-------------------------------------------------------------------
<portType name="fooSamplePortType">
<operation name="foo" parameterOrder="arg " >
<input name="foo1" message="wsdlns:foo1"/>
</operation>
<operation name="foo" parameterOrder="arg " >
<input name="foo2" message="wsdlns:foo2"/>
</operation>
</portType>
-------------------------------------------------------------------
위는 portType 영역이며 foo 메쏘드가 foo1 Message와 foo2 Message을 SOAP Envelope으로 사용한다는 것을 의미한다. 위의 경우 메쏘드 이름이 모두 foo 인데 이는 메쏘드 오버로딩을 의미한다. 즉, 메쏘드 이름은 같다하더라도 사용하는 SOAP Envelope은 다른 것이다.
앞서 설명한 Types, Messages, PortType 영역이 메쏘드 호출 시 필요한 정보를 기술한다면 Binding과 Services 영역은 실제 물리적 수준의 인코딩 방식, 프로토콜 종류, 그리고 서비스를 제공하는 실제 URL을 나타낸다. 그러므로 WebService 제공자로부터 WSDL을 제공 받은 사용자는 해당 서비스에 대한 메쏘드 시그너쳐 뿐 아니라 사용하는 데이터 타입, 그리고 프로토콜, 인코딩 방식 및 서비스를 제공 URL에 대한 모든 정보를 얻을 수 있다. 이는 이후 해당 서비스에 대한 프록시를 자동으로 생성하는 데 사용되어질 수도 있다. 실제 WSDL에 대한 상세한 기술도 개발자는 무시할 수 있다. 왜냐면 이 모든 과정 역시 진정한 WebService 플랫폼이라면 모두 개발자에게 투명하게 처리할 수 있어야 하기 때문이다. 예를 들어 .NET Framework의 경우 WSDL은 아래와 같이 ASP.NET을 제공하는 URL에 WSDL이라는 인자를 줌으로써 자동으로 추출이 가능하다. 즉, 개발자는 자신이 제공하고자 하는 서비스를 .NET Framework에서 동작하는 각종 언어로 기술하고 이에 해당하는 WSDL 파일은 자동으로 추출하는 것이다. 이렇게 추출된 WSDL은 역시 .NET Framework SDK에서 제공하는 wsdl 유틸리티를 이용하여 간단하게 원하는 언어로 작성된 프락시를 생성할 수 있게 한다.
-------------------------------------------------------------------
http://www.webservice.com/Stock.asmx?WSDL
wsdl c:\service\Stock.wsdl /language:cs
-------------------------------------------------------------------
DISCO (WebService Discovery)
WebService Discovery는 WSDL에 대한 위치 지정 서비스라고 할 수 있다. 즉, 해당 서버는 자신 혹은 자신과 관련된 WebService를 기술한 WSDL 파일에 대한 위치 정보를 DISCO파일에 기술할 수 있다. DISCO는 크게 두 가지 형태가 있는데, 동적 DISCO와 수동 DISCO가 그것이다. 수동 DISCO의 경우 필요한 WSDL파일의 URL을 직접 기술하는 데 사용된다.
-------------------------------------------------------------------
<?xml version="1.0" ?>
<disco:discovery xmlns:disco="http://schemas.xmlsoap.org/disco"
xmlns:scl="http://schemas.xmlsoap.org/disco/scl">
<scl:contractRef ref="http://MyWebServer/UserName.asmx?WSDL"/>
</disco:discovery>
-------------------------------------------------------------------
앞서 말한 바와 같이 ASP.NET WebService의 경우 실제 서비스를 제공하는 URL에 WSDL이라는 인자를 사용하여 WSDL을 생성한다고 했다. 그러므로 위의 DISCO 파일은 실제 WSDL의 위치를 지정하고 있다고 할 수 있다.
동적 DISCO의 경우는 해당 웹 어플리케이션 내의 모든 WebService에 대한 WSDL의 위치를 자동으로 찾아주는 데 사용된다.
-------------------------------------------------------------------
<disco:discovery xmlns:disco="http://schemas.xmlsoap.org/disco/">
</disco:discovery>
-------------------------------------------------------------------
동적 DISCO, 및 수동 DISCO는 ASP.NET WebService의 경우 모두 .vsdisco라는 확장자로 기술되어진다.
UDDI (Universal Description, Discovery and Integration)
UDDI(www.uddi.org)는 Microsoft, IBM, Ariba가 추축이 되어서 제안한 WebService 에 대한 디렉토리 서비스며 현재 2.0까지 발표되었다. 물론 Microsoft, SUN, Oracle, IBM같은 주요 벤더들의 폭넓은 지지를 받고 있다. WebService 제공자들은 UDDI를 이용하여 자신이 제공하는 서비스에 대한 정보를 등록하고, 사용자들은 UDDI 서비스를 이용하여 자신이 원하는 WebService를 제공하는 서비스 제공자에 대한 정보를 받게 된다. UDDI 서비스의 핵심은 UDDI Business Registration이라고 할 수 있다. 이것은 WebService 제공자와 제공자가 서비스 중인 WebService에 대한 정보를 기술하고 있는 XML 데이터이다. 이러한 Business Registration은 크게 White Pages, Yellow Pages, Green Pages로 나눌 수 있다. White Pages의 경우 WebService를 제공하고자 하는 사업자의 주소, 전화 번호, 이름과 같은 정보를 포함하고 있다. Yellow Pages의 경우 Universal Standard Products and Services Codes, ISO 3166 Geographic Taxonomy 같은 표준적인 산업 분류법에 따라 제공자들을 분류해 놓았다. 그리고 Green Pages는 실제 WebService를 제공하는 URL 및 WSDL 같은 기술적인 사항을 포함하고 있다.
이러