只贴出服务端代码
1.Service接口类
package com.test.hello; import java.util.Map; import javax.jws.WebService; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import com.test.util.MineAdapter; @WebService public interface HelloWorld { // public void sayHello(); //cxf 不能处理 map 类型,于是我们采用MineAdapter.class进行处理 public @XmlJavaTypeAdapter(MineAdapter.class) Map<String,Cat> getMap(); }
2.服务实现类
package com.test.hello; import java.util.HashMap; import java.util.Map; import javax.jws.WebService; @WebService(endpointInterface="com.test.hello.HelloWorld",serviceName="HelloWorldWS") public class HelloWorldImpl implements HelloWorld{ private static Map<String,Cat> map; static { map = new HashMap<String, Cat>(); map.put("tomcat", new Cat()); map.put("garfield", new Cat()); } public Map<String,Cat> getMap() { return map; } }
Cat类
package com.test.hello; public class Cat { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }
StringCat
package com.test.util; import java.util.ArrayList; import java.util.List; import com.test.hello.Cat; public class StringCat { public static class Entry { private String key; private Cat value; public Entry(String key, Cat value) { this.key=key; this.value=value; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public Cat getValue() { return value; } public void setValue(Cat value) { this.value = value; } } private List<Entry> entries = new ArrayList<StringCat.Entry>(); public List<Entry> getEntries() { return entries; } public void setEntries(List<Entry> entries) { this.entries = entries; } @Override public String toString() { StringBuilder str = null; for (Entry entry : entries) { str.append(entry.getKey() +" : "+entry.getValue()); } return str.toString(); } }
这是重点,适配器类
package com.test.util; import java.util.HashMap; import java.util.Map; import javax.xml.bind.annotation.adapters.XmlAdapter; import com.test.hello.Cat; import com.test.util.StringCat.Entry; //改转换器就负责完成StringCat与Map的相互转换 public class MineAdapter extends XmlAdapter<StringCat, Map<String,Cat>>{ @Override public Map unmarshal(StringCat strngCat) throws Exception { Map result = new HashMap(); for(Entry entry : strngCat.getEntries()){ result.put(entry.getKey(),entry.getValue()); } return result; } @Override public StringCat marshal(Map<String,Cat> map) throws Exception { StringCat stringCat = new StringCat(); for (String key : map.keySet()) { stringCat.getEntries().add(new Entry(key,map.get(key))); } return stringCat; } }
最后是运行类
package com.test.hello; import javax.xml.ws.Endpoint; public class ServerMain { public static void main(String[] args) { HelloWorld helloWorldImpl = new HelloWorldImpl(); Endpoint.publish("http://localhost:1234/ws", helloWorldImpl); System.out.println("webservice 暴露成功"); } }