在开发java WebSerivce的时候,有时候会想到XFire,AXIS.其实也可以用JAVA自带的JAX-WS也可以做到的。
比如,你可以写个简单的例子
package com.java.ws.app;
import javax.jws.WebService;
@WebService
public interface Calculator {
public int add(int a, int b);
public int multi(int a, int b);
}
package com.java.ws.app;
import javax.jws.WebService;
@WebService(endpointInterface = "com.java.ws.app.Calculator", serviceName = "CaculatorSemsService", targetNamespace="http://com.test.app/")
public class CalculatorImpl implements Calculator {
public int add(int a, int b) {
return a + b;
}
public int multi(int a, int b) {
return a * b;
}
public int minus(int a, int b) {
return a - b;
}
}
package com.java.ws.app;
import javax.xml.ws.Endpoint;
public class Server {
public static void main(String[] args) {
Endpoint.publish("http://localhost:8088/calculator",
new CalculatorImpl());
}
在浏览器中输入http://localhost:8088/calculator?wsdl,如果出现XML格式的字串,说明配置正确,截图如下所示:
package com.java.ws.app;
import javax.jws.WebService;
@WebService
public interface Calculator {
public int add(int a, int b);
public int multi(int a, int b);
}
package com.ws.app;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import com.java.ws.app.Calculator;
public class TestClient {
public static void main(String[] args) {
URL url = null;
try {
url = new URL("http://localhost:8087/calculator?wsdl");
} catch (MalformedURLException e) {
e.printStackTrace();
}
QName qName = new QName("http://com.test.app/", "CaculatorSemsService");
//根据targetNamespace,serverName来查找服务
Service service = Service.create(url, qName);
Calculator port = service.getPort(Calculator.class);
System.out.println("client22 :\t" + port.add(1, 2));
}
}
命令如下所示:
根据wsdl生成代码和文件
wsimport -keep http://localhost:8088/calculator?wsdl
接下来,我们只要书写几行代码,即可,如下所示:
package client;
import app.test.com.CaculatorSemsService;
import app.test.com.Calculator;
public class TestClient {
public static void main(String[] args) {
CaculatorSemsService service = new CaculatorSemsService();
Calculator calculator = service.getCalculatorImplPort();
System.out.println(calculator.add(1, 2));
}
}
通过wsgen生成wsdl
如下所示:
package net.oseye;
import javax.jws.WebMethod;
import javax.jws.WebService;
@WebService
public class Hello {
@WebMethod
public String SayHello(String name){
return String.format("Hello,%s",name);
}
}
wsgen -cp ./bin -r ./wsdl -s ./src ./bin -wsdl net.oseye.Hello
这样会生成一堆文件,截图如下所示:
将wsdl文件夹拷贝到tomcat webapps指定的项目目录下,即可完成和tomcat服务器的整合。
也可以通过XML配置文件,进行整合,代码如下所示:
记得要引入CXF框架
org.apache.cxf
cxf
2.4.6
jar
compile
org.apache.geronimo.specs
geronimo-activation_1.1_spec
1.1
org.apache.geronimo.specs
geronimo-annotation_1.0_spec
1.1.1
org.apache.geronimo.specs
geronimo-javamail_1.4_spec
1.7.1
org.apache.geronimo.specs
geronimo-ws-metadata_2.0_spec
1.1.3
org.apache.neethi
neethi
3.0.1
org.mortbay.jetty
jetty-util
6.1.26
org.codehaus.woodstox
stax2-api
3.1.1
org.apache.ws.xmlschema
xmlschema-core
2.0.1
net.sf.morph
morph
1.1.1