1. 添加cxf.jar 包(集成了Spring.jar、servlet.jar ),spring.jar包 ,servlet.jar 包。
2. 編寫業務類,通過CXF來發布webservice
3. 添加一個CXF請求的 Servlet,用來處理webservice的請求 。過濾的地址例如:/ws/*
4. 配置Spring的配置文件: applicationContext.xml ,把cxf的bean在spring配置 。
5. 在web.xml中配置 CXF的 Servlet , 添加spring的監聽 。
6. 通過wsimport生成本地代理 ,訪問webservice 。
下面舉個例子,向外暴露StudentInter接口,裏面有獲取學生和添加學生的方法:
1、引入CXF的jar包,這裏把Spring和Servlet相關的去取,因爲Spring的我自己加,Servlet的我myEclipse會自動添加。
2、創建暴露出去的接口類(服務類),並添加@webServer註釋:
//通過註釋更改server的名稱,如果不改,也要添加@WebService此註釋,不然發佈失敗
@WebService(serviceName="StudentManager")
public interface StudentInter {
//獲取學生
public abstract Student getStudent(int num);
//添加學生
public abstract void addStudent(Student student);
}
3、實現該接口的類(服務的實現類):
public class StudentManagerImpl implements StudentInter {
//爲了測試添加的數據
private static List<Student> list = null;
static {
list = new ArrayList<Student>();
list.add(new Student(0, "lmk0"));
list.add(new Student(1, "lmk1"));
list.add(new Student(2, "lmk2"));
}
@Override
public Student getStudent(int num) {
return list.get(num);
}
@Override
public void addStudent(Student student) {
list.add(student);
}
}
4、添加Spring相應的jar包
添加cxf的語言格式:
配置bean:
<!-- CXF的配置:
address:
地址:http://192.168.114.10:8080/CXF_Server/ws/studentManager
組成說明:http://192.168.114.10:8080 +CXF_Server( 項目名)+ws(過濾的路徑)+/studentManager(自定義部分)。
serviceClass:暴露出去的接口(服務類)。
serviceBean:服務的實現類。
inInterceptors/outInterceptors:有人用到這個服務時候打印的log
-->
<jaxws:server address="/studentManager" serviceClass="com.lmk.service.inter.StudentInter">
<jaxws:serviceBean>
<ref bean="studentManagerImpl" />
</jaxws:serviceBean>
<jaxws:inInterceptors>
<bean class="org.apache.cxf.interceptor.LoggingInInterceptor"/>
</jaxws:inInterceptors>
<jaxws:outInterceptors>
<bean class="org.apache.cxf.interceptor.LoggingOutInterceptor"/>
</jaxws:outInterceptors>
</jaxws:server>
5、web.xml的配置:
<!-- cxf的Servlet攔截器 -->
<servlet>
<servlet-name>cxf</servlet-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>cxf</servlet-name>
<!-- 攔截地址,是wsdl文件地址的組成一部分 -->
<url-pattern>/ws/*</url-pattern>
</servlet-mapping>
<!-- 初始化Spring -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
6、發佈完成後運行tomcat,輸入http://localhost:8080/CXF_Server/ws
測試部分(你可以用myEclipse自帶的webServer瀏覽器,這裏是用生成本地代理的方式測試):
1、在cmd命令窗口中輸入以下代碼,生成class字節碼:wsimport ./ http://localhost:8080/CXF_Server/ws/studentManager?wsdl
2、把字節碼打成jar包: jar cvf jobService.jar xx(剛纔的字節碼文件地址)
3、新建項目,把以上jar包放入項目中,編寫以下代碼,測試:
public static void main(String[] args) {
//獲取服務
StudentManager sm=new StudentManager();
//獲取服務的實現類
StudentInter studentInterPort = sm.getStudentInterPort();
//調用實現的方法
Student student = studentInterPort.getStudent(0);
System.out.println(student.getName());
}