Use JB and WL to develop Web Services

Source: Internet
Author: User
Tags xml parser

At present, most companies are either actively developing the Web service infrastructure or planning to do so. Honestly, using the previously written business logic and making it public as a Web service is not that difficult. In the past few years, the Web Service Standards have been greatly developed and have become reliable and robust. Even different development toolboxes can generate standard results across different platforms.

Adding a web service infrastructure to a business process brings the following benefits. First, the existing source code (PC-based or mainframe-based) and all development investment will not be wasted, but will continue to play a role through the new web interface. Second, new business transactions are easily processed through the Web and can interact with any new system or a traditional system that is open as a standard web service. Third, business transactions become meaningful, thanks in part to the soap and XML standards. Fourth, if the web service is well designed, the required process control should be minimal. Fifth, because the session is connected over HTTP, it may not be restricted by the firewall. Of course, there are many other benefits to implementing Web Services. Therefore, for any company, Web services have a high ROI (ROI ).

In this article, I will explain how to use enterprise-level tools (such as JBuilder X, JBuilder 2005 Enterprise, and BEA WebLogic application server) to create simple Web Services based on existing Java applications. I will also describe the structure, standards, logic, and related platforms of Web Services. To demonstrate the running Web service, I will create a project with servers and clients. The client starts a real Web Service session on the server. I will also briefly describe how to use free tools such as Eclipse IDE and axis toolkit to complete the same task.

Host environment

To obtain the running Web service, you must have an application server that can reside in the service. Web service can be registered in any public UDDI (Universal Description, discovery and integration, unified description, discovery and integration protocols, or register with the local UDDI registry that resides on the application server. UDDI provides the address book function to potential business clients. It allows clients to locate specific services and describes which APIs are available. Without a UDDI registration library, the business client can (and often) directly turn to a Web Service URL and request the WSDL (Web Service Definition Language, Web Service Description Language) document, the document also contains detailed descriptions of the APIS provided. WSDL is an XML document that resides on the application server.

In a real business environment, WSDL defines not only all available methods, but also all transaction modes. The purpose of WSDL is to be recognized by the web service program and help it create object stubs with methods that can be called by the client. Therefore, the WSDL file is automatically generated by the Toolbox used to create the web service.

The Web service resides in the Web Service container on the application server as a web application. Any client you are interested in can start a regular http session to interact with it. We will use the BEA WebLogic application server to establish a web service, which is one of the mainstream platforms in the industry. For development purposes, the BEA WebLogic application server can be used for free. For production purposes, a license is required. As an alternative, you can also use the free Tomcat application server and axis toolbox, or use the jetty application server and axis toolbox. Of course there are other application servers, such as JBoss, SunONE of Sun Microsystems, and WebSphere of IBM, which are beyond the scope of this article. All these Web platforms can reside in web applications and Web services. However, from the perspective of development, JBuilder X or 2005 Enterprise is flexible and easy to use in creating web services.

BEA WebLogic is easy to install, but JBuilder needs to be configured to hook up the application server. Note: Go to JBuilder and click Configure servers under the tool menu to set up the application server.

Create a traditional project

Create a new project in JBuilder. Create a "beanexport" package under the project and add a package namedBean1. Create anotherTuple(SeeList1). The tuple class has a string used to demonstrate more complex objects sent by a Web service. This object is optional and does not have to be used.

Publish code as a Web Service

To demonstrate how to wrap existing "traditional" APIs and convert them into full-featured Web Services, consider an extremely simple Java class named bean1, which has only three methods. The first method always returns a random number, the second returns a "hello" string, and the third returns a more complex object.

This class discloses a public API with only three methods, while the APIS contained in real applications are much more complex. An enterprise application may contain hundreds of methods that return values from the database, EJB, or mainframe call wrapper. Some of these methods contain parameters, while others start the business transaction session. However, converting any complex API into a Web Service API is as easy as this example class.

package beanexport;import java.io.Serializable;public class Bean1 implements Serializable {   public double getDouble(){      return Math.random();   }   public String getText(){      return "Hello";   }   public Tuple getHeader(){      Tuple t = new Tuple("Vlad","Kofman");      return t;   }}

AboutTupleObject source, seeList1.

Create a Web Service

Assume that we have createdBean1Java project, and can be compiled successfully, while BEA Weblogic server is running normally, now bean1 class can be published as web service. JBuilder simplifies the creation and deployment of Web Services. Open the bean1 project and perform the following steps:

  • Click project> Project Properties> server.
  • Select WebLogic from the listed options.

Note:For web services to be deployed on free Tomcat servers, you can also use JBuilder for development. Here, it is also listed as an option.

  • Additional service configuration: The project will reside on the selected service (for example, EJB. You can also select Servlet and JSP. Click OK.

Figure3

  • Click File> New> Web Services.
  • Click new web service configuration (JBuilder X ).
  • Select WebLogic as the toolbox. The default toolbox is axis (used with the Tomcat server ).
  • Select the server and client modules.
  • Create a web module. All default values are used.
  • Create an application module. All default values are also used.



Figure4

  • In the next interface, name the server bean1server and save it.

JBuilder automatically creates all required J2EE (Java 2 Enterprise Edition) Standardized folders and file structures. After saving the initial configuration, it opens a web services designer view.

The next step is simple.Bean1The project should already have the following structure (left panel ):

  • Package "beanexport"
  • Applicationmodule1 Module
  • Web-Services Module
  • Web-services design tools

Retrieve the bean1 class and drag it to the Web-services design tool area. Alternatively, click Create service and select Java service from the drop-down menu.

ReconstructionBean1Project; more files are automatically created in the subfolders of the project. In this way, the Web service has been developed. Next, you just need to deploy it!

Consider the role of JBuilder.

After obtaining the class to be made public, JBuilder will review all public APIs of the class and automatically generate the WSDL definition file and all soap stubs and proxies, package them into war and ear files (see the following for details), and prepare deployment descriptors specific to the selected application server.

Similarly, if axis is selected as the toolbox and Tomcat is used as the server, files specific to them are generated.

 

All Web Services communicate over HTTP (or HTTPS. The client sends a SOAP (Simple Object Access Protocol) request and waits for the soap response. Soap is essentially a special XML format used to describe communication. Both the server and client have the XML Parser and Encoder that communicate through the HTTP socket. After receiving a request, it is decoded as a callable, parameter-specific method, after calling this method, its return value is packaged into the XML-SOAP envelope and then returned.

According to J2EE specifications, web applications must use a specific application structure. The war (Web Archive) file contains the deployment descriptor and code, and is compressed to the ear (Enterprise archive) file for installation on the application server. This specification treats all platforms equally, so any code in the war and ear packages developed by any toolbox can run on any application server. However, most application server vendors generally have different deployment descriptor files.

Fortunately, JBuilder simplifies web application development. It can also often use an independent axis java2wsdl tool, or manually package the code into the ear file.

Sample Server

Now that the project has been completed, you can deploy it on the application server and run it as a web service. It should be like this (see the panel on the right ):

Deploying a web service with JBuilder is as easy as creating it. Make sure that BEA WebLogic is running. Right-click applicationmodule1 (service application module name) and choose-> deploy options-> deploy.


Figure 7

JBuilder displays the following content:

Initiated Task: [0] [Deployer:149026]Deploy application                ApplicationModule1 on myserver.Task 0 running: [Deployer:149026]Deploy application                ApplicationModule1 on myserver.Deployment completed on Server myserver

That's it! Now the new Web Service is resident and can be used all over the world!

You can also release the deployment and redeploy it in the same way. All current deployments can be listed in the same menu.

To perform a test, you can open JBuilder> Tools> Web Services console or direct the web browser to http: // localhost: 7001/Web-services/bean1.

A new web-based service testing client provided by Weblogic will appear. It will call soap communication in the background to call the bean1 method. It can even display XML sent to various places.

For example, if you click the gettext () method, the following message is displayed:

Parameter Name

Parameter Value

Return Value

Hello

Send a request to the server:

<!--REQUEST.................--><env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/"              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"              xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"              xmlns:xsd="http://www.w3.org/2001/XMLSchema">   <env:Body env:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">   <m:getText xmlns:m="http://beanws">   </m:getText>   </env:Body></env:Envelope>

Server Response:

<!--RESPONSE.................--><env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/"              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"              xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"              xmlns:xsd="http://www.w3.org/2001/XMLSchema">   <env:Body env:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">      <m:getTextResponse xmlns:m="http://beanws">         <result xsi:type="xsd:string">Hello</result>      </m:getTextResponse>   </env:Body></env:Envelope>

Add "?" to the URL You can see the entire WSDL file:

Http: // localhost: 7001/Web-services/bean1? WSDL

Server deployment in the production environment certainly does not use JBuilder to deploy the ear file, but uses the web-based Management Console that is as easy to operate as JBuilder, it is usually run on the same port as the WebLogic Server (for example, http: // localhost: 7001/console ).

See the Weblogic document on how to use the server management function. You can find the applicationmodule. Ear file in the JBuilder project directory.

Simple Client

WebLogic testing clients are not very useful for businesses; other clients want to use their own Web Services. The general mechanism for creating a client is to direct the Web Service toolbox to the WSDL file and generate a client object stub. Use the stub to open the port to the server and call its method. The stubs also hide all the complexities of grouping and ungrouping soap (all processed in the background ). However, because the client module is added to the project, JBuilder automatically adds a generatedwebservicesclient folder for the project and creates the beanw.client.jar file.

This jar file contains all the files required to add a full-featured client to bean1.

Follow these steps to create a simple test client:

Create a new package named "test" and add a new test class.

Then, importBeanexport. generated .*Package; because the program is in the project, it should already be in the class path.

Create a connection to the service by generating a stub:

String wsdlUrl = "http://localhost:7001/web-services/Bean1?WSDL";Bean1 service = new Bean1_Impl(wsdlUrl);    //bind to serviceBean1Port port = service.getBean1Port();    //get port

Call a method at will. The complete program list is as follows:

package test;import beanexport.generated.*;public class Test {   public static void main(String[] args) {      try {         String wsdlUrl = "http://localhost:9501/web-services/Bean1?WSDL";         Bean1 service = new Bean1_Impl(wsdlUrl);         Bean1Port port = service.getBean1Port();         int result = port.getInt();         System.out.println("Int is: " + result);         Tuple[] tuple = port.getHeader();         System.out.println("1st tuple: " + tuple[0]);         System.out.println("2nd tuple: " + tuple[1]);         }         catch (Exception e) {         e.printStackTrace();      }   }}

The final result is an executable program, which uses Web service to communicate with the server. Before calling it, it is still a traditional Java method, but now it is a Web Service API.

Conclusion

This article introduces the basic knowledge of web service. A simple Java class is created to convert it into a full-featured web service. This article also discusses how to generate a client that communicates with the server and calls soap.

Packaging "traditional" code as a Web service mainly involves understanding the tools used. The current application server and toolbox can hide the complexity of "information pipeline" and soap grouping and XML parsing, this makes it easy to create a new Web service or publish existing code as a Web service task.

Listing 1

Tuple Classpackage beanexport;import java.io.Serializable;public class Tuple   implements Serializable {      private String key;      private String value;      public Tuple() {      }   public Tuple(String key, String value) {      this.key = key;      this.value = value;   }   public Tuple(Object key, Object value) {      this.key = key.toString();      this.value = value.toString();   }   public String getValue() {      return value;   }   public String getKey() {      return key;      this.key = key;   }   public void setValue(String value) {      this.value = value;   }}   }   public String toString() {      return key + " : " + value;   }   public void setKey(String key) {

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.