SERVER-SIDE DEVELOPMENT 1 SOAP

 
MAIN

Web Services

Introduction To The Web Services


Different books and different organizations provide different definitions to Web Services. Some of them are listed here.

  • A web service is any piece of software that makes itself available over the internet and uses a standardized XML messaging system. XML is used to encode all communications to a web service. For example, a client invokes a web service by sending an XML message, then waits for a corresponding XML response. As all communication is in XML, web services are not tied to any one operating system or programming language—Java can talk with Perl; Windows applications can talk with Unix applications.
  • Web services are self-contained, modular, distributed, dynamic applications that can be described, published, located, or invoked over the network to create products, processes, and supply chains. These applications can be local, distributed, or web-based. Web services are built on top of open standards such as TCP/IP, HTTP, Java, HTML, and XML.
  • Web services are XML-based information exchange systems that use the Internet for direct application-to-application interaction. These systems can include programs, objects, messages, or documents.
  • A web service is a collection of open protocols and standards used for exchanging data between applications or systems. Software applications written in various programming languages and running on various platforms can use web services to exchange data over computer networks like the Internet in a manner similar to inter-process communication on a single computer. This interoperability (e.g., between Java and Python, or Windows and Linux applications) is due to the use of open standards.


To summarize, a complete web service is, therefore, any service that −

↪Is available over the Internet or private (intranet) networks

↪Uses a standardized XML messaging system

↪Is not tied to any one operating system or programming language

↪Is self-describing via a common XML grammar

↪Is discoverable via a simple find mechanism

Components of Web Services

The basic web services platform is XML + HTTP. All the standard web services work using the following components −

➧SOAP (Simple Object Access Protocol)

➧UDDI (Universal Description, Discovery and Integration)

➧WSDL (Web Services Description Language)

All these components have been discussed in the Web Services Architecture chapter.

 Web Service Work

A web service enables communication among various applications by using open standards such as HTML, XML, WSDL, and SOAP. A web service takes the help of −

➥XML to tag the data

➥SOAP to transfer a message

➥WSDL to describe the availability of service.

You can build a Java-based web service on Solaris that is accessible from your Visual Basic program that runs on Windows.

You can also use C# to build new web services on Windows that can be invoked from your web application that is based on JavaServer Pages (JSP) and runs on Linux.

Example

Consider a simple account-management and order processing system. The accounting personnel uses a client application built with Visual Basic or JSP to create new accounts and enter new customer orders.

The processing logic for this system is written in Java and resides on a Solaris machine, which also interacts with a database to store information.

The steps to perform this operation are as follows −

➯The client program bundles the account registration information into a SOAP message.

➯This SOAP message is sent to the web service as the body of an HTTP POST request.

➯The web service unpacks the SOAP request and converts it into a command that the application can understand.

➯The application processes the information as required and responds with a new unique account number for that customer.

➯Next, the web service packages the response into another SOAP message, which it sends back to the client program in response to its HTTP request.

➯The client program unpacks the SOAP message to obtain the results of the account registration process.

 Difference between web service and web application

Web Applications


tt


Web applications are defined as being interactive. You're supposed to use a web application in order to perform a function and use some of the web applications features. Lots of web applications don't even have real informative content or data exactly. People are just supposed to use them in order to perform additional tasks, using their features to accomplish something. You use a web application to check your incoming messages, for instance, or play a game.

The browser capabilities involved with web applications are significantly more high-tech, which is one reason why it's usually harder for people to design a web application than a website. Websites are all about getting more data, and web applications are all about doing things. One of your actions is probably going to be getting more information or learning more information, but the web application helped you perform that action. You got the information from a website.

The user interface of a web application is also usually much more complicated than the user interface of a website. Websites might have tags and categories that you need to understand, but you don't have to go through and learn any potentially complicated tasks in order to use websites. Web applications often require step-by-step guides, or you're not going to be able to complete them.

The setup of websites is completely different from web applications in most cases. The rhythm of typing in the address, loading websites, and going back and forth between websites is often absent with web applications.

Web applications, unsurprisingly, are usually harder to design and create than websites. Lots of people have their own websites today, and this was the case even ten years ago. The people who are able to create their own web applications can more easily make money off of them because it takes more work to learn how to code and create a web application.

Web Services




Web service is a technology by which two or more remote web applications interact with each other over network/internet. It can be implemented using Java, .net, PHP etc. Web pages allow people to communicate and collaborate with each other while web services allow programs to communicate and collaborate with each other.

A web service is essentially a collection of open protocols and standards used for exchanging data between applications or systems. Software applications written in various programming languages and running on various platforms can use web services to exchange data over computer networks like the Internet in a manner similar to inter-process communication on a single computer. This interoperability (e.g., between Java and Python, or Windows and Linux applications) is due to the use of open standards (XML, SOAP, HTTP).

All the standard Web Services works using the following components:

  • SOAP (Simple Object Access Protocol)
  • UDDI (Universal Description, Discovery, and Integration)
  • WSDL (Web Services Description Language)

It works somewhat like this:

  • The client program bundles the account registration information into a SOAP message.
  • This SOAP message is sent to the Web Service as the body of an HTTP POST request.
  • The Web Service unpacks the SOAP request and converts it into a command that the application can understand.
  • The application processes the information as required and responds with a new unique account number for that customer.
  • Next, the Web Service packages up the response into another SOAP message, which it sends back to the client program in response to its HTTP request.
  • The client program unpacks the SOAP message to obtain the results of the account registration process.


Web Services Description Language (WSDL)

Web Services Description Language (WSDL) is a format for describing a Web Services interface. It is a way to describe services and how they should be bound to specific network addresses. WSDL has three parts:

Definitions

Definitions are generally expressed in XML and include both data type definitions and message definitions that use the data type definitions. These definitions are usually based upon some agreed upon XML vocabulary. This agreement could be within an organization or between organizations. Vocabularies within an organization could be designed specifically for that organization. They may or may not be based on some industry-wide vocabulary. If data type and message definitions need to be used between organizations, then most likely an industry-wide vocabulary will be used. For more on XML vocabularies, click here. 

XML, however, is not necessarily required for definitions. The OMG Interface Definition Language (IDL), for example, could be used instead of XML. If a different definitional format were used, senders and receivers would need to agree on the format as well as the vocabulary. Nevertheless, over time, XML-based vocabularies and messages are likely to dominate. XML Namespaces are used to ensure uniqueness of the XML element names in the definitions, operations, and service bindings.


Operations

Operations describe actions for the messages supported by a Web service. There are four types of operations:

One-way: Messages sent without a reply required
Request/response: The sender sends a message and the receiver sends a reply.
Solicit-response: A request for a response. (The specific definition for this action is pending.)
Notification: Messages sent to multiple receivers. (The specific definition for this action is pending.)
Operations are grouped into port types. Port types define a set of operations supported by the Web service.


Service bindings


Service bindings connect port types to a port. A port is defined by associating a network address with a port type. A collection of ports defines a service. This binding is commonly created using SOAP, but other forms may be used. These other forms could include CORBA Internet Inter-ORB Protocol (IIOP), DCOM, .NET, Java Message Service (JMS), or WebSphere MQ to name a few.

The following figure shows the relationship between the basic parts of WSDL:


gg

  • WSDL is an XML-based language for describing web services and how to access them.
  • WSDL stands for Web Services Description Language.
  • WSDL was developed jointly by Microsoft and IBM.
  • WSDL is an XML based protocol for information exchange in decentralized and distributed environments.
  • WSDL is the standard format for describing a web service.
  • WSDL definition describes how to access a web service and what operations it will perform.
  • WSDL is a language for describing how to interface with XML-based services.
  • WSDL is an integral part of UDDI, an XML-based worldwide business registry.
  • WSDL is the language that UDDI uses.
  • WSDL is pronounced as 'wiz-dull' and spelled out as 'W-S-D-L'.

WSDL Elements


A WSDL document contains the following elements −

  • Definition − It is the root element of all WSDL documents. It defines the name of the web service, declares multiple namespaces used throughout the remainder of the document, and contains all the service elements described here.

  • Data type − The data types to be used in the messages are in the form of XML schemas.

  • Message − It is an abstract definition of the data, in the form of a message presented either as an entire document or as arguments to be mapped to a method invocation.

  • Operation − It is the abstract definition of the operation for a message, such as naming a method, message queue, or business process, that will accept and process the message.

  • Port type − It is an abstract set of operations mapped to one or more end-points, defining the collection of operations for a binding; the collection of operations, as it is abstract, can be mapped to multiple types of transport through various bindings.

  • Binding − It is the concrete protocol and data formats for the operations and messages defined for a particular port type.

  • Port − It is a combination of a binding and a network address, providing the target address of the service communication.

  • Service − It is a collection of related end-points encompassing the service definitions in the file; the services map the binding to the port and include any extensibility definitions.


In addition to these major elements, the WSDL specification also defines the following utility elements −

➽Documentation − This element is used to provide human-readable documentation and can be included inside any other WSDL element.

➽Import − This element is used to import other WSDL documents or XML Schemas.

NOTE − WSDL parts are usually generated automatically using web services-aware tools.

The WSDL Document Structure

Web Services Description Language (WSDL) is an XML grammar for describing network services as collections of communication endpoints capable of exchanging messages. The diagram below illustrates the elements that are present in a WSDL document and indicates their relationships. To see an example of how this is implemented in a WSDL document, see Example of a WSDL Document.


hj


The main structure of a WSDL document looks like this −

<definitions>
   <types>
      definition of types........
   </types>

   <message>
      definition of a message....
   </message>

   <portType>
      <operation>
         definition of a operation.......  
      </operation>
   </portType>

   <binding>
      definition of a binding...
   </binding>

   <service>
      definition of a service...
   </service>
</definitions>


A WSDL document can also contain other elements, like extension elements and a service element that makes it possible to group together the definitions of several web services in one single WSDL document.

Proceed further to analyze an example of WSDL Document.

Difference between <binding> and <portType> in WSDL


PortType (Analogs to Java interface)

PortType is an abstraction part of WSDL.
An abstract set of operations supported by one or more endpoints.
binding

Binding is a concrete part of WSDL.
Describes how the operation is invoked by specifying a concrete protocol and data format specifications for the operations and messages.
bindings are three types

SOAP Binding:

SOAP binding allows either document or RPC style with either encoding or literal. Encoding indicates how a data value should be encoded in an XML format (These rules specify how "something" is encoded/serialized to XML and then later decoded/de-serialized from XML back to "something"). Literal means that the data is serialized according to a schema (this is just plain XML data). With transportation type HTTP, JMS, SMTP...

HTTP GET & POST binding:
WSDL includes a binding for HTTP 1.1's GET and POST verbs in order to describe the interaction between a Web Browser and a web site.

MIME binding: WSDL includes a way to bind abstract types to concrete messages in some MIME format.

SOAP 

Introduction

In today's world, there is a huge number of applications which are built on different programming languages. For example, there could be a web application designed in Java, another in.Net and another in PHP.

Exchanging data between applications is crucial in today's networked world. But data exchange between these heterogeneous applications would be complex. So will be the complexity of the code to accomplish this data exchange.

One of the methods used to combat this complexity is to use XML (Extensible Markup Language) as the intermediate language for exchanging data between applications.

Every programming language can understand the XML markup language. Hence, XML was used as the underlying medium for data exchange.

But there are no standard specifications on use of XML across all programming languages for data exchange. That is where SOAP comes in.

SOAP was designed to work with XML over HTTP and have some sort of specification which could be used across all applications. We will look into further details on the SOAP protocol in the subsequent chapters.

Advantages of SOAP

SOAP is the protocol used for data interchange between applications. Below are some of the reasons as to why SOAP is used.

  • When developing Web services, you need to have some of the languages which can be used for web services to talk with client applications. SOAP is the perfect medium which was developed in order to achieve this purpose. This protocol is also recommended by the W3C consortium which is the governing body for all web standards.
  • SOAP is a light-weight protocol that is used for data interchange between applications. Note the keyword 'light.' Since SOAP is based on the XML language, which itself is a lightweight data-interchange language, hence SOAP as a protocol that also falls in the same category.
  • SOAP is designed to be platform independent and is also designed to be operating system independent. So the SOAP protocol can work any programming language based applications on both Windows and Linux platform.
  • It works on the HTTP protocol –SOAP works on the HTTP protocol, which is the default protocol used by all web applications. Hence, there is no sort of customization which is required to run the web services built on the SOAP protocol to work on the World Wide Web.

SOAP Communication Model.

All communication by SOAP is done via the HTTP protocol. Prior to SOAP, a lot of web services used the standard RPC (Remote Procedure Call) style for communication. This was the simplest type of communication, but it had a lot of limitations.

Let's consider the below diagram to see how this communication works. In this example, let's assume the server hosts a web service which provided 2 methods as

🟂GetEmployee - This would get all Employee details
🟂SetEmployee – This would set the value of the details like employees dept, salary, etc. accordingly.

In the normal RPC style communication, the client would just call the methods in its request and send the required parameters to the server, and the server would then send the desired response.

GHJ


The above communication model has the below serious limitations

🟊Not Language Independent – The server hosting the methods would be in a particular programming language and normally the calls to the server would be in that programming language only.

🟊Not the standard protocol – When a call is made to the remote procedure, the call is not carried out via the standard protocol. This was an issue since mostly all communication over the web had to be done via the HTTP protocol.

🟊Firewalls – Since RPC calls do not go via the normal protocol, separate ports need to be open on the server to allow the client to communicate with the server. Normally all firewalls would block this sort of traffic, and a lot of configuration was generally required to ensure that this sort of communication between the client and the server would work.

To overcome all of the limitations cited above, SOAP would then use the below communication model

DFG


  1. The client would format the information regarding the procedure call and any arguments into a SOAP message and sends it to the server as part of an HTTP request. This process of encapsulating the data into a SOAP message was known as Marshalling.
  2. The server would then unwrap the message sent by the client, see what the client requested for and then send the appropriate response back to the client as a SOAP message. The practice of unwrapping a request sent by the client is known as demarshalling.

SOAP Message Structure

One thing to note is that SOAP messages are normally auto-generated by the web service when it is called.

Whenever a client application calls a method in the web service, the web service will automatically generate a SOAP message which will have the necessary details of the data which will be sent from the web service to the client application.

As discussed in the previous topic, a simple SOAP Message has the following elements –

  • The Envelope element
  • The header element and
  • The body element
  • The Fault element (Optional)
Let's look at an example below of a simple SOAP message and see what element actually does.

IMA78


  1. As seen from the above SOAP message, the first part of the SOAP message is the envelope element which is used to encapsulate the entire SOAP message.
  2. The next element is the SOAP body which contains the details of the actual message.
  3. Our message contains a web service which has the name of "Guru99WebService".
  4. The "Guru99Webservice" accepts a parameter of the type 'int' and has the name of TutorialID.

Now, the above SOAP message will be passed between the web service and the client application.

You can see how useful the above information is to the client application. The SOAP message tells the client application what is the name of the Web service, and also what parameters it expects and also what is the type of each parameter which is taken by the web service.

SOAP Envelope Element

The first bit of the building block is the SOAP Envelope.

The SOAP Envelope is used to encapsulate all of the necessary details of the SOAP messages, which are exchanged between the web service and the client application.

The SOAP envelope element is used to indicate the beginning and end of a SOAP message. This enables the client application which calls the web service to know when the SOAP message ends.

The following points can be noted on the SOAP envelope element.

  • Every SOAP message needs to have a root Envelope element. It is absolutely mandatory for a SOAP message to have an envelope element.
  • Every Envelope element needs to have at least one soap body element.
  • If an Envelope element contains a header element, it must contain no more than one, and it must appear as the first child of the Envelope, before the body element.
  • The envelope changes when SOAP versions change.
  • A v1.1-compliant SOAP processor generates a fault upon receiving a message containing the v1.2 envelope namespace.
  • A v1.2-compliant SOAP processor generates a Version Mismatch fault if it receives a message that does not include the v1.2 envelope namespace.
Below is an example of version 1.2 of the SOAP envelope element.

<?xml version="1.0"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://www.w3.org/2001/12/soap-envelope" SOAP-ENV:encodingStyle=" http://www.w3.org/2001/12/soap-encoding">
          <soap:Body>
        <Guru99WebService xmlns="http://tempuri.org/">
                  <TutorialID>int</TutorialID>
                </Guru99WebService>
          </soap:Body>
</SOAP-ENV:Envelope>

The Fault message


When a request is made to a SOAP web service, the response returned can be of either 2 forms which are a successful response or an error response. When success is generated, the response from the server will always be a SOAP message. But if SOAP faults are generated, they are returned as "HTTP 500" errors.

The SOAP Fault message consists of the following elements.

⧪<faultCode>- This is the code that designates the code of the error. The fault code can be either of any below values
  • SOAP-ENV: VersionMismatch – This is when an invalid namespace for the SOAP Envelope element is encountered.
  • SOAP-ENV: MustUnderstand - An immediate child element of the Header element, with the mustUnderstand attribute set to "1", was not understood.
  • SOAP-ENV: Client - The message was incorrectly formed or contained incorrect information.
  • SOAP-ENV: Server - There was a problem with the server so the message could not proceed.
⧪<faultString> - This is the text message which gives a detailed description of the error.
⧪<faultActor> (Optional)- This is a text string which indicates who caused the fault.
⧪<detail>(Optional) - This is the element for application-specific error messages. So the application could have a specific error message for different business logic scenarios.

Example for Fault Message


An example of a fault message is given below. The error is generated if the scenario wherein the client tries to use a method called TutorialID in the class tutorial.

The below fault message gets generated in the event that the method does not exist in the defined class.

<?xml version='1.0' encoding='UTF-8'?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance" xmlns:xsd="http://www.w3.org/1999/XMLSchema">
      <SOAP-ENV:Body>
         <SOAP-ENV:Fault>
         <faultcode xsi:type="xsd:string">SOAP-ENV:Client</faultcode>
        <faultstring xsi:type="xsd:string">
            Failed to locate method (GetTutorialID) in class (GetTutorial)
         </faultstring>
    </SOAP-ENV:Fault>
   </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

Output:

When you execute the above code, it will show the error like "Failed to locate method (GetTutorialID) in class (GetTutorial)"

SOAP Messages with Attachments


  • Organizations are being challenged to partner with other organizations in order to respond more rapidly to new business opportunities, increase the efficiency of business processes, and reduce the time to market for their products. To address these issues, they're typically required to develop interoperability between disparate, legacy applications to support collaborative business processes.

  • This is accomplished by coordinating the exchange of business documents between applications in a predefined manner. For example, two insurance companies with different systems may need to exchange auto insurance claim data, such as a TIFF file for claims processing.

  • Enterprise applications that support these types of requirements are known as business services. Supporting business services through Web applications, commonly known as Web services, requires a careful evaluation of available technologies. An important underlying technology of Web services is Simple Object Access Protocol. SOAP enables applications to communicate with each other in a platform, language, and operating system-independent manner.

  • For those who need to use a Web service to perform a functionality such as sending a document in the form of attachments (e.g., a TIFF file) from one application to another using SOAP, a pertinent specification is the SOAP Messages with Attachments note. This article discusses this emerging W3C note and illustrates how it can be used with the Apache SOAP implementation.

SOAP Messages with Attachments Specification

  • As you know, SOAP is a simple, lightweight XML-based distributed computing protocol. The SOAP 1.1 specification essentially comprises three parts:

➥A framework for describing the contents of a SOAP message and how it's processed
➥An encoding standard for objects sent over SOAP
➥A mechanism for representing remote procedure calls (RPC) using SOAP.
  • A SOAP message is an XML document that comprises a SOAP envelope. Within the envelope are an optional SOAP header and a mandatory SOAP body. The SOAP message header represents the metadata of the message and provides a way to extend SOAP. The SOAP message body is the actual message payload. The details of a remote procedure call including the arguments are described in the envelope that is transported from one application to another over a selected protocol (e.g., HTTP). HTTP provides a firewall-friendly application-level protocol for communication between heterogeneous applications. The SOAP Messages with Attachments specification builds on SOAP 1.1.
  • Before we discuss this specification, we should briefly consider the concept of a Multipurpose Internet Mail Extensions multipart. MIME is leveraged in the SOAP with Attachments specification as well as in other related Web services specifications such as WSDL (Web Services Description Language). Typically, e-mail messages with attachments are sent over the Internet using Simple Mail Transfer Protocol and MIME. SMTP is limited to 7-bit ASCII text with a maximum line length of a thousand characters which results in the inability to send attachments. MIME addresses these limitations by specifying message header fields and allowing different related objects such as attachments to be included in the message body in the form of a MIME multipart.
  • For example, if the message body contains multiple independent objects of possibly different data types, the message body is divided into parts by boundaries. To indicate that the message body comprises a multipart structure of independent attachments, a Content-Type message header field is set. The message body boundary is defined with a parameter in the Content-Type field as shown below:

Content-Type: multipart/mixed;boundary="1995021309105517"
  • The Content-Type header can also be used to identify a Multipart structure with related MIME parts. RFC 2387 specifies the Multipart/Related Content-Type to provide a mechanism for representing an object that consists of related MIME body parts. As you'll see, the Multipart/Related Content-Type allows a SOAP message to reference attachments such as audio and image files.
  • Armed with this basic knowledge of SOAP and MIME, let's discuss the concept of SOAP messages with attachments. Let's assume we use the MIME specifications to support SOAP messages with attachments and we package a SOAP 1.1 message as a part of a MIME multipart structure. Further, let's assume we provide a way for that SOAP 1.1 message to refer to attachments that are represented as other parts of that MIME multipart. In a nutshell, this is the approach described in the SOAP Messages with Attachments technical note.
  • This note specifies how to package a SOAP 1.1 message with attachments using existing MIME specifications. A SOAP Message Package, which is a central concept in this specification, consists of a SOAP 1.1 message that can reference attachments and any related attachments. A SOAP message package is built using the Multipart/Related Content-Type. The primary SOAP 1.1 message must be included in the root body part of the Multipart/Related container. Thus the type header of the Multipart container and the Content-Type header of the root body part will be the same (i.e., text/XML). The attachments in the Multipart container must be composed of a Content-ID MIME header or a Content-Location MIME header.
  • For the SOAP message to reference attachments in the MIME container, the SOAP 1.1 encoding rules are used. In the specification, a URI that is a value of an HREF attribute can be used to refer to a resource. Since each attachment in the MIME container has a URI reference in its Content-Location or Content-ID header, it's possible for the attachments to be referred to using the HREF attribute from the SOAP 1.1 message. To refer to an attachment with a specific Content-ID header value, the Content-ID Uniform Resource Locator scheme, "cid," is used, as defined in RFC 2111. So, for example, to refer to a MIME part (GIF image) with a Content-ID of 286.apache-soap.MYHOST, an HREF value of "cid:286.apache-soap. MYHOST" is used. An illustration of a SOAP message package with an image attachment constructed using a MIME multipart is shown in Figure 1.

Apache SOAP Implementation of SOAP Messages with Attachments

  • The Apache Software Foundation (www.apache.org) provides an implementation of SOAP including support for SOAP Messages with Attachments. I've chosen to discuss the Apache implementation because it's freely available. Apache SOAP version 2.2, which can be downloaded from the Apache Web site, requires a number of components, such as a servlet container (e.g., Apache Tomcat), JavaMail, JavaBeans Activation Framework, and a JAXP-compatible XML parser. As you know, JavaMail is a J2EE API that provides a platform and protocol-independent interface for sending and retrieving e-mail messages. It interacts with the message content through another layer in the form of the JavaBeans Activation Framework. JAF provides a uniform way of determining the type of a message's content and encapsulating access to it. You can obtain more information on JavaMail and JAF from the Resources section.
  • Here's a quick overview of how a simple Web service can be constructed with Apache SOAP and Java. The first step is to define and implement a Web service. When developing a simple Java application to support a Web service using SOAP, you'll notice that there's no SOAP-specific code in your Java class because Apache SOAP manages the details pertaining to SOAP. After implementing the service, you deploy the service describing the operation(s) that it supports and assign the service a unique service ID. When a SOAP client uses the service by calling one of its operations, the Apache SOAP RPC router servlet responds to the request. The request is routed to the pertinent Java object that supports the Web service. The service object interfaces with the core business logic to perform the business function and a response is returned to the client.
  • After deploying a Web service, you could create a Java client that calls the Web service. The client program uses a Call object to specify values such as the service ID, method name, and parameters of the method such as attachments. The invoke() operation of the Call object requires the URI of the rpc router servlet and returns a Response object. The response is also a SOAP message. If an error occurs during the invocation of the method, a Fault object can be returned within the SOAP message body. The Fault object includes a code and a description of the error.
  • The SOAPMappingRegistry class handles the marshaling and unmarshaling of data types and comes with preregistered serializers and deserializers such as the MimePartSerializer class. This and other classes and interfaces you might encounter using the Apache SOAP Messages with Attachments implementation are summarized in Table 1.

Example

  • To provide a simple, concrete illustration of the previous discussion, let's assume we have a subscriber who uses systems provided by messaging system vendors A and B. Suppose, using A's system, a subscriber needs to change his/her voicemail greeting on B's system. This need can be met by a Web service using SOAP provided by vendor B. So, vendor A develops a Web application that accesses vendor B's Web service using SOAP to change the voicemail greeting of a subscriber.
  • To support this scenario, two simple Java programs will be used to illustrate the SOAP RPC approach rather than the message-based approach. The first program will implement the Web service; the second will be a test client to call the service. The class to support the Web service consists of one operation, changeGreeting(), with two parameters - a subscriber ID and a voice greeting in the form of a WAV file attachment. The attachment is obtained using a DataHandler object and written to disk for this example. Vendor B's existing business objects could then use this audio file to actually change the greeting. Notice how the Web service can simply provide a coarse-grained service-based interface that shields the calling application from an organization's existing business-logic-layer implementation (Java classes, CORBA objects, EJBs) that is reused to support the Web service. A code snippet of the class that implements this Web service is given in Listing 1.
  • To deploy the code, a deployment descriptor is needed to specify the URN of the SOAP service ("urn:soapattachtest") and operations (changeGreeting) that SOAP clients can use. The Java class (GreetingService) that supports the Web service is also specified in the deployment descriptor provided in Listing 2.
  • The other program involved in this example is a client program that calls the Web service. In this SOAP client, a Call object is created and initialized with the serviceID and the name of the operation (changeGreeting), both of which must match the values in the deployment descriptor. The Call object is also initialized with two parameters needed for the changeGreeting() operation - the subscriber ID and a voice greeting attachment file. After the Call object is initialized, the URL representing the rcprouter servlet is passed into its invoke() operation to call the Web service and send the attachment. Listing 3 gives a code snippet of this class. The code listings shown can be deployed on Apache Tomcat and SOAP 2.2.
  • The Apache SOAP implementation also includes a useful utility called TcpTunnelGui that allows you to "sniff" SOAP messages exchanged between a SOAP client and a SOAP server. For example, assuming you're using Apache Tomcat, a SOAP client can connect to port 8070 to send SOAP requests that are then routed to port 8080 (Apache Tomcat's default port) on your Web server's host. As you can see in Figure 2, this tool is helpful for learning about the contents of SOAP requests and responses as they pertain to the SOAP Messages with Attachments specification.


Great Web Service Testing Tools


  • Over the last few years, the popularity and usage of web services or APIs have increased. Web services or APIs are a collection of procedures or software components that help an application to interact or perform some process/transaction by forming a connection between other application or server. There are basically two types of web service – REST and SOAP to drive the communication of data and information over internet protocol.

  • Since these web services are exposed to the web and distributed over different networks, they are vulnerable to risks and security threats which affect the processes based on them. Hence, testing of web services or APIs becomes necessary to ensure they perform rightly and respond correctly to the queries.
HJKL

  • There are several commercial and open source testing tools in the market to test their connectivity, response, and performance. These testing tools automate testing for a specific scenario such as functional testing, load testing, performance testing, etc. Below tools are not in any specific order.

SoapUI

SoapUI is an open source, cross-platform testing tool. It can automate functional, regression, compliance, and load testing of both SOAP and REST web services. It comes with an easy-to-use graphical interface and supports industry-leading technologies and standards to mock and stimulate the behavior of web services.


Key Features

  • Provides printable, exportable, and HTML-based reports at Project, TestSuite, TestCase, or LoadTest level.
  • Comes integrated with Hudson, Bamboo, Maven, ANT, and JUnit.
  • Allows developing own set of features as SoapUI Plugins.
  • Records, monitors, and displays all the data.
  • Supports WS-Security and SSL decryption.

TestingWhiz


TestingWhiz is a codeless test automation tool which comes with API/web services testing capability. It lets you perform functional, compliance, load testing and mocking of REST and SOAP web services via WSDL interface over HTTP and FTP. It also let’s perform service denial and penetration checks to ensure the overall health of the web services. Plus, it also lets you perform end-to-end testing right from Web UI, business logic, to database and ETL without coding needs.

  • Supports String comparison to validate the API response.
  • Helps log API defects through integrated bug tracking tools like JIRA, Mantis, and FogBugz.
  • Generates visual logs and reports of test execution with an emailing facility.
  • Allows distributed and parallel execution across multiple machines and nodes.
  • Provide Continuous Integration with Jenkins, Bamboo & Hudson.
  • Supports data-driven and keyword-driven testing.

SOAPSonar

SOAPSonar provides comprehensive web services testing for HTML, XML, SOAP, REST, and JSON. It provides functional, performance, compliance, interoperability and security testing with out-of-the-box support for OASIS and W3C standards.

  • Supports vulnerability tests with XSD-mutation.
  • Provides comprehensive WSDL and Schema parsing.
  • Performs load testing with behavior modeling and multiple simultaneous loading transactions.
  • Provides reports in XML, DOC, XLS, PDF, RTF, and RPT formats.
  • Integrates with HP Quality Center.

SOAtest

SOAtest is an enterprise-grade tool by Parasoft for testing and validating APIs and API-driven apps. It provides robust support for the functional unit, integration, security, simulation, mocking, compliance and load testing of technologies like REST, JSON, MQ, JMS, TIBCO, HTTP, and XML.

  • Provides end-to-end testing
  • Supports 120+ protocols/message types.
  • Comes with an easy-to-use interface.
  • Helps create sophisticated, extensible and reusable tests without coding.
  • Supports continuous integration testing.

TestMaker

TestMaker is an open source tool to test and monitor the performance of the web, web services and SOA application by PushtoTest. It runs on Jython (Python is written in Java). TestMaker can repurpose Selenium tests, SoapUI tests, Sahi tests or any tests written in Groovy, Java, Python, PHP, Ruby, and Perl into functional, load and performance tests.

  • Uses command-line prompt for functional, load and performance testing.
  • Features an intuitive look and feel with a standard multi-windowed IDE.
  • Provides a monitoring dashboard to run tests and display live results.
  • Allows accessing all Java libraries and classes due to Jython language.

Postman

Postman is yet another API/ web services testing tool which comes with powerful HTTP client support. It has an easy-to-use request builder that allows you to write test cases and manage response data and response time for efficient testing and management of API test cases.

  • Allows collecting and organizing APIs in a feature called Postman Collections.
  • Facilitates collaboration and sharing of API data and controls with the team.
  • Comes with pasting text feature for hassle-free test creation on command line window.
  • Allows writing Boolean tests within Postman Interface.

vRest

vRest is a tool exclusive for testing, mocking, and validation of REST APIS and web services. It also supports testing of web, mobile, and desktop applications that interact with third-party APIs or HTTP services.

  • Comes with a mock server functionality to create API mock within minutes.
  • Provides a Chrome extension to record and playtest cases.
  • Supports integration with Jenkins for continuous server integration and Jira for bug tracking.
  • Facilitates roles and permissions management.
  • Allows exporting and importing test cases and reports from external tools such as Postman Collections, Swagger 2, and more

HttpMaster

HttpMaster is another exclusive tool for REST web services testing. It helps testers to test the behavior of REST APIs and validate output data in formats like XML, JSON, and HTML.  With its universal HTTP tool, HttpMaster also helps the developer simulate client activity and response behavior of an API application.

  • Comes with an easy-to-use and elegant user interface that doesn’t require advanced technical skills.
  • Uses HTTP methods such as GET, POST, DELETE etc.
  • Provides different validation types and expressions to ease testing.
  • Utilizes command-line interface for test creation and execution
  • Allows storing all information – API calls and project data at a single place.

Runscope

Runscope is a simple tool to test and monitor the performance of the API. It helps you verify whether the web service or API returns the correct data and also prompts when things go wrong with the API. Runscope also supports API and backend service testing of mobile apps.

  • Allows creating tests with dynamic data for even complex cases.
  • Displays visually-rich metrics and analytics to identify problems.
  • Integrates with tools like HipChat, Webhooks, Slack, and PagerDuty to notify when the APIs are down.
  • Allows reusing and executing tests across multiple locations.
  • Facilitates managing tests centrally for better team collaboration.

Rapise

Rapise is a robust automation tool with powerful and extensible features. It is based on an open and flexible architecture for rapid functional testing of REST/SOAP web services. Rapise also provides support for testing web applications built in Java, .NET, Ajax, Silverlight, and Flash.

  • Uses HTTP standard methods such as POST, GET, PUT, and DELETE.
  • Allows storing prototyped requests against a specific web service.
  • Contains built-in REST definition builder and object library.
  • Comes with powerful, integrated reporting capabilities.
  • Supports cross-browser testing and parallel execution.

WebInject

WebInject is a free tool for automated functional, acceptance, and regression testing of web and web services. It is a command-line tool and is based on Perl, which simplifies the execution of tests since it doesn’t require one to spend time at the command prompt. Further, it has no IDE like user interface which means, the tests are written outside of the WebInject UI. It can run on platforms that have Perl interpreter.


  • Provides real-time results display.
  • Monitors system response time.
  • Supports different usage – as a complete test framework and as a standalone test runner.
  • Generates reports in HTML and XML formats.
  • Allows integration with other systems as a plugin for external monitoring.

Storm

Lastly, Storm is another open source tool by CodePlex for testing web services written in Java or .NET. It currently supports only SOAP web service.

  • Allows testing multiple web services from a single UI.
  • Helps edit raw SOAP requests.
  • Allows invoking web service methods that contain complex data types.
  • Supports testing of WCF apps.

JAX-WS Annotations

@WebService

This JAX-WS annotation can be used in 2 ways. If we are annotating this over a class, it means that we are trying to mark the class as implementing the Web Service, in other words, Service Implementation Bean (SIB). Or we are marking this over an interface, it means that we are defining a Web Service Interface (SEI), in other words, Service Endpoint Interface.

Now let's see the java program demonstrating both of the mentioned ways:

WSAnnotationWebServiceI.java

package com.javacodegeeks.examples.jaxWsAnnotations.webservice;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;
@WebService
@SOAPBinding(style=Style.RPC)
public interface WSAnnotationWebServiceI {
    @WebMethod
    float celsiusToFarhenheit(float celsius);
}

In the above program, we can see that we haven’t provided any optional element along with the @WebService annotation. And here it is used to define SEI. Regarding the other annotations used in the above program, we shall see their description a little ahead.

WsAnnotationsWebServiceImpl.java


package com.javacodegeeks.examples.jaxWsAnnotations.webservice;
import javax.jws.WebService;
@WebService(endpointInterface="com.javacodegeeks.examples.jaxWsAnnotations.webservice.WSAnnotationWebServiceI")
public class WsAnnotationsWebServiceImpl implements WSAnnotationWebServiceI {
    @Override
    public float celsiusToFarhenheit(float celsius) {
        return ((celsius - 32)*5)/9;
    }
}

In the above program, we can see that we have provided an optional element endpointInterface along with the @WebService annotation. And here it is used to define SIB. endpointInterface optional element describes the SEI that the said SIB is implementing.

While implementing a web service as in the above example, it is not mandatory for WsAnnotationsWebServiceImpl to implement WSAnnotationWebServiceI, this just serves as a check. Also, it is not mandatory to use an SEI, however, as a basic design principle “We should program to an interface”, hence we have adopted this methodology in the above program.

Other optional elements to @WebService can be like wsdlLocation that defines the location of pre-defined WSDL defining the web service, the name that defines the name of the web service etc.

@SOAPBinding

Demonstration of @SOAPBinding JAX-WS annotation has already been shown in the first program in 1.1. This annotation is used to specify the SOAP messaging style which can either be RPC or DOCUMENT. This style represents the encoding style of the message sent to and fro while using the web service.

With RPC style a web service is capable of only using simple data types like integer or string. However, DOCUMENT style is capable of richer data types for a class let’s say, Person, which can have attributes like String name, Address address etc.

Document style indicates that in the underlying web service, the underlying message shall contain full XML documents, whereas, in the RPC style, the underlying message contains parameters and return values in request and response message respectively. By default the style is Document.

The other important optional attribute is used. It represents the formatting style of the web service message. Its value can either be literal or encoded.

Example usage of @SOAPBinding:

@SOAPBinding(style=Style.DOCUMENT, use=Use.LITERAL)

 @WebMethod

@WebMethod JAX-WS annotation can be applied over a method only. This specified that the method represents a web service operation. For its demonstration, please refer to first program in 1.1.

 @WebResult

To understand this JAX-WS annotation, let’s write SEI & SIB again:

WSAnnotationsWebResultI.java

package com.javacodegeeks.examples.jaxWsAnnotations.webresult;
import javax.jws.WebMethod;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;
@WebService
@SOAPBinding(style = Style.RPC)
public interface WSAnnotationsWebResultI {
    @WebMethod
    @WebResult(partName="farhenheitResponse")
    float celsiusToFarhenheit(float celsius);
}

WSAnnotationsWebResultImpl.java

package com.javacodegeeks.examples.jaxWsAnnotations.webresult;
import javax.jws.WebService;
@WebService(endpointInterface="com.javacodegeeks.examples.jaxWsAnnotations.webresult.WSAnnotationsWebResultI")
public class WSAnnotationsWebResultImpl implements WSAnnotationsWebResultI {
    @Override
    public float celsiusToFarhenheit(float celsius) {
        return ((celsius - 32)*5)/9;
    }
}

Now let’s publish this endpoint:

WSPublisher.java

package com.javacodegeeks.examples.jaxWsAnnotations.webresult;
import javax.xml.ws.Endpoint;
public class WSPublisher {
    public static void main(String[] args) {
        Endpoint.publish("http://127.0.0.1:9999/ctf", new WSAnnotationsWebResultImpl());
    }
}

On publishing the generated WSDL (at URL: http://127.0.0.1:9999/ctf?wsdl) would be like:


<definitions
    xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
    xmlns:wsp="http://www.w3.org/ns/ws-policy" xmlns:wsp1_2="http://schemas.xmlsoap.org/ws/2004/09/policy"
    xmlns:wsam="http://www.w3.org/2007/05/addressing/metadata" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
    xmlns:tns="http://webresult.jaxWsAnnotations.examples.javacodegeeks.com/"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.xmlsoap.org/wsdl/"
    targetNamespace="http://webresult.jaxWsAnnotations.examples.javacodegeeks.com/"
    name="WSAnnotationsWebResultImplService">
    <types />
    <message name="celsiusToFarhenheit">
        <part name="arg0" type="xsd:float" />
    </message>
    <message name="celsiusToFarhenheitResponse">
        <part name="farhenheitResponse" type="xsd:float" />
    </message>
    <portType name="WSAnnotationsWebResultI">
        <operation name="celsiusToFarhenheit">
            <input
               wsam:Action="http://webresult.jaxWsAnnotations.examples.javacodegeeks.com/WSAnnotationsWebResultI/celsiusToFarhenheitRequest"
                message="tns:celsiusToFarhenheit" />
            <output
                wsam:Action="http://webresult.jaxWsAnnotations.examples.javacodegeeks.com/WSAnnotationsWebResultI/celsiusToFarhenheitResponse"
                message="tns:celsiusToFarhenheitResponse" />
        </operation>
    </portType>
    <binding name="WSAnnotationsWebResultImplPortBinding" type="tns:WSAnnotationsWebResultI">
        <soap:binding transport="http://schemas.xmlsoap.org/soap/http"
            style="rpc" />
        <operation name="celsiusToFarhenheit">
            <soap:operation soapAction="" />
            <input>
                <soap:body use="literal"
                    namespace="http://webresult.jaxWsAnnotations.examples.javacodegeeks.com/" />
            </input>
            <output>
                <soap:body use="literal"
                    namespace="http://webresult.jaxWsAnnotations.examples.javacodegeeks.com/" />
            </output>
        </operation>
    </binding>
    <service name="WSAnnotationsWebResultImplService">
        <port name="WSAnnotationsWebResultImplPort" binding="tns:WSAnnotationsWebResultImplPortBinding">
            <soap:address location="http://127.0.0.1:9999/ctf" />
        </port>
    </service>
</definitions>

Refer to the highlighted line in above wsdl, the part name has been changed to “farhenheitResponse” as was defined using @WebResult. What interest here is that @WebResult can be used to determine what the generated WSDL shall look like.

If we comment out the @WebResult, the WSDL (at URL: http://127.0.0.1:9999/ctf?wsdl) shall be like:


<definitions
    xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
    xmlns:wsp="http://www.w3.org/ns/ws-policy" xmlns:wsp1_2="http://schemas.xmlsoap.org/ws/2004/09/policy"
    xmlns:wsam="http://www.w3.org/2007/05/addressing/metadata" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
    xmlns:tns="http://webresult.jaxWsAnnotations.examples.javacodegeeks.com/"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.xmlsoap.org/wsdl/"
    targetNamespace="http://webresult.jaxWsAnnotations.examples.javacodegeeks.com/"
    name="WSAnnotationsWebResultImplService">
    <types />
    <message name="celsiusToFarhenheit">
        <part name="arg0" type="xsd:float" />
    </message>
    <message name="celsiusToFarhenheitResponse">
        <part name="return" type="xsd:float" />
    </message>
    <portType name="WSAnnotationsWebResultI">
        <operation name="celsiusToFarhenheit">
            <input
                wsam:Action="http://webresult.jaxWsAnnotations.examples.javacodegeeks.com/WSAnnotationsWebResultI/celsiusToFarhenheitRequest"
                message="tns:celsiusToFarhenheit" />
            <output
                wsam:Action="http://webresult.jaxWsAnnotations.examples.javacodegeeks.com/WSAnnotationsWebResultI/celsiusToFarhenheitResponse"
                message="tns:celsiusToFarhenheitResponse" />
        </operation>
    </portType>
    <binding name="WSAnnotationsWebResultImplPortBinding" type="tns:WSAnnotationsWebResultI">
        <soap:binding transport="http://schemas.xmlsoap.org/soap/http"
            style="rpc" />
        <operation name="celsiusToFarhenheit">
            <soap:operation soapAction="" />
            <input>
                <soap:body use="literal"
                    namespace="http://webresult.jaxWsAnnotations.examples.javacodegeeks.com/" />
            </input>
            <output>
                <soap:body use="literal"
                    namespace="http://webresult.jaxWsAnnotations.examples.javacodegeeks.com/" />
            </output>
        </operation>
    </binding>
    <service name="WSAnnotationsWebResultImplService">
        <port name="WSAnnotationsWebResultImplPort" binding="tns:WSAnnotationsWebResultImplPortBinding">
            <soap:address location="http://127.0.0.1:9999/ctf" />
        </port>
    </service>
</definitions>
In the above program, part name has value return.

Other elements of @WebResult are WebParam.The mode that defines the direction in which parameter is flowing, targetNamespace to define XML namespace for the parameter.

 @WebServiceClient

To understand @WebServiceClient JAX-WS annotation, let us first publish the endpoint written in 1.1 using the below program:

WSPublisher.java

package com.javacodegeeks.examples.jaxWsAnnotations.webservice;
import javax.xml.ws.Endpoint;
public class WSPublisher {
    public static void main(String[] args) {
        Endpoint.publish("http://127.0.0.1:9999/ctf", new WsAnnotationsWebServiceImpl());
    }
}

Before moving further we should understand wsimport utility provided by Java that eases the task of writing client for a SOAP-based web service. We won’t go into much detail here about wsimport, instead, let’s first save the WSDL file with name ‘ctf.wsdl’ and then write following command on the command prompt:

wsimport -keep -p client ctf.wsdl

The generated code shall have the following classes generated:
Now let’s open WsAnnotationsWebServiceImplService.java. It shall be like:

WsAnnotationsWebServiceImplService.java


package client;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import javax.xml.ws.WebEndpoint;
import javax.xml.ws.WebServiceClient;
import javax.xml.ws.WebServiceException;
import javax.xml.ws.WebServiceFeature;

/**
 * This class was generated by the JAX-WS RI. JAX-WS RI 2.2.9-b130926.1035
 * Generated source version: 2.2
 * 
 */

@WebServiceClient(name = "WsAnnotationsWebServiceImplService", targetNamespace = "http://webservice.jaxWsAnnotations.examples.javacodegeeks.com/", wsdlLocation = "file:/Users/saurabharora123/Downloads/ctf.wsdl")
public class WsAnnotationsWebServiceImplService extends Service {
    private final static URL WSANNOTATIONSWEBSERVICEIMPLSERVICE_WSDL_LOCATION;
    private final static WebServiceException WSANNOTATIONSWEBSERVICEIMPLSERVICE_EXCEPTION;
    private final static QName WSANNOTATIONSWEBSERVICEIMPLSERVICE_QNAME = new QName(
            "http://webservice.jaxWsAnnotations.examples.javacodegeeks.com/", "WsAnnotationsWebServiceImplService");
    static {
        URL url = null;
        WebServiceException e = null;
        try {
            url = new URL("file:/Users/saurabharora123/Downloads/ctf.wsdl");
        } catch (MalformedURLException ex) {
            e = new WebServiceException(ex);
        }
        WSANNOTATIONSWEBSERVICEIMPLSERVICE_WSDL_LOCATION = url;
        WSANNOTATIONSWEBSERVICEIMPLSERVICE_EXCEPTION = e;
    }
    public WsAnnotationsWebServiceImplService() {
        super(__getWsdlLocation(), WSANNOTATIONSWEBSERVICEIMPLSERVICE_QNAME);
    }
    public WsAnnotationsWebServiceImplService(WebServiceFeature... features) {
        super(__getWsdlLocation(), WSANNOTATIONSWEBSERVICEIMPLSERVICE_QNAME, features);
    }
    public WsAnnotationsWebServiceImplService(URL wsdlLocation) {
        super(wsdlLocation, WSANNOTATIONSWEBSERVICEIMPLSERVICE_QNAME);
    }
    public WsAnnotationsWebServiceImplService(URL wsdlLocation, WebServiceFeature... features) {
        super(wsdlLocation, WSANNOTATIONSWEBSERVICEIMPLSERVICE_QNAME, features);
    }
    public WsAnnotationsWebServiceImplService(URL wsdlLocation, QName serviceName) {
        super(wsdlLocation, serviceName);
    }
    public WsAnnotationsWebServiceImplService(URL wsdlLocation, QName serviceName, WebServiceFeature... features) {
        super(wsdlLocation, serviceName, features);
    }
    /**
     * 
     * @return returns WSAnnotationWebServiceI
     */
    @WebEndpoint(name = "WsAnnotationsWebServiceImplPort")
    public WSAnnotationWebServiceI getWsAnnotationsWebServiceImplPort() {
        return super.getPort(new QName("http://webservice.jaxWsAnnotations.examples.javacodegeeks.com/",
                "WsAnnotationsWebServiceImplPort"), WSAnnotationWebServiceI.class);
    }
    /**
     * 
     * @param features
     *            A list of {@link javax.xml.ws.WebServiceFeature} to configure
     *            on the proxy. Supported features not in the
     *            <code>features</code> parameter will have their default
     *            values.
     * @return returns WSAnnotationWebServiceI
     */
    @WebEndpoint(name = "WsAnnotationsWebServiceImplPort")
    public WSAnnotationWebServiceI getWsAnnotationsWebServiceImplPort(WebServiceFeature... features) {
        return super.getPort(new QName("http://webservice.jaxWsAnnotations.examples.javacodegeeks.com/",
                "WsAnnotationsWebServiceImplPort"), WSAnnotationWebServiceI.class, features);
    }
    private static URL __getWsdlLocation() {
        if (WSANNOTATIONSWEBSERVICEIMPLSERVICE_EXCEPTION != null) {
            throw WSANNOTATIONSWEBSERVICEIMPLSERVICE_EXCEPTION;
        }
        return WSANNOTATIONSWEBSERVICEIMPLSERVICE_WSDL_LOCATION;
    }
}

Refer to the highlighted line in the above-generated program that has the annotation @WebServiceClient. The information specified in this annotation helps in identifying a wsdl: service element inside a WSDL document. This element represents the Web service for which the generated service interface provides a client view.

 @RequestWrapper

@RequestWrapper JAX-WS annotation is used to annotate methods in the Service Endpoint Interface with the request wrapper bean to be used at runtime. It has 4 optional elements; className that represents the request wrapper bean name, localName that represents element’s local name, partName that represent the part name of the wrapper part in the generated WSDL file, and targetNamespace that represents the element’s namespace.

Example usage: WSRequestWrapperInterface.java

package com.javacodegeeks.examples.jaxWsAnnotations.wrapper;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;
import javax.xml.ws.RequestWrapper;
@WebService
@SOAPBinding(style=Style.RPC)
public interface WSRequestWrapperInterface {
    @WebMethod
    @RequestWrapper(localName="CTF", 
    targetNamespace="http://javacodegeeks.com/tempUtil", 
    className="com.javacodegeeks.examples.jaxWsAnnotations.webservice.CTF")
    float celsiusToFarhenheit(float celsius);
}
1.7 @ResponseWrapper
@ResponseWrapper JAX-WS annotation is used to annotate methods in the Service Endpoint Interface with the response wrapper bean to be used at runtime. It has 4 optional elements; className that represents the response wrapper bean name, localName that represents element’s local name, partName that represent the part name of the wrapper part in the generated WSDL file, and targetNamespace that represents the element’s namespace.

Example usage: WSRequestWrapperInterface.java

package com.javacodegeeks.examples.jaxWsAnnotations.wrapper;
import javax.jws.WebMethod;
import javax.xml.ws.ResponseWrapper;
public interface WSResponseWrapperInterfaceI {
    @WebMethod
    @ResponseWrapper(localName="CTFResponse", 
    targetNamespace="http://javacodegeeks.com/tempUtil", 
    className="com.javacodegeeks.examples.jaxWsAnnotations.webservice.CTFResponse")
    float celsiusToFarhenheit(float celsius);
}

@Oneway

@Oneway JAX-WS annotation is applied to WebMethod which means that method will have only input and no output. When a @Oneway method is called, control is returned to calling method even before the actual operation is performed. It means that nothing will escape method neither response neither exception.

Example usage: WSAnnotationsOnewayI.java

package com.javacodegeeks.examples.jaxWsAnnotations.oneway;
import javax.jws.Oneway;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;
@WebService
@SOAPBinding(style = Style.RPC)
public interface WSAnnotationsOnewayI {
    @WebMethod
    @Oneway
    void sayHello();
}

@HandlerChain

Web Services and their clients may need to access the SOAP message for additional processing of the message request or response. A SOAP message handler provides a mechanism for intercepting the SOAP message during request and response.

A handler at the server side can be a validator. Let’s say we want to validate the temperature before the actual service method is called. To do this our validator class shall implement interface SOAPHandler

TemperatureValidator.java


package com.javacodegeeks.examples.jaxWsAnnotations.handler;
import java.util.Set;
import javax.xml.namespace.QName;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;
public class TemperatureValidator implements SOAPHandler {
    @Override
    public boolean handleMessage(SOAPMessageContext context) {
        // TODO Auto-generated method stub
        return false;
    }
    @Override
    public boolean handleFault(SOAPMessageContext context) {
        // TODO Auto-generated method stub
        return false;
    }
    @Override
    public void close(MessageContext context) {
        // TODO Auto-generated method stub
         
    }
    @Override
    public Set getHeaders() {
        // TODO Auto-generated method stub
        return null;
    }
}
Next, we shall implement a SOAP handler XML file that may also contain sequence of handlers.

soap-handler.xml


<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<javaee:handler-chains xmlns:javaee="http://java.sun.com/xml/ns/javaee"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <javaee:handler-chain>
        <javaee:handler>
            <javaee:handler-class>com.javacodegeeks.examples.jaxWsAnnotations.handler.TemperatureValidator
            </javaee:handler-class>
        </javaee:handler>
    </javaee:handler-chain>
</javaee:handler-chains>
After this we shall configure @HandlerChain JAX-WS annotation in SEI:

WSAnnotationsHandlerChainI.java


package com.javacodegeeks.examples.jaxWsAnnotations.handler;
import javax.jws.HandlerChain;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;
@WebService
@SOAPBinding(style = Style.RPC)
public interface WSAnnotationsHandlerChainI {
    @HandlerChain(file = "soap-handler.xml")
    @WebMethod
    float celsiusToFarhenheit(float celsius);
}


The directory structure of this example

The directory structure of the above example in eclipse shall look like:


PROJECT

 Web Service Testing

Web Services Testing is testing of Web services and its Protocols like SOAP & REST. To test a Webservice you can


  • Test Manually
  • Create your own Automation Code
  • Use an off-the-shelf automation tool like SoapUI.

WebService Testing involves the following steps -


  1. Understand the WSDL file
  2. Determine the operations that particular web service provides
  3. Determine the XML request format which we need to send
  4. Determine the response XML format
  5. Using a tool or writing code to send a request and validate the response

Suppose we want to test a web service which provides Currency Conversion Facility. It will the current conversion rates between the different countries currency. This service we can use in our applications to convert the values from one currency to the other currency.

Now let's look at the above steps


Step 1 to 4: Understading WSDL and determining operations & XML formats

Currency Converter WSDL file can be seen @ (http://www.webservicex.net/CurrencyConvertor.asmx?wsdl) which will give the information about the Currency Converter web service methods which it will support, the parameter which we need a pass and the type of parameters… etc

t3
t4



Step 5: Using a tool or writing code to send a request and validate the response


There are lots of tools available to test web services. SoapUI is one of the popular tools which will help us to test web services. In fact, you can use any programing language which is capable of sending the XML request to the web service provider application over the HTTP and able to parse and validate the response XML against the expected result. In our case, we will test the web service


  1. Using Java
  2. Using SoapUI


PART 1) WebService Testing Using Apache Axis2 API (Java).


Generally, web service takes the request and sends the response in the XML format.

Apache Axis2 API project is a Java implementation API, which will be used to create the Web services for both server-side (service provider) and client side (service consumer).

Axis2 is capable of sending SOAP messages and Receives & Processes the SOAP messages. We can write a small Java program using the API to create the web service. Axis2 will generate the WSDL from Java program which will be used to communicate the services offered by the web service. We can use the same Axis2 to generate the Java class (stub) from WSDL file which we can use as a client program to generate the web service request, to send the request to the service endpoint and to process the response.


  • Basically, we will create a simple Java program in which we will instantiate the stub class.
  • Using the stub we will invoke the request method bypassing all the required information.
  • Stub program will convert that request into XML request format and sends it the service endpoint which will read the request and processes the request and sends the response in XML format.
  • The XML response will be converted into a Java class by stub and returned to the actual program.

Let's look at the above steps in detail

Step a) Download the axis2 API @ https://axis.apache.org/axis2/Java/core/download.cgi & Set the environment variable 'AXIS2_HOME'

SYSTEM PROPERTIES


Step b) Create a folder to keep all the generated artifacts

Ex : C:\Axis\Projects\CurrencyConverter

Step c) Open the command prompt and navigate to the folder structure where you want to generate the artifacts and Run the following command which will generate the stubs

%AXIS2_HOME%\bin\WSDL2Java -uri http://www.webservicex.net/CurrencyConvertor.asmx?wsdl -p org.apache.axis2.currencyconvertor -d adb –s

CMD

Step d) Once the command is successfully run, you will see the folder with required files.

df


Step e) Next we have to create the client program, through which we will send the actual request using the generated stubs. Open the eclipse and create the new Java project and select the folder which we have created above.

oval
  
Step f) Add all the axis2 related jars to project build path, which will be there in lib folder of the axis2 software folder

(for ex : C:\Axis\axis2-1.6.2\lib)

pro


Step g) Create a new Java class (ex: Client.Java) and instantiate stub object. Using the stub object we can call all the supported methods of the particular WebService.  




Client.Java Program
package org.apache.axis2.currencyconvertor;
import org.apache.axis2.currencyconvertor.CurrencyConvertorStub.ConversionRate;
import org.apache.axis2.currencyconvertor.CurrencyConvertorStub.ConversionRateResponse;
import org.apache.axis2.currencyconvertor.CurrencyConvertorStub.Currency;

public class Client {
 public static void main(Java.lang.String args[]) {

  try {

       //Create the stub object by passing the service end point url
       CurrencyConvertorStub stub = new CurrencyConvertorStub("http://www.webservicex.net/CurrencyConvertor.asmx");
       //ConversionRate is the class which we have to use mention the from and to currency
       //ConversionRate object will be the parameter for the conversionRate operation
       ConversionRate conversionRate = new ConversionRate();
       conversionRate.setFromCurrency(Currency.USD);
       conversionRate.setToCurrency(Currency.INR);

       //Create the ConversionRateResponse object, which is going to be used to catch the response
       //call the conversionRate service using the stub object
       ConversionRateResponse conversionRateResponse = stub.conversionRate(conversionRate);

       //We can use the conversionRateResponse object to retrieve the response of the ConversionRate Service
       System.out.println("Conversion Rate from INR to USD : " + conversionRateResponse.getConversionRateResult());

       } catch (Exception e) {
       e.printStackTrace();
      }
    }
}
PART 2) Using SoapUI to Test the WebService

In SoapUI  

Go to File > New Soap Project
Enter the project Name and the WSDL URI location
Click OK

scc

Expand the first request and double click on the 'Request1'. It will display the SOAP request in the XML format.
Enter the From Currency and To Currency
Click on the submit button
Response XML will be displayed right side pane.


 Hosting Java Web-based Distributed Systems with Tomcat


image5

Setting the JAVA_HOME Variable in Windows

To install Confluence manually on Windows, you will need to set an environment variable to point Confluence to your Java installation directory.

In most cases, you should set the JRE_HOME environment variable, but if it is not set, Confluence will use JAVA_HOME.

Set the JAVA_HOME Variable

To set the JRE_HOME or JAVA_HOME variable:


  • Locate your Java installation directory


image2


  • Do one of the following:

🔼Windows 7 – Right click My Computer and select Properties > Advanced
🔼Windows 8 – Go to Control Panel > System > Advanced System Settings
🔼Windows 10 – Search for Environment Variables then select Edit the system environment variables

  • Click the Environment Variables button.
  • Under System Variables, click New.
  • In the Variable Name field, enter either:
➥JAVA_HOME if you installed the JDK (Java Development Kit)

or
➥JRE_HOME if you installed the JRE (Java Runtime Environment)
  •  In the Variable Value field, enter your JDK or JRE installation path.



image1

image3

image4



  • Click OK and Apply Changes as prompted

You'll need to close and re-open any command windows that were open before you made these changes, as there's no way to reload environment variables from an active command prompt. If the changes don't take effect after reopening the command window, restart Windows.

Set the JAVA_HOME variable via the command line


If you would prefer to set the JAVA_HOME (or JRE_HOME) variable via the command line:

  1. Open Command Prompt (make sure you Run as administrator so you're able to add a system environment variable).
  2. Set the value of the environment variable to your JDK (or JRE) installation path as follows:

setx -m JAVA_HOME "C:\Progra~1\Java\jdk1.8.0_XX"

If the path contains spaces, use the shortened path name.

    3. Restart Command Prompt to reload the environment variables then uses the following command to check it's been added correctly.

echo %JAVA_HOME%

You should see the path to your JDK (or JRE) installation. 


Components and Features of Apache Tomcat


Apache Tomcat has the following components and features to manage web applications.


  • Catalina
  • Coyote
  • Jasper
  • Cluster
  • High Availability
  • Web Application

Jasper 2

Jasper is the JSP Engine for Tomcat. Jasper is responsible for parsing JSP files and compilation of JSP’s Java code as servlets.
Jasper is capable of background compilation, which means if any changes are made to JSP files, then the older versions of those JSP files are still retained by the server until the updated JSP files are recompiled.

Catalina

Catalina is Tomcat’s servlet container. Catalina makes Tomcat a Web Server for dynamic content.

Coyote

Coyote is the component that makes Tomcat capable as an HTTP Web Server. Coyote makes Catalina also act as a server that serves static content.

Apache Tomcat Configuration 

HTTP Connector


  • The HTTP Connector element represents a Connector component that supports the HTTP/1.1 protocol. It enables Catalina to function as a stand-alone web server, in addition to its ability to execute servlets and JSP pages. A particular instance of this component listens for connections on a specific TCP port number on the server. One or more such Connectors can be configured as part of a single Service, each forwarding to the associated Engine to perform request processing and create the response.
  • If you wish to configure the Connector that is used for connections to web servers using the AJP protocol (such as the mod_jk 1.2.x connector for Apache 1.3), see here instead.
  • At server startup time, this Connector will create a number of request processing threads (based on the value configured for the minSpareThreads attribute). Each incoming request requires a thread for the duration of that request. If more simultaneous requests are received than can be handled by the currently available request processing threads, additional threads will be created up to the configured maximum (the value of the maxThreads attribute). If still more simultaneous requests are received, they are stacked up inside the server socket created by the Connector, up to the configured maximum (the value of the acceptCount attribute). Any further simultaneous requests will receive "connection refused" errors until resources are available to process them.



➤Attributes

Common Attributes

All implementations of Connector support the following attributes:

ima7

ima8


➤Standard Implementation

HTTP supports the following additional attributes (in addition to the common attributes listed above):


ima9
ima10
ima11
    



➤Special Features

↪HTTP/1.1 and HTTP/1.0 Support

This Connector supports all of the required features of the HTTP/1.1 protocol, as described in RFC 2616, including persistent connections, pipelining, expectations and chunked encoding. If the client (typically a browser) supports only HTTP/1.0, the Connector will gracefully fall back to supporting this protocol as well. No special configuration is required to enable this support. The Connector also supports HTTP/1.0 keep-alive.

RFC 2616 requires that HTTP servers always begin their responses with the highest HTTP version that they claim to support. Therefore, this Connector will always return HTTP/1.1 at the beginning of its responses.


↪Proxy Support

The proxyName and proxyPort attributes can be used when Tomcat is run behind a proxy server. These attributes modify the values returned to web applications that call the request.getServerName() and request.getServerPort() methods, which are often used to construct absolute URLs for redirects. Without configuring these attributes, the values returned would reflect the server name and port on which the connection from the proxy server was received, rather than the server name and port to whom the client directed the original request.

For more information, see the Proxy Support HOW-TO.


↪SSL Support

You can enable SSL support for a particular instance of this Connector by setting the secure attribute to true. In addition, you may need to configure the following attributes:

ima12
ima13


The AJP Connector


The AJP Connector element represents a Connector component that communicates with a web connector via the AJP protocol. This is used for cases where you wish to invisibly integrate Tomcat 5 into an existing (or new) Apache installation, and you want Apache to handle the static content contained in the web application, and/or utilize Apache's SSL processing.

This connector supports load balancing when used in conjunction with the jvmRoute attribute of the Engine.

The native connectors supported with this Tomcat release are:

  • JK 1.2.x with any of the supported servers
  • mod_proxy on Apache httpd 2.x (included by default in Apache HTTP Server 2.2), with AJP, enabled: see the httpd docs for details.
Other native connectors supporting AJP may work but are no longer supported.

Attributes

Common Attributes
All implementations of Connector support the following attributes:

aaaa
a12


Standard Implementation

To use AJP, you must specify the protocol attribute (see above).

This implementation supports the AJP 1.3 protocol.

It supports the following additional attributes (in addition to the common attributes listed above):

imaa12
ccc



The Server Component


A Server element represents the entire Catalina servlet container. Therefore, it must be the single outermost element in the conf/server.xml configuration file. Its attributes represent the characteristics of the servlet container as a whole.

Attributes

Common Attributes
All implementations of Server support the following attributes:

kk

Standard Implementation

The standard implementation of Server is org.apache.catalina.core.StandardServer. It supports the following additional attributes (in addition to the common attributes listed above):

Attribute   | Description

Nested Components

The following components may be nested inside a Server element:

  • Service - One or more service element.
  • GlobalNamingResources - Configure the JNDI global resources for the server.

Special Features

There are no special features associated with a Server.


Should JAVA_HOME point to JDK or JRE?

  • If you're doing any sort of development, or building with Maven or Ant, you need to point to the JDK (Java Development Kit) where utilities such as javac (the Java Compiler) reside. Otherwise, you can point to the JRE (Java Runtime Environment).

  • The JDK contains everything the JRE has and more. If you're just executing Java programs, you can point to either the JRE or the JDK.


Start and Stop Apache Tomcat from the Command Line (Windows)


Apache Tomcat can be started and stopped from the command line.

To learn how to start and stop Apache Tomcat from the command line in a Windows environment, follow these five steps:

  1. Start a Command Prompt from the Start menu.
  2. Navigate to the Tomcat bin directory, e.g., c:/Tomcat8/bin:

ima21


3.Type in startup and then hit Enter to execute the Tomcat server startup script:

ima22




4. A separate window will open and a series of messages will appear, followed by the message indicating the server is started: 

ima23


The exact number of milliseconds will vary based on the number of web applications that are deployed, among other factors.


5. To stop the Tomcat server, type in shutdown and then hit Enter in the original command prompt: 

ima24


The startup window that appeared earlier will now be closed, indicating the Tomcat server has been stopped.


 Run a JSP Program in Apache Tomcat 


A Java Server Page, or JSP, program is a crucial part of a Java web application because the JSP will send a response back to the server in the form of a web page. For example, a JSP might display the line items of an order to the browser user. In this topic, you will create a very simple JSP and learn how to run the program at the Tomcat server.

To learn how to run a JSP in Apache Tomcat in a Windows environment, follow these 7 steps:

  1. In your text editor, you will develop a simple JSP that creates a web page to display the current date. Type in the following statements in a new file:

ima45


The program contains <%@ tags that provide metadata about the JSP and import directives. The JSP also contains HTML tags that will be rendered by the browser in the usual way. Note the <% tags that encapsulate Java code. The snippets of Java code are referred to as "scriplets." When the JSP is requested by the browser, the program will be converted into a servlet by a program in the Tomcat container (Jasper) and the HTML output will be sent to the browser.

2. Save your file as DateJSP.jsp.
3. Copy your file to CATALINA_HOME/webapps/ROOT, e.g., c:/Tomcat8/webapps/ROOT.
4. Start the Tomcat server.
5. Start your browser if it is not already running.
6. In the address area of the browser, type http://localhost:8080/DateJSP.jsp and submit that address to the browser.

7. The output of your JSP page will be displayed: 


ima46


Steps of changing the Tomcat Port

1) Locate server.xml in {Tomcat installation folder}\ conf \

2) Find following similar statement

<!-- Define a non-SSL HTTP/1.1 Connector on port 8180 -->
    <Connector port="8080" maxHttpHeaderSize="8192"
               maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
               enableLookups="false" redirectPort="8443" acceptCount="100"
               connectionTimeout="20000" disableUploadTimeout="true" />

or

    <!-- A "Connector" represents an endpoint by which requests are received
         and responses are returned. Documentation at :
         Java HTTP Connector: /docs/config/http.html (blocking & non-blocking)
         Java AJP  Connector: /docs/config/ajp.html
         APR (HTTP/AJP) Connector: /docs/apr.html
         Define a non-SSL HTTP/1.1 Connector on port 8080
    -->
    <Connector port="8080" protocol="HTTP/1.1" 
               connectionTimeout="20000" 
               redirectPort="8443" />


3) About Tomcat’s server.xml file cites its runs on port 8080. Change the Connector port=”8080″ port to any other port number.

For example

 <Connector port="8181" protocol="HTTP/1.1" 
               connectionTimeout="20000" 
               redirectPort="8443" />
Above statement instruct Tomcat server runs on port 8181.


4) Edit and save the server.xml file. Restart Tomcat. Done

Creating Servlet  in Eclipse

Eclipse is an open-source ide for developing JavaSE and JavaEE (J2EE) applications. You can download the eclipse ide from the eclipse website http://www.eclipse.org/downloads/.

You need to download the eclipse ide for JavaEE developers.

Creating a servlet example in eclipse ide saves a lot of work to be done. It is easy and simple to create a servlet example. Let's see the steps, you need to follow to create the first servlet example.

  • Create a Dynamic web project
  • create a servlet
  • add servlet-api.jar file
  • Run the servlet

1) Create a dynamic web project:

For creating a dynamic web project click on File Menu -> New -> Project..-> Web -> dynamic web project -> write your project name e.g. first -> Finish.

1

2

3

4

5
6


2) Create the servlet in eclipse IDE:

For creating a servlet, explore the project by clicking the + icon -> explore the Java Resources -> right click on src -> New -> servlet -> write your servlet name e.g. Hello -> uncheck all the checkboxes except doGet() -> next -> Finish.

6

7

Creating Servlet in eclipse IDE


8

9

10


3) add jar file in eclipse IDE:

For adding a jar file, right click on your project -> Build Path -> Configure Build Path -> click on Libraries tab in Java Build Path -> click on Add External JARs button -> select the servlet-api.jar file under tomcat/lib -> ok.

89

90

91

922

23

Now servlet has been created, Let's write the first servlet code.

oo



4) Start the server and deploy the project:

For starting the server and deploying the project in one step, Right click on your project -> Run As -> Run on Server -> choose tomcat server -> next -> addAll -> finish.

pp

ll

kk

jj

Now tomcat server has been started and the project is deployed. To access the servlet write the URL pattern name in the URL bar of the browser. In this case Hello then enter.


hh

 Configure tomcat server in Eclipse

If you are using Eclipse IDE first time, you need to configure the tomcat server First.

For configuring the tomcat server in eclipse IDE, click on servers tab at the bottom side of the IDE -> right click on blank area -> New -> Servers -> choose tomcat then its version -> next -> click on Browse button -> select the apache tomcat root folder previous to bin -> next -> addAll -> Finish.


dd

aa1

ss

zz

xx

c

vv

Now, the tomcat7 server has been configured in eclipse IDE.


bbd

 JAR Files

A JAR file is a file that contains all components to make a self-contained executable Java application. Moreover, a JAR file includes compiled Java source code, manifest file, XML based configuration data, JSON based data files, images, and audio. It is an aggregation of all these files into a single, compressed file. Compressing all the files helps to reduce the size of the application. Furthermore, it makes it easier to move the JAR file over the network between different platforms.

Every Java Development Kit (JDK) includes a JAR utility to support JAR files. It allows creating new JAR files with a manifest file and extracting all the content of a JAR file onto the file system. Moreover, JAR utility helps to update existing JAR files.

jar


WAR Files

A WAR file contains files related to a web project. It contains servlet, JSP, XML, HTML, CSS, and JavaScript files that can be deployed on any servlet/JSP container. The jar tool of JDK helps to create a WAR file. These files are inside the WEB-INF folder of the project. A WAR file combines all the files into a single unit. Therefore, it takes a minimum amount of time to transfer a file from client to server.
There are two methods to deploy a WAR file: by using the server control panel or by manually having the war file in a specific folder of the server. If the programmer wants to deploy a WAR file in a server such as Apache Tomcat manually, he can go to the webapps directory of Tomcat and paste the WAR file in that directory. If not, when running the web project, the server extracts the WAR file internally.


war

Difference Between JAR and WAR Files


Definition

A JAR file is a file with Java classes, associated metadata, and resources such as text, images aggregated into one file. A WAR file is a file that is used to distribute a collection of JAR files, JSP, Servlet, XML files, static web pages like HTML and other resources that constitute a web application. Thus, this explains the main difference between JAR and WAR Files.

Long Form

JAR file stands for Java Archive. WAR file stands for Web Application Resource or Web Application Archive.

File Extension

Moreover, a JAR file has the .jar file extension while a WAR file has the .war file extension.

Consist of

JAR files include compiled Java source code, manifest file, XML based configuration data, JSON based data files, images, and audio. In contrast, WAR files contain servlet, JSP, XML, HTML, CSS, and, JavaScript files. Hence, this is another difference between JAR and WAR Files.

Usage

Their usage attributes to another difference between JAR and WAR Files. That is; a JAR file allows Java Runtime Environment (JRE) to deploy an entire application including the classes and the associated resources in a single request. On the other hand, a WAR file allows testing and deploying a web application easily.


differ

Basic structure:

WEB-INF/ - directory for application support
   lib/ - supporting jar files
   web.xml - configuration file for the application
...

'WEB-INF' is used to package:

Configuration

Supporting compiled java code.

Other non-public information.

The 'web.xml' file tells the J2EE container (Tomcat) what to do.

Everything outside of 'WEB-INF' is public content available via the web server (Tomcat).


Tomcat starts but Home Page does NOT open on the browser with URL http://localhost:8080


1


Today I was running Apache Tomcat from Eclipse and while accessing URL http://localhost:8080 found HTTP Status 404 – Not Found error.

The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.

I’ve setup Apache Tomcat by following detailed steps using in-depth tutorial. Steps worked perfectly fine but as I didn’t have any projects added to tomcat web apps folder it threw 404 error for me.

If you also face 404 Page not found an error then try following below steps:

Step-1
Go to Eclipse IDE
Click on Servers Tab
Double click on Tomcat v9.0 Server at localhost

SS


Step-2
New Apache Tomcat configuration page will open
Go to Server Location section
Select Use Tomcat installation (takes control of Tomcat installation)

2


Step-3
Save configuration
Restart Server by right-clicking on tomcat server and click Restart
Visit http://localhost:8080 again and now you should see working tomcat page


THIRTD




Share:

0 comments