[b]接口[/b]
[b]实现类[/b]
[b]服务端开启服务[/b]
[b]客户端通过wsimport命令将wsdl转换为本地java文件[/b]
package com.hqh.soap;
import java.util.List;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
//如果要指定命名空间,那么接口与实现类要显示定义相同的targetNamespace!
@WebService
public interface IMyService {
//服务端可能会抛出Exception,客户端调用如果出错则抛出异常
@WebResult(name="user")
public User login(@WebParam(name="username")String username,
@WebParam(name="pwd")String pwd) throws UserException;
}
[b]实现类[/b]
package com.hqh.soap;
import java.util.ArrayList;
import java.util.List;
import javax.jws.WebService;
@WebService(endpointInterface="com.hqh.soap.IMyService")
public class MyServiceImpl implements IMyService {
private static List<User> users = new ArrayList<User>();
public MyServiceImpl() {
users.add(new User(1,"admin","admin"));
}
@Override
public User login(String username, String pwd) throws UserException {
for(User user:users) {
if(username.equals(user.getName()) && pwd.equals(user.getPwd()))
return user;
}
//这里抛出的异常类型如果与接口中声明的异常类型一致,那么服务端将不抛出此异常,而是直接通过soap message将异常传递到客户端
throw new UserException("用户不存在");
//抛出运行时异常与接口声明的异常不同,服务端会自己抛出异常,客户端也能接收到异常信息
// throw new RuntimeException("用户不存在");
}
}
[b]服务端开启服务[/b]
package com.hqh.soap;
import javax.xml.ws.Endpoint;
public class MyServer {
public static void main(String[] args) {
String address = "http://localhost:8888/ms";
IMyService implementor = new MyServiceImpl();
Endpoint.publish(address, implementor);
}
}
[b]客户端通过wsimport命令将wsdl转换为本地java文件[/b]
package com.hqh.soap.test;
import static org.junit.Assert.*;
import com.hqh.soap.IMyService;
import com.hqh.soap.MyServiceImplService;
import com.hqh.soap.UserException_Exception;
public class Test {
@org.junit.Test
public void test() {
MyServiceImplService serviceImpl = new MyServiceImplService();
//获取服务接口
IMyService service = serviceImpl.getMyServiceImplPort();
try {
service.login("za", "123");
} catch (UserException_Exception e) {
//e.printStackTrace();
System.out.println(e.getMessage());
} catch (Exception e) {
e.printStackTrace();
}
}
}