1. 新建web工程,写好服务端代码
package service;
import vo.Student;
public class StudentService {
public String sayHello(Student stu) {
System.out.println("hello , " + stu.getName());
return "hello , " + stu.getName();
}
public Student createStudent(int age, String name) {
return new Student(name, age);
}
}
package vo;
public class Student {
private String name;
private int age;
public Student(){
}
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
2. 添加My-Eclipse中JAX-WS自带的library ,操作如下图
3. 使用MyEclipse生成service的代理类和配置文件:
生成的代理类如下:
package service;
import vo.Student;
@javax.jws.WebService(targetNamespace = "http://service.fhpt.com", serviceName = "studentService", portName = "studentService")
public class StudentServiceDelegate {
service.StudentService studentService = new service.StudentService();
public String sayHello(Student stu) {
return studentService.sayHello(stu);
}
public Student createStudent(int age, String name) {
return studentService.createStudent(age, name);
}
}
生成的配如下:Web.xml中生成配置
<listener> <listener-class> com.sun.xml.ws.transport.http.servlet.WSServletContextListener </listener-class> </listener> <servlet> <description>JAX-WS endpoint - studentService</description> <display-name>studentService</display-name> <servlet-name>studentService</servlet-name> <servlet-class> com.sun.xml.ws.transport.http.servlet.WSServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>studentService</servlet-name> <url-pattern>/studentService</url-pattern> </servlet-mapping>
生成新的配置文件sun-jaxws.xml,内容
<?xml version = "1.0"?> <endpoints version="2.0" xmlns="http://java.sun.com/xml/ns/jax-ws/ri/runtime"> <endpoint name="studentService" implementation="service.StudentServiceDelegate" url-pattern="/studentService"> </endpoint> </endpoints>
4. 发布服务端代码到tomcat/webapps下,启动服务, 在IE地址栏输入:
http://localhost:8888/jax-ws-demo/studentService,结果如下:
输入http://localhost:8888/jax-ws-demo/studentService?wsdl , 结果如下:
5. 使用MyEclipse生成客户端代码:
生成客户端代码结构如下图:
6. 写测试代码:
package test;
import com.fhpt.service.Student;
import com.fhpt.service.StudentService;
import com.fhpt.service.StudentServiceDelegate;
public class ClientTest {
public static void main(String[] args) {
StudentServiceDelegate stuService =new StudentService().getStudentService();
Student stu=new Student();
stu.setAge(27);
stu.setName("pengcc");
String returnValue=stuService.sayHello(stu);
System.out.println(returnValue);
Student stu2=stuService.createStudent(26, "pengcc1985");
System.out.println(stu2);
System.out.println(stu2.getAge());
System.out.println(stu2.getName());
}
}
运行结果:
hello , pengcc
com.fhpt.service.Student@467991
26
pengcc1985