Developing Web services based on Jax-ws
This article is purely to move bricks.
Reproduced in: http://www.ithov.com/linux/125942_4.shtml.
Web Services is a service-oriented technology that provides services through a standard WEB protocol to ensure that application services from different platforms are interoperable. The benefits of Web services can be exchanged between applications implemented under the Web Services specification, regardless of the language, platform, or internal protocol in which they are used, to exchange data with one another. This article selects IBM WebSphere application Server as the operating environment for Web services and selects the IBM Rational Application Developer (RAD) for WebSphere is the development platform for this article. RAD is optimized for the test environment of IBM WebSphere application Server, reducing the time spent by developers in configuring the environment. All the examples shown in this article are developed and tested on the RAD for WebSphere platform.
Web Services and Jax-ws
There are two forms of Web Services development today: REST and SOAP. REST Web Services is based on the HTTP protocol, and SOAP Web Services supports a variety of transport protocols: HTTP, SMTP, MIME, and so on.
This article mainly introduces SOAP Web services. For JAVA, there are currently two SOAP Web Services specifications: Jax-ws and SAAJ.
SOAP Web services typically requires a machine-readable description (typically WSDL-based) on the server side to allow the client to identify the WEB services provided by the server side.
JAX-WS (Java API for XML Web services) is a set of Java APIs dedicated to implementing XML Web services. JDK 1.6 comes with a JAX-ws version of 2.1. However, Jax-WS only provides the underlying functionality of Web services, so if you want to implement complex features of Web services, such as WS-SECURITY,WS-POLICY,WS-RM, you need to switch to Apache CXF, Metro, or Axis.
The goal of this article is for developers who are first exposed to Web services or JAX-ws. So this article will share the following content:
- Web Services server-side development
- Development of Web Services clients
- Web services communication based on HTTPS protocol
- Optimizing network data transmission with @MTOM
JAX-WS Web Services development
Rad is an eclipse-based full-featured integrated development Environment (IDE), so developers who are familiar with eclipse can quickly get started with the RAD platform.
Server-Side development:
First, on the RAD platform, create the simplest Web service, which returns only one string-"Hello world"-to the client. The server-side workflow is as follows: Complete Web Services Authoring and publish Web services build Service description Files (WSDL) for client access. Next, wait for the SOAP request message from the client to parse the method call and the parameter format. Based on the description of WSDL and WSML, the corresponding object is called to complete the specified function, and the return value is placed in the SOAP response message back to the user.
Start by creating a new Web Project–webprojectdemo in RAD,
Figure 1. Create Web Project
Select the appropriate Target runtime (confirm that the Server runtime is already created in the "Servers" view) and make sure that the "ADD Project to an ear" is checked so that you do not need to create the ear manually.
Figure 2. Select a running environment to complete Project creation
Complete the creation of Web Project.
Next, start writing the Web service class, the development method is very simple, just use @WebService annotated Java class as the Web service class, @WebMethod the labeling class method as a Web service method. These tagged classes and methods can be called by the client after the service is released.
Listing 1. Service-side code
@WebService public class HelloWorld { @WebMethod public String SayHello () { return "Hello world!";
The short five-line code is HELLOWORLD Web service Class! HelloWorld has only one Web service method –sayhello ().
And then the HelloWorld service was released,
Figure 3. Publish HelloWorld Service
Publish finished, typing in browser
HTTP://WEBSERVER:9080/WEBPROJECTDEMO/HELLOWORLDSERVICE?WSDL, if you can see the following interface, it means that the release was successful. Next, we started the client development.
Figure 4. WSDL file
Client development:
This article chooses the Eclipse client-side development platform because RAD has built in the was JRE Runtime library and is prone to conflict with the JAVA JRE runtime, so this article swapped with eclipse to develop the client.
The client's workflow is as follows: Obtain the server-side service description file WSDL, parse the file contents, understand the server-side service information, and call method (Generate client Stub). Writes a client SOAP request message (specifying the method called and the parameters of the call) sent to the server side. Waits for the SOAP response message returned by the server side to parse the resulting return value.
There are a variety of ways to generate client stubs, such as: Axis2, Jax-WS, Xfire, etc., but it is important to note that the various open source software to the SOAP protocol resolution, so the resulting client is not the same. This article uses JAX-WS to generate client stubs with the following steps:
- First confirm that the HelloWorld Service can be accessed from the client machine:
- Http://WEBSERVER:9080/WebProjectDemo/HelloWorldService?
- In Eclipse, create a new Java project–webserviceclient
- Open command Console, Run command:/jdk/bin/wsimport.exe-d C:\WebServiceClient\\bin-s c:\webserviceclient\\src–keep Http://WEBSERVER : 9080/webprojectdemo/helloworldservice?wsdl
- When you refresh Project, you will find some more files in the Src folder, as shown in Figure 5.
Figure 5. Client file structure
- Modify the Helloworldservice.java. Found it
Wsdllocation = "***.wsdl" and url = new URL (baseUrl, "***.wsdl"), replace ***.wsdl with
http://WEBSERVER:9080/WEBPROJECTDEMO/HELLOWORLDSERVICE?WSDL.
- Configuration is complete. Now we can call Stub and server-side communication! New Helloworldclient.java,
Listing 2. Client code
public class Helloworldclient {public static void Main (string[] args) { HelloWorldService service = new Helloworl Dservice (); HelloWorld proxy = Service.gethelloworldport (); System.out.println (Proxy.sayhello ()); }
Running Helloworldclient.java, if the console outputs "Hello World", indicates that the client and server-side communication succeeded.
Https and Web Services
Web Services use the network to transmit data, and data is easily exposed. In this case, we can use the HTTPS protocol to transmit data, establish an information security channel, to ensure the security of data transmission. When the client establishes an HTTPS connection with the server, the client and server need a handshake to complete the authentication and ensure the security of the network communication.
For this, we need to do the corresponding processing in the client code:
- Use the browser to export the server-side certificate and save it as DEMO.CRT. Different browser export steps are not the same, please query the appropriate export method.
- Create Truststore:/java/bin/keytool.exe-genkey-alias mydomain-keyalg Rsa-keystore Clienttruststore.jks on the client
- Add DEMO.CRT to Truststore:/java/bin/keytool.exe-import-trustcacerts-alias storealias-file demo.crt-keystore Client Truststore.jks
- Add the following code to the client Helloworldclient.java:
Listing 3. Https and Web Services
public class Helloworldclient {public static void Main (string[] args) { system.setproperty (" Javax.net.ssl.trustStore "," Path\\clienttruststore.jks "); (truststore) system.setproperty ("Javax.net.ssl.trustStorePassword", "password");//(Truststore password) System.setproperty ("Javax.net.ssl.trustStoreType", "JKS"); (truststore type) helloworldservice service = new HelloWorldService (); HelloWorld proxy = Service.gethelloworldport (); System.out.println (Proxy.sayhello ()); }
The authentication is complete and you can continue the adventure of Web services.
MTOM and Web Services
Let's start by knowing how SOAP transmits data by default:
All binary data in the SOAP message must be present in the XML file in the encoded form (to avoid character collisions). Normal text XML uses Base64 to encode binary data, which requires four characters per three bytes, which increases the size of the data by One-third. If we need to transfer 10M files, the file size is 13M after encoding. In this case, JAVA introduces the MTOM (message transfer optimization mechanism) message encoding. MTOM is an improved approach based on the transmission of SOAP messages. For the transfer of large amounts of data, BASE64 encoding is not performed, but is encapsulated directly in the MIME portion of the SOAP message as the binary raw data of the attachment. The purpose of using MTOM is to optimize the transmission of large binary loads. For smaller binary loads, sending SOAP messages using MTOM can incur significant overhead, but when these loads increase to thousands of bytes, the overhead becomes negligible.
Now, we use the MTOM mechanism to implement a HelloWorld Web Service that provides the ability to upload and download files. First, add upload () and download () Two methods on the server side, and by adding label @MTOM, turn on the MTOM message transfer function on the server side, and select the DataHandler type to encapsulate the transfer file. and use the @XmlMimeType ("Application/octet-stream") to label the DataHandler to indicate that this is an attachment type of binary data.
Listing 4. MTOM Service-side code
@MTOM @WebService public class HelloWorld {private static final String REPOS = "/home/webservicetest"; @WebMethod public String SayHello () {return "Hello world!"; /** * Uploads the file to the Server and is named @fileName */@WebMethod public String upload (@XmlMimeType ("application/o Ctet-stream ") DataHandler handler, String fileName) {try {File file = new file (REPOS +"/"+ file Name); OutputStream output = new Bufferedoutputstream (new FileOutputStream (file)); Handler.writeto (output); Output.close (); } catch (IOException e) {e.printstacktrace (); } return "Success"; /** * Download a file named @fileName from Server */@WebMethod public @XmlMimeType ("Application/octet-stream") DataHandler Download ( String fileName) {datahandler dh = new DataHandler (new Filedatasource (REPOS + "/" + FileName)); return DH; } }
Each time you republish the Web service, you need to rerun Wsimport on the client, keeping the client Stub consistent with the Web service. Now, we're going to upload the Test.txt file to the server by calling HelloWorld's upload () method on the client, and download the file named Wsdemo from the server via download ().
The way clients open MTOM differs from the Server side, see client code.
Listing 5. MTOM Client Code
HelloWorldService service = new HelloWorldService (); HelloWorld proxy = Service.gethelloworldport (new mtomfeature ()); Open MTOM File File = new file (test.txt "); DataHandler datahandler = null; DataHandler = new DataHandler (new Filedatasource (file)); try { //upload Test.txt file to Server and name Wsdemo System.out.println ("Hello World Upload Function:" + Proxy.upload (DataHandler, "Wsdemo")); } catch (Soapfaultexception ex) { System.out.println (ex.getmessage ()); } Download the file Wsdemo and save it locally. DataHandler data = Proxy.download ("Wsdemo"); File Serverfile = new File (". \\data\\server_test.txt");
We use the upload () method to upload 5 files of different sizes (1m,10m,50m,100m,300m) and to count the time it takes to upload them:
Figure 6. Upload () Consumption time statistics
Figure 7. Upload () Consumption time linear graph
As you can see, the time it takes to upload a file increases linearly as the file size grows. and the actual consumption time and expected consumption time (the time of the above 1M file is the benchmark, linear calculation) of the difference is also within the acceptable range. This is entirely in line with our expectations.
Conclusion
This article demonstrates the use of the JAVA Web Services specification JAX-WS to implement WEB services client and server-side communication. Soap Web Services uses HTTP to deliver XML, but because of the limitations of HTTP and the need for additional consumption parsing XML files, SOAP communicates faster than other scenarios. On the other hand, XML is an open, robust, and semantically informative mechanism, and HTTP is a wide range of issues that can be avoided by many firewalls, so that SOAP is widely used. Therefore, if efficiency is an important indicator of a project, you need to consider carefully whether to implement Web Services using SOAP.
Chapter II Development of Web services based on Jax-ws