参考资料:http://www.cnblogs.com/frankliiu-java/articles/1641949.html
使用 CXF 做 webservice 简单例子
一、编写的源文件
----------------------------------------------------------------------------------------------------------------------
package com.demo;
import java.util.List;
import javax.jws.WebService;
import javax.jws.WebParam;
/**服务接口点*/
@WebService
public interface HelloWorld {
String sayHi(@WebParam(name="text")String text);
String sayHiToUser(User user);
String[] SayHiToUserList(List<User> userList);
}
----------------------------------------------------------------------------------------------------------------------
package com.demo;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.jws.WebService;
/**实现服务*/
@WebService(endpointInterface="com.demo.HelloWorld",serviceName="HelloWord")
public class HelloWorldImpl implements HelloWorld {
Map<Integer,User> users = new LinkedHashMap<Integer,User>();
@Override
public String[] SayHiToUserList(List<User> userList) {
// TODO Auto-generated method stub
String[] result = new String[userList.size()];
int i=0;
for(User u:userList){
result[i] = "Hello" + u.getName();
i++;
}
return result;
}
@Override
public String sayHi(String text) {
// TODO Auto-generated method stub
return "Hello"+text;
}
@Override
public String sayHiToUser(User user) {
// TODO Auto-generated method stub
users.put(users.size()+1, user);
return "Hello"+user.getName();
}
}
----------------------------------------------------------------------------------------------------------------------
package com.demo;
public class User {
private String name;
public User(String name) {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
----------------------------------------------------------------------------------------------------------------------
/**webServiceApp类来暴露 web服务*/
public class webServiceApp {
public static void main(String[] args){
System.out.println("web service start");
HelloWorld implementor = new HelloWorldImpl();
String address = "http://localhost:8080/helloWorld";
Endpoint.publish(address,implementor);
System.out.println("web service started");
}
}
----------------------------------------------------------------------------------------------------------------------
二 出现的bug
1.第一个bug:Exception in thread "main" javax.xml.ws.WebServiceException: Unable to create JAXBContext
分析:从控制台提示来看,关键提示是:
Caused by: java.security.PrivilegedActionException: com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException: 1 counts of IllegalAnnotationExceptions
com.demo.User does not have a no-arg default constructor.
仔细检查user.java后,发现构造器有错误。原本是
public User(String name) {
super();
this.name = name;
}
后因只需要空(默认)构造器即可,因此仅删除this.name=name;构造器不符合语法规则,报错。
总结:cxf webservic所使用的object bean 必须要有默认的构造器