使用的JDK1.7(1.6之后的就行,具体哪个版本可以,不了解)
1.定义接口和实现类
接口:
public interface IHello {
public String hello(String name);
}
实现类:
@WebService(targetNamespace=”http://com.webservice”)
public class Hello implements IHello {
@WebMethod
public String hello(String name) {
return name + ",你好";
}
public static void main(String[] args) {
Endpoint en = Endpoint.publish("http://localhost:8080/webservice", new Hello()) ;
}
}
(解释1)
/**
targetNamespace=”http://com.webservice” :
在用命令生成客户端代码时,
会自动在 cmd的执行命令目录下 生成webservice/com/java and .class
生成的包目录和定义的是相反的
*/
(解释2)Endpoint en = Endpoint.publish(“http://localhost:8080/webservice“, new Hello()) ;
为发布webservice,资源是Hello,其中的webservice为自定义
2.查看webservice是否发布
运行上面的main方法后,在浏览器下输入http://localhost:8080/webservice?wsdl(main方法中发布的)
如下图:
3.生成客户端代码
(1)
在cmd输入上述命令:wsimport -keep http://localhost:8080/webservice?wsdl
编译成功会在E盘(我是在E盘路径执行的命令)下生成webservice.com.*.java等代码
(2)
把生成的代码copy到你的客户端
这里确保你工程的包名要和你定义的包名一致
例如你定义的:(@WebService(targetNamespace=”http://com.webservice”) )
你工程的是:webservice.com 这就没问题
(3)
如果你的包名改了别的,就会有问题。
因为生成的客户端代码是基于定义的包路径的
如下图代码生成的Hello:
或者你把所有的类文件设计到包路径的地方都修改了(没试过)
4.客户端测试
public class Test3 {
public static void main(String[] args) {
HelloService service = new HelloService() ;
Hello hello = service.getHelloPort() ;
System.out.println(hello.hello("周星驰"));
}
}
成功输出 周星驰,你好
5.
上述测试基于main方法,如果要在web工程启动的时候,就启动webservice,则需要下面的步骤
(1)web.xml添加监听
<listener>
<listener-class>
org.jboss.resteasy.plugins.guice.GuiceResteasyBootstrapServletContextListener
</listener-class>
</listener>
<listener>
<listener-class>ench.cng.agent.listen.ConfigListener</listener-class>
</listener>
第一个listener是jboss的
第二个listener是我们自定义的执行发布webservice的servlet
(2)ConfigListener(servlet)的编写
public class ConfigListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent arg0) {
try{
Endpoint en = Endpoint.publish(“http://localhost:8080/webservice“, new Hello()) ;
}catch(Exception e){
e.printStackTrace();
}finally{
}
}
}
web工程启动的时候 应该就可以了