在 SSH專案中加入WebService
這兩天要在SSH專案內加入WebService 於是海選了一下,找到如下經典之貼,於是把它轉到自己這邊來,留作記錄。
以我在自己專案為例,我們有兩個不同的專案A和B,它們在不同的伺服器上,而A釋出的新聞要在B專案中使用,且A專案釋出的新聞是在當前專案中生成的靜態頁面,因此使用WebServic。
首先在自己的專案中加入如下JAR包(WEB-INF/lib):
activation- 1.1.jar、
commons -beanutils-1.7.0.jar、
commons-codec-1.3.jar、
commons-httpclient.jar、
commons-logging-1.0.4.jar、
jaxen-1.1-beta-9.jar、
jaxws-api-2.0.jar、
jdom- 1.0.jar、
jsr173_api-1.0.jar、
mail-1.4.jar、
saaj-api-1.3.jar、
saaj-impl- 1.3.jar、
spring-1.2.6.jar、
stax-api-1.0.1.jar、
wsdl4j-1.5.2.jar、
wstx-asl- 3.0.1.jar、
xbean-2.1.0.jar、
xbean-spring-2.5.jar、
xfire-aegis-1.2.2.jar、
xfire-annotations-1.2.2.jar、
xfire-core-1.2.2.jar、
xfire-java5-1.2.2.jar、
xfire-jaxws-1.2.2.jar、
xfire-jsr181-api-1.0-M1.jar、
xfire-spring- 1.2.2.jar、
XmlSchema-1.1.jar
然後做如下配置:
1)web.xml的配置
一般情況下,我們通過HTTP作為Web Service的傳輸協議,這樣我們只需啟動一個Web伺服器(如Tomcat,在本例中使用的是Tomcat5.5.20),這樣客戶端就可以通過 HTTP訪問到Web Service服務。為了整合Spring容器,XFire專門提供一個XFireSpringServlet,我們可以在web.xml中配置該 Servlet,將Spring容器中定義的Web Service在某個URI下發布。
為了能正確使用XFire,需在 web.xml中進行相應配置,在該檔案中配置XFire的servlet和servlet-mapping。同時因為本例項需要將XFire整合到 Spring中,因而需要在web.xml檔案中載入Spring的相應配置檔案。在本例項中,我們首先在WEB-INF下建立兩個配置Spring配置檔案,一個為applicationContext.xml,該檔案用來定義本工程的bean,一個為xfire-servlet.xml,用來配置 XFire的相關bean。修改後的web.xml的內容如下所示:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/classes/applicationContext.xml,
/WEB-INF/spring/application*.xml,
/WEB-INF/xfire-servlet.xml
</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.util.IntrospectorCleanupListener
</listener-class>
</listener>
<!-- begin XFire 配置 -->
<servlet>
<servlet-name>xfire</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>xfire</servlet-name>
<url-pattern>*.ws</url-pattern>
</servlet-mapping>
<servlet>
<!-- 配合Spring容器中XFire一起工作的Servlet-->
<servlet-name>xfireServlet</servlet-name>
<servlet-class>
org.codehaus.xfire.spring.XFireSpringServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>xfireServlet</servlet-name>
<!-- 在這個URI下開放Web Service服務 -->
<url-pattern>/service/*</url-pattern>
</servlet-mapping>
<!-- end XFire 配置 -->
2)Web Service的介面類ReadNewsService.java和對應實現類ReadNewsServiceImpl.java
為了用Web Service完成HelloWorld功能,我們首先在src/webservice目錄下建立介面類ReadNewsService.java。它僅包含一個articleShow(long name)的方法,其詳細內容如下:
public interface ReadNewsService {
public String articleShow(long artId) ;
}
我們還需要建立一個對應的實現類,來實現articleShow的功能,該實現類即為ReadNewsServiceImpl.java。該類的詳細內容如下:
public class ReadNewsServiceImpl extends HibernateDaoSupport implements ReadNewsService {
private String tableName = null;
private GetLoadSql loadSql = null;
FileOperator fileOperator ;
public ReadNewsServiceImpl() {
fileOperator = new FileOperator();
loadSql = new GetLoadSql(WebConfig.SERVICE_PATH);
}
public String articleShow(long artId) {
tableName = "News";
String sql = "" ;
String content = "" ;
try{
sql = loadSql.getSqlLoad(WebConfig.PERSONAL_ARTICLESHOWINFOR);
Query q = this.getSession().createQuery(sql) ;
// SQL 條件設定
q.setLong(0, artId);
// SQL 執行
Iterator it = q.list().iterator() ;
while(it.hasNext()) {
News news = (News)it.next() ;
// 路徑取得
String articleAddr = news.getPageAddr() ;
if (articleAddr != null && !"".equals(articleAddr)) {
// 根目錄取得
// String basePath = request.getScheme() + "://"
// + request.getServerName() + ":"
// + request.getServerPort()
// + request.getContextPath();
//獲取WebService介面的URL地址
String basePath = WebConfig.SERVICE_HUJIAO_PATH ; //"http://192.168.0.119:8088/rck" ;
// 絕對路徑absolutePath
String absolutePath = basePath + articleAddr ;
URI uri = new URI(absolutePath);
if (uri.isAbsolute()) {
// if (uri.getPath().toString().startsWith(
// request.getContextPath().toString())) {
// absolutePath = request.getSession()
// .getServletContext().getRealPath(
// uri.getPath().toString().replace(
// request.getContextPath(), ""));
// }
//取得新聞靜態檔案存放的目錄
absolutePath = ClassLoaderUtil.getExtendResource(".." + articleAddr).getFile() ;
//此處才是真正取得靜態頁面的絕對路徑
absolutePath = absolutePath.replaceAll("/WEB-INF", "") ;
} else {
absolutePath = String.valueOf(uri);
}
if (fileOperator.fileIsExist(absolutePath)) {
// workArticle.setArticleLoad(articleAddr);
//content = articleAddr ;
//構造URL地址
content = basePath + articleAddr ;
} else {
content = "對不起,您訪問的頁面不存在或已被刪除!" ;
}
}
}
} catch (Exception e) {
ZPLogger.error(this, "articleShow()", "API DB出現異常。"
+ tableName + " SQL(STATEMENT) " + sql);
content = "程式出現錯誤,請稍候重試!" ;
}
return content ;
}
}
3)Spring配置檔案applicationContext.xml和xfire-servlet.xml的配置
首先我們在applicationContext.xml檔案中配置對應的bean——readNewsService,該xml檔案的內容如下:
<bean id="readNewsService" class="com.chinarck.service.impl.news.ReadNewsServiceImpl">
<property name="hibernateTemplate">
<ref bean="hibernateTemplate"/>
</property>
</bean>
這個配置檔案很簡單,在此不詳述。
XFire 為Spring 提供了方便易用的匯出器XFireExporter,藉助該匯出器的支援,我們可以在Spring容器中將一個POJO匯出為Web Service。HelloWorld是業務服務類,在此擁有一個sayHelloWorld的方法,我們希望將此方法開放為Web Service。在實際應用中,如果某個類具有眾多的方法,而其中的某些方法不需要開放為Web Service的情況下,我們可以定義一個窄介面,該介面中只需定義那些開放為Web Service的業務方法。
將一個業務類所有需要開放為Web Service的方法通過一個窄介面來描述是值得推薦的作法,這讓Web Service的介面顯得很“乾淨”。其次,XFire的匯出器也需要服務介面的支援,因為它採用基於介面的動態代理技術。
窄介面中的方法在真實的系統中可能需要引用其它的業務類或DAO獲取資料庫中的真實資料,為了簡化例項,我們在此簡化了例項。
下面讓我們看看在xfire-servlet.xml檔案中匯出器的設定,該檔案內容如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<!-- 引入XFire預配置資訊 -->
<import resource="classpath:org/codehaus/xfire/spring/xfire.xml" />
<!-- 定義訪問的url -->
<bean
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="urlMap">
<map>
<entry key="/ReadNewsService.ws">
<ref bean="ReadNewsService" />
</entry>
</map>
</property>
</bean>
<!-- 使用XFire匯出器 -->
<bean id="baseWebService"
class="org.codehaus.xfire.spring.remoting.XFireExporter"
lazy-init="false" abstract="true">
<!-- 引用xfire.xml中定義的工廠 -->
<property name="serviceFactory" ref="xfire.serviceFactory" />
<!-- 引用xfire.xml中的xfire例項 -->
<property name="xfire" ref="xfire" />
</bean>
<bean id="ReadNewsService" parent="baseWebService">
<!-- 業務服務bean -->
<property name="serviceBean" ref="readNewsService" />
<!-- 業務服務bean的窄介面類 -->
<property name="serviceClass" value="com.chinarck.service.news.ReadNewsService" />
</bean>
</beans>
上面的配置中,我們可以看到,在該配置檔案中引入了xfire.xml這個Spring配置檔案。它是在XFire核心JAR包中擁有一個預定義的 Spring配置檔案,它定義了XFire在Spring中必須用到的一些Bean和資源,需要引入這個預定義的配置檔案。從該配置檔案中可以看出,我們通過XFireExporter將業務類匯出為Web Service,對於任何匯出器,我們都需要引入XFire環境,即serviceFactory和xfire,這是標準的配置。 ServiceFactory是XFire的核心類,它可以將一個POJO生成為一個Web Service。
在本例項中,我們通過定義一個baseWebService,其餘的webService配置都將該bean作為父bean,這樣可以簡化Spring的配置,不需要多次引入serviceFactory和xfire。
3. Web Service的測試
在上一步操作完成之後,我們的這個簡單的Web Service已經編寫完畢,下面讓我們來看看自己的勞動成果吧。
在瀏覽器中輸入地址:http://localhost:8080/rck/ReadNewsService.ws?wsdl,我們可以看到ReadNewsService對應的WSDL資訊,閱讀這個WSDL文件,我們可以知道readNewsService的articleShow方法已經被成功地釋出為Web Service了。只要拿到這個WSDL就可以開發相應的客戶端呼叫程式了。
XFire為訪問服務端Web Service提供了各種方便的方式:我們一般根據服務地址和窄介面類建立客戶呼叫程式。
在不能獲得服務窄接
口類的情況下,XFire允許我們通過WSDL檔案生成客戶端呼叫程式,通過指定服務介面的方式呼叫服務。
1)通過WSDL檔案生成客戶端呼叫程式
首先我們通過http://localhost:8080/rck/ReadNewsService.ws?wsdl我們可以獲得WSDL檔案ReadNewsService.wsdl,並將其放在src目錄下面,接著我們通過程式訪問該WSDL檔案,並呼叫需測試的方法。此時測試類WebServiceClientTest .java的內容如下所示:
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import org.codehaus.xfire.client.Client;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import com.bean.UserWebServiceTest;
public class WebServiceClientTest {
//HelloWorld helloWorld = null ;
/**
* HelloWorld的webservice的測試類
* @param args
*/
public static void main(String[] args) {
//WebServiceClientTest test = new WebServiceClientTest() ;
UserWebServiceTest useService = new UserWebServiceTest() ;
useService.setArtId("9") ;
try {
//test.testClient() ;
String to_url = useService.getNewsContent() ;
StringBuffer document = new StringBuffer();
try {
URI uri = new URI(to_url);
if (uri.isAbsolute()) {
URL url = new URL(to_url);
URLConnection conn = url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null)
document.append(line + " ");
reader.close();
} else {
document.append("很抱歉,讀取新聞出現異常!請稍候重試!") ;
}
} catch (MalformedURLException e) {
e.printStackTrace();
document.append("很抱歉,讀取新聞出現異常!請稍候重試!") ;
} catch (IOException e) {
e.printStackTrace();
document.append("很抱歉,讀取新聞出現異常!請稍候重試!") ;
}
System.out.println(document.toString());
//useService.testClient() ;
} catch (Exception e) {
e.printStackTrace();
}
}
public void testClient() throws Exception {
String wsdl = "ReadNewsService.wsdl" ; //對應的WSDL檔案
Resource resource = new ClassPathResource(wsdl) ;
Client client = new Client(resource.getInputStream() ,null) ; //根據WSDL建立客戶例項
Object[] objArray = new Object[1] ;
objArray[0] = "1" ;
//呼叫特定的WebService方法
Object[] result = client.invoke("articleShow", objArray) ;
System.out.println("result:" + result[0]) ;
}
}
2)根據服務地址建立客戶端呼叫程式
此種呼叫沒有做測試
相關文章
- 關於git專案中多ssh-key管理Git
- A專案軼事之加入專案2個月
- Veeam宣佈加入HPEComplete專案
- 專案管理之——Git SSH配置專案管理Git
- 短視訊開發app,webservice自定義加入攔截器APPWeb
- 在spring boot專案(maven)中引入其他 spring boot專案Spring BootMaven
- vue專案中加入拖放排序功能Vue排序
- Harbor開源專案加入CNCF基金會!
- 在vue專案中mock資料VueMock
- 在Android原生專案中整合FlutterAndroidFlutter
- 在 Laradock 中開發 Vue 專案Vue
- 在專案中如何直接使用hystrix?
- 在gradle中構建java專案GradleJava
- 專案實戰之gradle在實際專案中的使用Gradle
- JWT 在專案中的實際使用JWT
- bing Map 在vue專案中的使用Vue
- TypeScript在react專案中的實踐TypeScriptReact
- TypeScript在node專案中的實踐TypeScript
- 在Django中查詢重複專案Django
- SpringBoot專案在Eclipse/MyEclipse中執行Spring BootEclipse
- 在 Homestead 中搭建 ThinkPHP 專案記錄PHP
- 在 React 專案中全量使用 HooksReactHook
- 在idea中利用spingboot建立maven專案IdeabootMaven
- 中國首個開源基金會成立,已有七個專案加入孵化
- 在 Windows 中編譯 Github 中的 GO 專案Windows編譯GithubGo
- 專案實戰之Rxjava、RxBinding在實際專案中的使用RxJava
- [原創]專案過程管理在專案管理中的重要性專案管理
- 在vue專案中優雅的使用SvgVueSVG
- Objc Runtime在專案中該怎麼用OBJ
- 在專案中遇到的一些bug
- Spring在開發專案中起的作用Spring
- vue-ssr在專案中的實踐Vue
- JWT在專案中的簡單應用JWT
- 在專案中如何用Redis分散式鎖Redis分散式
- UI2 在專案中的應用UI
- 在TypeScript專案中進行BDD測試TypeScript
- TypeScript在React專案中的使用總結TypeScriptReact
- 20100420專案管理沙龍專題:軟體工程在軟體專案中的位置專案管理軟體工程
- 專案儀表板在專案管理軟體中的功能是什麼專案管理