webService返回自定义类型的数据处理

时间:2023-01-24 19:32:42

1.自定义一个Student 数据类型:

 

package com.chnic.webservice;

import java.io.Serializable;

public class Student implements Serializable {

 private String id;
 private String name;

 public Student() {}

 public Student(String id, String name) {
  super();
  this.id = id;
  this.name = name;
 }

 public String getId() {
  return id;
 }

 public void setId(String id) {
  this.id = id;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }
 
}

2.写Service程序:

package  com.chnic.webservice;   
  
public   class  HelloWorld {   
       
     public  HelloWorld(){} 
    
     public Student getStudentInfo(){
      Student a = new Student("001","noodles");
         return a;
     }
       
}

 

3.将上述文件部署至axis的class目录,并对server-config.wsdd文件进行相关描述:

<deployment  xmlns = "http://xml.apache.org/axis/wsdd/"  
            xmlns:java = "http://xml.apache.org/axis/wsdd/providers/java">
       
     <service   name = "HelloWorld"   provider = "java:RPC">   
     <parameter   name = "className"   value = "com.chnic.webservice.HelloWorld"/>   
     <parameter   name = "allowedMethods"   value = "*"/>   
     <beanMapping qname="myNS:Student" xmlns:myNS="urn:HelloWorld" languageSpecificType="java:com.chnic.webservice.Student"/>
    </service>   
</deployment>

 

4.重启tomcat,清空/tomcat/work,删除server-config.wsdd文件进行重新部署.

   通过http://localhost:8080/axis/servlet/AxisServlet查看所部署的服务.

 

5.客户端写测试:

package  com.chnic.test;   
  
import  java.net.URL;   
import  javax.xml.namespace.QName;   
import  org.apache.axis.client.Call;   
import  org.apache.axis.client.Service;   
import org.apache.axis.encoding.ser.BeanDeserializerFactory;
import org.apache.axis.encoding.ser.BeanSerializerFactory;

import com.chnic.webservice.Student;
  
public   class  Test {    
        
 public   static   void  main(String[] args)  throws  Exception{   
      String targetEendPoint =  "http://localhost:7070/axis/services/HelloWorld" ;   
      Service service =  new  Service();   
      Call call = (Call) service.createCall(); 
     
      QName qn = new QName("urn:HelloWorld","Student");
      call.registerTypeMapping(Student.class, qn,
        new BeanSerializerFactory(Student.class,qn),
        new BeanDeserializerFactory(Student.class,qn));
     
      call.setTargetEndpointAddress( new  URL(targetEendPoint));   
      call.setOperationName( new  QName(targetEendPoint,  "getStudentInfo" ));
      call.setReturnClass(Student.class);
     
      Student s = (Student) call.invoke( new  Object[]{}); 
     
      System.out.println(s.getName()+ " ’s id is: "  + s.getId());  

    }
}