Saturday, December 26, 2009

Tạo Web services với JAX-WS 2.0 và Java SE 6 Platform

Phần 1: tạo Web Service và publish nó

Tạo lớp .java với nội dung

package hello;

import javax.jws.WebService;

@WebService

public class CircleFunctions {
public double getArea(double r) {
return java.lang.Math.PI * (r * r);
}

public double getCircumference(double r) {
return 2 * java.lang.Math.PI * r;
}
}

Chúng ta có thể dùng phương thức publish() của lớp javax.xml.ws.Endpoint để publish lớp vừa tạo thành 1 web service trong context root được chỉ định. Ở đây ta tạo lớp PubWS.java có nội dung sau:

package hello;
import javax.xml.ws.Endpoint;
public class PubWS{
public static void main(String[] args) {
Endpoint.publish(
"http://localhost:8080/WebServiceExample/circlefunctions",
new CircleFunctions());
}
}

Bây giờ ta hãy compile source code bằng lệnh sau
javac -d . *.java

Phải đảm bảo rằng không có lỗi nào xảy ra.

Sau đó ta dùng tool wsgen để sinh ra các lớp hỗ trợ cho việc tạo webservice cũng như sinh WSDL file đồng thời public lên Web Server, cú pháp như sau:
wsgen -cp . hello.CircleFunctions

Bây giờ ta có thể public webservice bằng cách thự thi lệnh sau:
java hello.PubWS

Như vậy ta đang có 1 webservice đang được thực thi trên web server.
Mở trình duyệt, duyệt đến địa chỉ http://localhost:8080/WebServiceExample/circlefunctions?WSDL ta sẽ có kết quả như hình:
Ws_J2SE



Và, chúng ta có thể viết client ứng dụng web service này được rồi đó!
Phần 2: Tạo client

1. Tạo thư mục client, mở cửa sổ command, chạy lệnh sau để sinh ra các lớp đặc tả dịch vụ web service từ WSDL URL
wsimport http://localhost:8080/WebServiceExample/circlefunctions?WSDL

2. Tạo lớp client với nội dung sau

import hello.*;
import javax.xml.ws.WebServiceRef;
public class Client{
@WebServiceRef(wsdlLocation = "http://localhost:8080/WebServiceExample/circlefunctions?WSDL")
public static void main(String[] args){
Client client = new Client();
client.test();
}
public void test(){
try{
CircleFunctionsService service=new CircleFunctionsService();
CircleFunctions port =service.getCircleFunctionsPort();
double ret =port.getArea(3.0d);
System.out.println("Area result = " + ret);
}catch(Exception e){
e.printStackTrace();
}
}
}

3. Biên dịch file Client.java bằng lệnh sau
javac Client.java

Bạn chắc là không có lỗi nào xảy ra chứ?
4. Thực thi ứng dụng
java Client

Kết quả thu được của bạn như sau
D:\Bai giang Aptech\Aptech – Semester 4\XML Webservices with Java\examples\ex03_
JAX_WS\client>java Client
Area result = 28.274333882308138

D:\Bai giang Aptech\Aptech – Semester 4\XML Webservices with Java\examples\ex03_
JAX_WS\client>pause
Press any key to continue . . .
Chúc thành công!

No comments:

Post a Comment