apache-cxf-3.1.6(webService介面開發maven)
1 結構圖
2 jar包
pom.xml
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-core</artifactId>
<version>3.1.5</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId>
<version>3.1.5</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http-jetty</artifactId>
<version>3.1.5</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
3 介面
@WebService
public interface HelloWorld {
public String say(String str);
public List<Role> getRoleByUser(User user);
}
4 介面 實現類
@WebService
public class HelloWorldImpl implements HelloWorld {
public String say(String str) {
String aa = "error";
if ("abc".equals(str)) {
aa="success";
}else{
aa="error";
}
return aa;
}
public List<Role> getRoleByUser(User user) {
List<Role> roleList=new ArrayList<Role>();
// 模擬 直接寫死
if(user!=null){
if(user.getUserName().equals("admin") && user.getPassword().equals("123")){
roleList.add(new Role(1,"總監"));
roleList.add(new Role(2,"架構師"));
}else if(user.getUserName().equals("dt") && user.getPassword().equals("123")){
roleList.add(new Role(3,"程式設計師"));
}else {
roleList.add(new Role(4,"許可權錯誤"));
}
return roleList;
}else{
return null;
}
}
}
5 啟動伺服器介面
/////////////////////////////////////////////////////////////////////////////////////////////////客戶端方法一 自動生成客戶端
/////////////////////////////////////////////////////////////////////////////////////////////////客戶端方法二 非自動生成客戶端
import java.util.List;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import com.dt.setrvice.HelloWorld;
import com.dt.setrvice.HelloWorldService;
import com.dt.setrvice.Role;
import com.dt.setrvice.User;
public class Client {
public static void main(String[] args) {
/* 自動生成呼叫 */
HelloWorldService service=new HelloWorldService();
HelloWorld helloWorld=service.getHelloWorldPort();
System.out.println(helloWorld.say("abc"));
User user=new User();
user.setUserName("jack");
user.setPassword("123456");
List<Role> roleList=helloWorld.getRoleByUser(user);
for(Role role:roleList){
System.out.println(role.getId()+","+role.getRoleName());
}
//////////////////////////////////////
/* 非自動生成呼叫 */
JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
org.apache.cxf.endpoint.Client client = dcf.createClient("http://192.168.1.102:8888/helloWorld?wsdl");
try {
User user2=new User();
user2.setUserName("admin");
user2.setPassword("123");
Object[] objects = client.invoke("say", "aee"); // client.invoke("方法名稱", "要傳遞的引數");
Object[] objects2 = client.invoke("getRoleByUser", user2);
List<Role> aa= (List<Role>)objects2[0];
System.out.println(aa);
for(Role role:aa){
System.out.println(role.getId()+","+role.getRoleName());
}
//輸出呼叫結果
//System.out.println(objects[0].toString());
//System.out.println(objects2[0].toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}