SSM项目中整合WebService
先了解一下WebService的一些相關(guān)術(shù)語吧:
WebService:
WebService是一種跨編程語言和跨操作系統(tǒng)平臺(tái)的遠(yuǎn)程調(diào)用技術(shù)。
WSDL(web service definition language):
WSDL是webservice定義語言, 對(duì)應(yīng).wsdl文檔, 一個(gè)webservice會(huì)對(duì)應(yīng)一個(gè)唯一的wsdl文檔, 定義了客戶端與服務(wù)端發(fā)送請(qǐng)求和響應(yīng)的數(shù)據(jù)格式和過程
SOAP(simple object access protocal):
SOAP是"簡單對(duì)象訪問協(xié)議"
是一種簡單的、基于HTTP和XML的協(xié)議, 用于在WEB上交換結(jié)構(gòu)化的數(shù)據(jù)
soap消息:請(qǐng)求消息和響應(yīng)消息
SEI(WebService EndPoint Interface):
SEI是web service的終端接口,就是WebService服務(wù)器端用來處理請(qǐng)求的接口
CXF(Celtix + XFire):
一個(gè)apache的用于開發(fā)webservice服務(wù)器端和客戶端的框架。
本次采用的就是CXF框架來整合,
首先引入相關(guān)的pom包:
<!-- webservice --><dependency><groupId>org.apache.cxf</groupId><artifactId>cxf-rt-frontend-jaxws</artifactId><version>${cxf.version}</version></dependency><dependency><groupId>org.apache.cxf</groupId><artifactId>cxf-rt-transports-http</artifactId><version>${cxf.version}</version></dependency>由于版本的沖突,我將spring的版本調(diào)了,并且由于cglib包中的asm包和cxf框架中的asm包有沖突,我做了以下更改:
<!-- spring版本號(hào) --><spring.version>4.1.9.RELEASE</spring.version><dependency><groupId>cglib</groupId><artifactId>cglib</artifactId><version>3.2.5</version><exclusions><exclusion><groupId>org.ow2.asm</groupId><artifactId>asm</artifactId></exclusion></exclusions></dependency>
2. 接著引入spring-context-webservice.xml和cxf-config.xml:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:cxf="http://cxf.apache.org/core"xmlns:jaxws="http://cxf.apache.org/jaxws"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsdhttp://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd"><import resource="cxf-config.xml"/> </beans><?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxws="http://cxf.apache.org/jaxws"xmlns:context="http://www.springframework.org/schema/context"xmlns:jaxrs="http://cxf.apache.org/jaxrs"xsi:schemaLocation="http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsdhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsdhttp://cxf.apache.org/jaxrshttp://cxf.apache.org/schemas/jaxrs.xsd"><import resource="classpath*:META-INF/cxf/cxf.xml" /><import resource="classpath*:META-INF/cxf/cxf-extension-soap.xml" /><import resource="classpath*:META-INF/cxf/cxf-servlet.xml" /><!-- id 不能重復(fù) --><jaxws:endpoint id="servicemanWebService" implementor="clack.webserviceImp.ServicemanWebServiceImp" address="/servicemanws" /> <!-- <jaxrs:server id="restContainer" address="/"><jaxrs:serviceBeans><ref bean="roomService" /></jaxrs:serviceBeans><jaxrs:providers><bean class="org.codehaus.jackson.jaxrs.JacksonJaxbJsonProvider" /></jaxrs:providers><jaxrs:extensionMappings><entry key="json" value="application/json" /><entry key="xml" value="application/xml" /></jaxrs:extensionMappings></jaxrs:server> --></beans>
其中<jaxws:endpoint id="servicemanWebService" implementor="clack.webserviceImp.ServicemanWebServiceImp" address="/servicemanws" />
中的設(shè)置后續(xù)會(huì)用到。
3. 更改相應(yīng)的web.xml加載順序并加入cxf配置(反正是先加載spring,后加載springmvc) <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"><display-name>Archetype Created Web Application</display-name><context-param><param-name>contextConfigLocation</param-name><param-value>classpath:spring-context*.xml</param-value></context-param> <listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><listener><listener-class>org.springframework.web.context.request.RequestContextListener</listener-class></listener><!-- ================配置SpringMVC核心調(diào)度器================ --><!-- 不指定具體文件的話,默認(rèn)為"/WEB-INF/<servlet name>-servlet.xml" --><!-- load-on-startup代表啟動(dòng)順序,設(shè)置為大于等于0表示容器在應(yīng)用啟動(dòng)時(shí)就加載并初始化這個(gè)servlet --><!-- 推薦攔截/,風(fēng)格優(yōu)雅 --><servlet><servlet-name>SpringMVC</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><init-param><param-name>contextConfigLocation</param-name><param-value>classpath*:spring-mvc.xml</param-value></init-param><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>SpringMVC</servlet-name><url-pattern>/</url-pattern></servlet-mapping><servlet><servlet-name>CXFServlet</servlet-name><servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>CXFServlet</servlet-name><url-pattern>/ws/*</url-pattern></servlet-mapping> </web-app>
4. 接著添加一個(gè)工具類用于調(diào)出springmvc中加載的service注解
package clack.utils;import java.util.Enumeration; import javax.servlet.ServletContext;import org.springframework.web.context.ContextLoader; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils;public class ContextUtils {public static WebApplicationContext getSpringMVCContext() {WebApplicationContext rootWac = ContextLoader.getCurrentWebApplicationContext();// 獲取servletContextSystem.out.println(rootWac+"ddddd");ServletContext servletContext = rootWac.getServletContext();// 獲取子容器,名字最后對(duì)應(yīng)servlet名字//1.查看spring容器中的對(duì)象名稱String[] beannames = rootWac.getBeanDefinitionNames();for(String beanname:beannames){System.out.println(beanname);}System.out.println(servletContext);//2.查看servlet中容器列表Enumeration<String> servletnames = servletContext.getAttributeNames();while(servletnames.hasMoreElements()){System.out.println(servletnames.nextElement());}WebApplicationContext springmvc = WebApplicationContextUtils.getWebApplicationContext(servletContext,"org.springframework.web.servlet.FrameworkServlet.CONTEXT.SpringMVC");//System.out.println(springmvc+"eee");return springmvc;}}5. 準(zhǔn)備工作就緒后就建立webservice接口和webservice實(shí)現(xiàn)類:
package clack.webservice;import java.util.List;import javax.jws.WebMethod; import javax.jws.WebService;import clack.entity.Serviceman;@WebService public interface ServicemanWebService {//使用@WebMethod注解標(biāo)注WebServiceI接口中的方法@WebMethodList<Serviceman> getAllServiceman() throws Exception; }其中使用的 getAllServiceman()方法是本身的service中的方法調(diào)用。
package clack.webserviceImp;import java.util.List;import javax.jws.WebService;import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component;import clack.entity.Serviceman; import clack.service.ServicemanService; import clack.utils.ContextUtils; import clack.webservice.ServicemanWebService; //endpointInterface 編寫實(shí)現(xiàn)接口類名 service name 網(wǎng)絡(luò)訪問的名字 對(duì)應(yīng)<wsdl:service name="studentws"> @Component("servicemanWebService") @WebService(endpointInterface = "clack.webservice.ServicemanWebService", serviceName = "servicemanws") public class ServicemanWebServiceImp implements ServicemanWebService{@Autowiredprivate ServicemanService servicemanService;public ServicemanService getServicemanService() {return servicemanService;}public void setServicemanService(ServicemanService servicemanService) {this.servicemanService = servicemanService;}@Overridepublic List<Serviceman> getAllServiceman() throws Exception {// TODO Auto-generated method stubservicemanService = (ServicemanService)ContextUtils.getSpringMVCContext().getBean("servicemanService");List<Serviceman> servicemans = servicemanService.getAllServiceman();return servicemans;}}理清其中注解的對(duì)應(yīng)關(guān)系后問題不大,
啟動(dòng)項(xiàng)目,輸入地址:http://localhost:8080/StudyMaven1/ws/servicemanws?wsdl
?
?
?
?
?
?測試:
建立一個(gè)簡單的maven項(xiàng)目并導(dǎo)入相關(guān)的cxf包:
?
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>clack</groupId><artifactId>MyWebService</artifactId><version>0.0.1-SNAPSHOT</version><properties><cxf.version>2.2.3</cxf.version></properties><dependencies><!-- webservice --><dependency><groupId>org.apache.cxf</groupId><artifactId>cxf-rt-frontend-jaxws</artifactId><version>${cxf.version}</version></dependency><dependency><groupId>org.apache.cxf</groupId><artifactId>cxf-rt-transports-http</artifactId><version>${cxf.version}</version></dependency></dependencies><build><defaultGoal>compile</defaultGoal><finalName>MyWebService</finalName><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>3.1</version><configuration><source>1.8</source><target>1.8</target><encoding>utf-8</encoding></configuration></plugin><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-resources-plugin</artifactId><version>2.6</version><configuration><failOnMissingWebXml>false</failOnMissingWebXml></configuration></plugin></plugins><resources><!--編譯之后包含xml --><resource><directory>src/main/java</directory><includes><include>**/*.xml</include></includes></resource><resource><directory>src/main/resources</directory><includes><include>**/*</include></includes></resource></resources></build> </project>?
2. 使用了一個(gè)插件生成相關(guān)的文件 apache-cxf-3.2.7
3. 將所得的文件拷入maven項(xiàng)目中,并新建一個(gè)測試類測試是否能取得數(shù)據(jù):
目錄樹如下:
其中WebServiceApp是測試類:
package clack.webserviceimp;import java.net.URL; import java.util.List;import javax.xml.namespace.QName; import javax.xml.ws.Service;import org.apache.cxf.endpoint.Client; import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;import clack.webservice.Serviceman; import clack.webservice.ServicemanWebService;/*** 通過客戶端編程的方式調(diào)用Webservice服務(wù)**/ public class WebServiceApp {//1. 自定義方法public void mysoap() throws Exception {// CXF動(dòng)態(tài)客戶端工廠JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();// WSDL文檔url配置()String wsdlUrl = "http://localhost:8080/StudyMaven1/ws/servicemanws?wsdl";Object[] objects = null;try {// 獲取CXF客戶端Client client = dcf.createClient(wsdlUrl);// 調(diào)用Web Service方法objects = client.invoke("add", 1, 2);} catch (Exception e) {e.printStackTrace();}// 獲取調(diào)用結(jié)果System.out.println("調(diào)用結(jié)果:" + objects[0]);System.out.println("=========>");try {// 獲取CXF客戶端Client client = dcf.createClient(wsdlUrl);// 調(diào)用Web Service方法objects = client.invoke("sayHello", "World!");} catch (Exception e) {e.printStackTrace();}// 獲取調(diào)用結(jié)果System.out.println("調(diào)用結(jié)果:" + objects[0]);}//第二種 client工具生成輔助類 需使用apche cxf工具 //步驟 cmd wsdl2java -encoding utf8 http://localhost:8080/StudyMavenSSM/ws/studentws?wsdl//public void clientsoap() throws Exception{// 創(chuàng)建WSDL的URL,注意不是服務(wù)地址URL url = new URL("http://localhost:8080/StudyMaven1/ws/servicemanws?wsdl");// 創(chuàng)建服務(wù)名稱// 1.namespaceURI - 命名空間地址 (wsdl文檔中的targetNamespace// targetNamespace="http://webserviceImp.gxa/")// 2.localPart - 服務(wù)視圖名 (wsdl文檔中服務(wù)名稱,例如<wsdl:service name="studentws">)QName qname = new QName("http://webserviceImp.clack/", "servicemanws");// 創(chuàng)建服務(wù)視圖// 參數(shù)解釋:// 1.wsdlDocumentLocation - wsdl地址// 2.serviceName - 服務(wù)名稱Service service = Service.create(url, qname);// 獲取服務(wù)實(shí)現(xiàn)類// 參數(shù)解釋:serviceEndpointInterface - 服務(wù)端口(wsdl文檔中服務(wù)端口的name屬性,例如<wsdl:port// binding="tns:studentwsSoapBinding" name="StudentWebServiceImpPort">)ServicemanWebService studentWebService =service.getPort(ServicemanWebService.class);//調(diào)用查詢方法List<Serviceman> students = studentWebService.getAllServiceman();for(Serviceman serviceman:students){System.out.println(serviceman.getSname());}}public static void main(String[] args) throws Exception {new WebServiceApp().clientsoap();}}4. 最后運(yùn)行如下,成功調(diào)用:
至此,一個(gè)簡單的webservice就整合進(jìn)去了,但是,其中還有很多細(xì)節(jié)無法言說,學(xué)而無涯。
?
轉(zhuǎn)載于:https://www.cnblogs.com/clack/p/10001375.html
總結(jié)
以上是生活随笔為你收集整理的SSM项目中整合WebService的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 「BZOJ2200」[Usaco2011
- 下一篇: 有限元课堂笔记03:钢架(Frame)