場景
某SpringMVC項目原本為一個HTTP的WEB服務項目,之后想在該項目中添加WebService支持,使該項目同時提供HTTP服務和WebService服務。其中WebService服務通過 /ws/**
地址攔截。
配置
通過配置讓SpringMVC支持WebService。
依賴
首先通過Maven引入必要依賴包。
- org.apache.cxf
- org.apache.neethi
- com.ibm.wsdl4j
- org.apache.XmlSchema
Web.xml
通過配置Web.xml使Spring框架具備WebService特性,這里通過添加Servlet(這里使用CXFServlet)實現。假設SpringMVC本身的DispatcherServlet已經啟用,則在第2啟動順序添加CXFServlet。並添加servlet-mapping匹配請求。
配置如下
<!-- 在上下文中添加配置文件 -->
<context-param>
<param-name>patchConfigLocation</param-name>
<param-value>
/WEB-INF/applicationServlet.xml
/WEB-INF/webservice.xml
<param-value>
</context-param>
<!-- 添加servlet -->
<servlet>
<servlet-name>ws</servlet-name>
<servlet-class>org.apache.cxf.trasport.servlet.CXFServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>ws</servlet-name>
<url-pattern>/ws/**</url-pattern>
</servlet-mapping>
webservice.xml
將webservice的接口配置單獨分離出來。配置如下:
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:jaxws="http://cxf.apache.org/jaxws" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- cxf必要配置 -->
<import resource="classpath:META-INF/cxf/cxf.xml" />
<import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
<import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />
<!-- 接口的實現類聲明 -->
<jaxws:endpoint id="ticketDecodeAuthService" implementorClass="com.xxx.apps.web.ws.server.decode.XXXServiceImpl" address="/ticketDecodeAuth" />
</beans>
接口編寫
對應上文聲明的接口文檔在寫在相應的位置上(如本文例子則寫在com.xxx.apps.web.ws.server.decode包中)
代碼如下:
@WebService
@SOAPBinding(style = Style.RPC)
public interface XXXService {
public WSReturn getAuth(String userName, String password) throws Exception;
}
接口實現類:
@WebService
@SOAPBinding(style = Style.RPC)
@SuppressWarnings("deprecation")
public class XXXServiceImpl implements XXXService {
private static final Logger LOGGER = Logger.getLogger(XXXServiceImpl.class);
@Override
public WSReturn getAuth(String userName, String password) throws Exception {
// WSReturn 是自定義的通用接口返回包裝,可以用別的
WSReturn res = new WSReturn();
// TODO : your code here
return res;
}
}
發布接口效果
啟動SpringMVC項目,根據配置文件定義,接口地址類似:http://ip:port/項目名/ws/**
若本例配置則有如下接口可以查看:
查看所有接口列表
http://ip:port/項目名/ws
某具體端口(XXXService)為例
這也是客戶端調用時候的地址
http://ip:port/項目名/ws/XXXService?wsdl
這里可以看到端口的規范定義
客戶端編寫
客戶端代碼
通過CXF的動態代理方式編寫,以反射方式將class直接引入可以實現統一調用方法。這樣該Client即可調用任意接口。
代碼如下:
/** * webservice服務客戶端 * @author WSY * */
public class WSClient {
private static Logger logger = LoggerFactory.getLogger(WSClient.class);
/** * 調用代理 * @param cls 服務接口代理 * @param method 方法名 * @param wsdl wsdl地址 * @param params 參數Object[] * @return * @throws Exception */
@SuppressWarnings("rawtypes")
public static WSReturn invoke(Class cls,String method,String wsdl, Object[] params) throws Exception{
synchronized(WSClient.class){
logger.info("[WSClient invoking] - class:"+cls.getName()+"; method:"+method+"; wsdl:"+
wsdl+"; params:"+getParams(params));
JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
factory.getInInterceptors().add(new LoggingInInterceptor());
factory.getOutInterceptors().add(new LoggingOutInterceptor());
factory.setServiceClass(cls);
factory.setAddress(wsdl);
Object cInstance = factory.create();
Method invokeMethod = null;
for(Method m : cls.getDeclaredMethods()){
if(m.getName().equalsIgnoreCase(method)){
invokeMethod = m;
break;
}
}
if(invokeMethod == null)
throw new Exception("ERROR:method not found");
WSReturn res = (WSReturn) invokeMethod.invoke(cInstance, params);
return res;
}
private static String getParams(Object[] params){
StringBuilder sb = new StringBuilder("{");
for(Object b : params){
sb.append(b).append(",");
}
if(sb.length()==1)
return "{}";
else
return sb.substring(0,sb.length()-1)+"}";
}
}
}
打包
寫個Ant腳本將一些必要的Java類和定義的Interface(不要打實現類)打成包。本文中將Client代碼也寫在了Service端了,所以將WSClient也一並打包進去。這樣在編寫對應的客戶端時候,僅需專注於功能實現即可。
<?xml version="1.0"?>
<project name="tws-interfaces" default="jar" basedir=".">
<!-- Give user a chance to override without editing this file or typing -D -->
<property name="coredir" location="." />
<property name="classdir" location="${basedir}/target/classes" />
<target name="jar" description="Build the jars for core">
<delete file="${coredir}/webservice-interfaces-1.0.jar" />
<jar destfile="${coredir}/webservice-interfaces-1.0.jar">
<fileset dir="${classdir}">
<include name="**/com/xxx/apps/web/ws/server/**/*Service.class" />
<include name="**/com/xxx/apps/web/ws/server/tokenservice/**/*.class" />
<include name="**/com/xxx/apps/web/ws/server/WSReturn.class"/>
<include name="**/com/xxx/apps/comm/ResultState.class"/>
<include name="**/com/xxx/apps/web/ws/server/wsclient/WSClient.class"/>
<include name="**/com/xxx/apps/comm/RespResult.class"/>
<exclude name="**/com/xxx/apps/web/ws/server/**/*Impl.class" />
</fileset>
</jar>
<copy todir="../xxxclient/lib" file="./webservice-interfaces-1.0.jar"></copy>
</target>
</project>
客戶端項目實現
依賴
首先通過Maven引入必要依賴包。
- org.apache.cxf.cxf-rt-frontend-jaxws
- org.apache.cxf.cxf-rt-databinding-aegis
- org.apache.cxf.cxf-rt-transports-http
- org.apache.cxf.cxf-rt-transports-http-jetty
commons-codec.commons-codec
最重要的:引入server端打包好的jar包,里邊有WSClient和必要的接口
<dependency> <groupId>com.xxx</groupId> <artifactId>xxxserver</artifactId> <version>1.0</version> <scope>system</scope> <systemPath>${project.basedir}/lib/webservice-interfaces-1.0.jar</systemPath> </dependency>
WSClient調用
通過直接調用jar包中的WSClient即可調用遠程WebService接口。
調用示例代碼如下:
/** 這里將調用注釋復制過來 * 調用代理 * @param cls 服務接口代理 * @param method 方法名 * @param wsdl wsdl地址 * @param params 參數Object[] * @return * @throws Exception */
WSReturn res= WSClient.invoke(XXXService.class
, "getAuth"
,endpoints.get(XXXService.class.getName())
, new Object[]{"admin","admin"});
if(token.getStatusId() == ResultState.SUCESS){
tokenValue = (String) token.getMap().get("token");
} else {
logger.error("獲取token失敗:"+token.getMsg());
}
一些坑
一定要引入cxf的必要配置
雖然在項目中看不到,但是這些xml文件在cxf的jar包中。
<!-- cxf必要配置 -->
<import resource="classpath:META-INF/cxf/cxf.xml" />
<import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
<import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />
Interface的類路徑一定要統一
如服務端的 XXXService.java
在 com.xxx.web.ws.server
中,則在客戶端的XXXService.java類也應該在相同的路徑即: com.xxx.web.ws.server
。 所以為方便起見,用Ant直接打包比較方便,不容易錯。
客戶端並發問題
本例中調用WSClient,通過反射機制調用,共用一個Factory,因此在並發時候容易出現問題,需要在WSClient中加鎖
原文地址:https://blog.csdn.net/tzdwsy/article/details/51938786