Idea14 生成webservices

一直为idea生成soap协议的webservices而纠结,当初做axis2的时候,用的是eclipse,用它的插件来生成。
这次做短信平台,决定要换一下,因为eclipse用axis2生成的接口,会增加很多无用的东西在WEB-INF下面。
摸索一下,招到了一些方法,这里记录下 。

 


 

配置项目

Idea中,配置项目,最常用的键,就是F4了。打开项目结构(Project Structure),其他配置好,然后在Facets中,增加一个Webservices。
下拉选项中,选择所需要的实现方式即可。我这里这次用的是JAX_WS RI 2.2,是glassfish的产品。
增加后,项目就有了WebServices的功能。
此时,会自动将下载的jar包放入工程,在web.xml中生成JAX-WS的配置信息。同时,也在WEB-INF下生成一个sun-jaxws.xml文件,不过里面目前是空白的,只有一个头。

生成服务类。

在自己的包下面,new一个webservices,然后输入自己的类名称即可,就会生成一个应用主类。例如:

  1. @WebService()
  2. publicclassHelloWorld{
  3. @WebMethod
  4. publicString sayHelloWorldFrom(String from){
  5. String result ="Hello, world, from "+ from;
  6. System.out.println(result);
  7. return result;
  8. }
  9. publicstaticvoid main(String[] argv){
  10. Object implementor =newHelloWorld();
  11. String address ="http://localhost:9000/HelloWorld";
  12. Endpoint.publish(address, implementor);
  13. }
  14. }

同时,在sun-jaxws.xml中,也生成了一段内容,对应刚刚生成的这个服务类。
运行该类,输入address在浏览器,可以看到服务列表,其中有一个http://localhost:9000/HelloWorld?wsdl ,即是提供为其他人的wsdl文件。

客户端验证

至此,我们可以写一个客户端,调用一下即可。具体的写法,可以参照之前本博客记录的一篇日志: JAX_WS 2.2 规范的webservices客户端实现(Axis2,Cxf)

话外篇

当使用这种方式时,有时候需要获取到客户端的ip信息,可以参照以下代码,这里以我发送短信为例:

  1. import com.sun.net.httpserver.HttpExchange;
  2. import com.sun.xml.ws.developer.JAXWSProperties;
  3. import javax.annotation.Resource;
  4. import javax.jws.WebMethod;
  5. import javax.jws.WebService;
  6. import javax.xml.ws.Endpoint;
  7. import javax.xml.ws.WebServiceContext;
  8. import javax.xml.ws.handler.MessageContext;
  9. import java.net.InetSocketAddress;
  10. /*
  11. * Created by wang on 2015/5/8.
  12. */
  13. @WebService()
  14. publicclassSendSms{
  15. @Resource
  16. WebServiceContext webServiceContext;
  17. @WebMethod
  18. publicString sayHelloWorldFrom(String from){
  19. MessageContext mc = webServiceContext.getMessageContext();
  20. HttpExchange exchange =(HttpExchange) mc.get(JAXWSProperties.HTTP_EXCHANGE);
  21. InetSocketAddress remoteAddress = exchange.getRemoteAddress();
  22. String remoteHost = remoteAddress.getHostName();
  23. System.out.println("Client Host name :"+remoteHost);
  24. String result ="Hello, world, from "+ from;
  25. System.out.println(result);
  26. return result+",nice work";
  27. }
  28. publicstaticvoid main(String[] argv){
  29. Object implementor =newSendSms();
  30. String address ="http://localhost:9000/SendSms";
  31. Endpoint.publish(address, implementor);
  32. }
  33. }

这里不要导入错了包,以上代码,有很多个同名的包存在。
好了,所有就这些,用这种方式生成的webservices,简洁了太多,代码简洁,项目结构也简洁,很推荐这种方式。





posted @ 2015-05-08 13:32  薛定谔的猫_  阅读(507)  评论(0编辑  收藏  举报