使用jdk自带webservice发布webservice

来源:互联网 发布:淘宝店铺商品价格设置 编辑:程序博客网 时间:2024/05/17 22:50

        在java平台里发布webservice的框架有很多,比如CXF、XFire、Axis,用起来也很简单,也能和Spring进行很好的整合。但是鄙人最讨厌引入一大堆jar包,好在JDK1.6以上的版本自带了webservice功能,于是研究了一番,简单的入门例子网上很多,但是上传附件的资料却很少,这里写个稍微复杂的,可以使用webservice上传附件。废话少说,步骤如下:

        1、编写接口,代码如:

              @WebService(targetNamespace="http://com.gcms.webservices/", name="PubContent")
              @MTOM
              public interface PubContent {
                  /**
                    * 发布内容
                    * @param bean:内容对象
                    * @param attachment:附件
                    * @return
                   */
                   public Integer releaseContent(@WebParam(name="bean") Content bean, 

                                                                          @WebParam(name="attachments")  Attachment attachment);
              }

             这里参数Content是个复杂类型,代码如:

             @XmlRootElement(name = "GboatContent")
             public class Content implements Serializable{
                      private static final long serialVersionUID = -451646744964433772L;
                      /**
                      * 内容ID
                      */
                      private Integer id;
                      /**
                      * 具体内容
                      */
                      private String content;
                      public Integer getId() {
                      return id;
                      }
                      public void setId(Integer id) {
                      this.id = id;
                      }
                      public String getContent() {
                           return content;
                      }
                      public void setContent(String content) {
                      this.content = content;
                      }
          }

        注意,上边的@XmlRootElement(name = "Content")其实可以不加,但是加了以后的好处是,可以给用户提供基于XML参数的webservice,这样就能使用JDK自带的JAXB来将XML转换为java对象,否则的话得引XStream等框架,我是很讨厌乱引入的,所以就使用加注解的方式。

        Attachment,这个对象是附件对象,代码如下:

        @XmlAccessorType(XmlAccessType.FIELD)
        public class Attachment implements Serializable {
         private static final long serialVersionUID = -3444332170760626140L;
         /**
         * 附件的名称
         */
         private String name;
         /**
         * 附件的类型,或者说是后缀,比如.pdf、.png等等
         */
         private String type;
         /**
         * 数据处理类,使用MTOM必须要使用的类
         */
         @XmlMimeType(("application/octet-stream"))
         private DataHandler dataHandler;
                public String getName() {
                        return name;
                }
                 public void setName(String name) {
                          this.name = name;
                 }
                 public String getType() {
                          return type;
                }
                 public void setType(String type) {
                          this.type = type;
                 }
                 public DataHandler getDataHandler() {
                           return dataHandler;
                  }
                  public void setDataHandler(DataHandler dataHandler) {
                           this.dataHandler = dataHandler;
                 }
        }

   2、接口实现类代码如:

          @WebService(targetNamespace="http://com.gcms.webservices/", name="PubContent")
          @Service
          public class PubContentImpl implements PubContent,{

              @Override
              public Integer releaseContent(Content bean, Attachment attachment) {
                       System.out.println("内容是: " + bean.getContent());

                       // 操作附件:

                       try {
                            String name = attachment.getName();
                            String type = attachment.getType();
                            InputStream inputStream = attachment.getDataHandler().getInputStream();
                            String fileFullPath = “D:\\test\" + name + "." + type;
                            OutputStream outputStream = new FileOutputStream(fileFullPath);
                            byte[] bytes = new byte[1024];
                            int i;
                            while((i = inputStream.read(bytes)) != -1) {
                                 outputStream.write(bytes, 0, i);
                            }
                            outputStream.close();
                            inputStream.close();

                            } catch (IOException e) {
                                   e.printStackTrace();
                            }

                      }

                     return 1;
           }

          3、发布webservice,这个非常简单:

               // 如果使用的是Spring,这句代码则可以放在init-method方法里,也不用new PubContentImpl ,而是直接从Spring容器中取出来也行。

               Endpoint.publish("http://localhost:9000/pubcontext", new PubContentImpl () ); 

          4、客户端测试,先使用eclipse的工具生成客户端代理,也可以使用java自带的wsdl2java生成webservice客户端代理(和在eclipse中生成的不同),一般如下:

             public class ClintTest {
                   public static void main(String[] args) {
                         PubContentImplServiceLocator service = new PubContentImplServiceLocator();
                         try {
                             PubContent pub = service.getPubContentPort();
                                 Attachment atta = new Attachment();
                                 atta.setName("附件1");
                                 atta.setType("rar");
                                 atta.setDataHandler(readFile("D:\\test.rar"));
                                 Content content = new Content();
                                 content.setContent("测试内容");
                                 Integer id = pub.releaseContent(content, atta);
                                 System.out.println("id is: " + id);
                          } catch (ServiceException e) {
                                 e.printStackTrace();
                          } catch (IOException e) {
                                 e.printStackTrace();
                          }
             }
   
             public static byte[] readFile(String filePath) throws IOException{
                 File file = new File(filePath);  
                 long fileSize = file.length();  
                 if (fileSize > Integer.MAX_VALUE) {  
                     System.out.println("file too big...");  
                   return null;  
                 }  
                 FileInputStream fi = new FileInputStream(file);  
                byte[] buffer = new byte[(int) fileSize];  
                int offset = 0;  
                int numRead = 0;  
                while (offset < buffer.length  && (numRead = fi.read(buffer, offset, buffer.length - offset)) >= 0)  {  
                    offset += numRead;  
                 }  
                // 确保所有数据均被读取  
                 if (offset != buffer.length) {  
                      throw new IOException("Could not completely read file "  +  file.getName());  
                  }  
                 fi.close();            
                return buffer;
            }
    }

    以上各种Java注解的意义这里就不说了,以后专门写个博客说明吧,大家也可以查资料自己搞明白。

0 0
原创粉丝点击