




版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領(lǐng)
文檔簡介
1、結(jié)合Spring框架的 CXF WebService編程實例1. 需要的jar包,除了以上的jar包以外,還需要Spring包,這里就不一一列出了,根據(jù)項目的不同可能還需要其他的jar包,后期調(diào)試的時候根據(jù)控制臺出現(xiàn)的問題,找出原因。2. Web.xml的配置:<!- 加載Spring容器配置 -><listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><!- 設(shè)置Spr
2、ing容器加載配置文件路徑 -><context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:applicationContext-server.xml</param-value></context-param><listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener<
3、/listener-class></listener> <servlet> <servlet-name>CXFService</servlet-name> <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class></servlet> <servlet-mapping> <servlet-name>CXFService</servlet-name> <url-pattern&
4、gt;/*</url-pattern></servlet-mapping>然后在src目錄中,新建一個applicationContext-server.xml文件,這個applicationContext-server.xml需要在web.xml文件中引入(仔細查看上面在web.xml中的配置),當(dāng)然不一定非要新建applicationContext-server.xml,也可以寫在applicationContext.xml中.如果applicationContext-server.xml沒有寫在src下面則web.xml中的文件應(yīng)該這樣寫<context-p
5、aram><param-name>contextConfigLocation</param-name><param-value>/WEB-INF/classes/config/spring/*.xml</param-value></context-param>(這里解釋下:自己查看下編譯后的applicationContext-server.xml的位置是在項目)。我這是在src下面新建了config和spring兩個包,再在里面新建的applicationContext-server.xml(我這里夠啰嗦的了,但是為了你們明白
6、點,別整暈了啊,哈哈哈)。下面是applicationContext-server.xml中的內(nèi)容:<?xml version="1.0" encoding="UTF-8"?><beans xmlns="/schema/beans"xmlns:xsi="/2001/XMLSchema-instance" xmlns:aop="/schema/
7、aop"xmlns:tx="/schema/tx" xmlns:jaxws="/jaxws" xsi:schemaLocation="/schema/beans /schema/beans/spring-beans-2.5.xsd/schema/aop http:/w
8、/schema/aop/spring-aop-2.5.xsd/jaxws /schemas/jaxws.xsd/schema/tx /schema/tx/spring-tx-2.5.xsd"><!- = webService接口 = -> <import resource="classpath:META-INF/c
9、xf/cxf.xml"/> <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml"/> <import resource="classpath:META-INF/cxf/cxf-servlet.xml"/> <!- 配置好webservices的類名和服務(wù)名 -> <bean id="PersonServiceImpl" class="com.service.impl.PersonService
10、Impl"> <property name="employeeDAO"><ref bean="employeeDAO" /></property> </bean> <jaxws:server id="PersonService" serviceClass="com.service.PersonService" address="/PersonService"> <jaxws:serviceBean> <
11、!- 要暴露的 bean 的引用 -> <ref bean="PersonServiceImpl"/> </jaxws:serviceBean> </jaxws:server></beans> 好了以上就是webservice服務(wù)器端外圍的webservice環(huán)境;下面介紹具體的編碼實例;Javabean文件:里面有3個屬:編號,姓名,電話package com.service;public class Person private String code;private String name;private Stri
12、ng tel;public String getName() return name;public String getCode() return code;public void setCode(String code) this.code = code;public void setName(String name) = name;public String getTel() return tel;public void setTel(String tel) this.tel = tel;Webservice方法的接口,里面定義了兩個方法package com.serv
13、ice;import javax.jws.WebParam;import javax.jws.WebService;import javax.jws.soap.SOAPBinding;import javax.jws.soap.SOAPBinding.Style;WebService(name="PersonService")SOAPBinding(style = Style.RPC)public interface PersonService /根據(jù)輸入的字符串對數(shù)據(jù)庫中的人員進行模糊查詢WebParam(name="inputsth") String
14、 inputsthpublic String getPersonList(WebParam(name="inputsth") String inputsth);/根據(jù)登錄的Code,獲得人員信息public String getPersonInfo(WebParam(name="PROP_EMP_DISTINCT_NO") String PROP_EMP_DISTINCT_NO);以下是具體兩個方法的實現(xiàn)類:(這里數(shù)據(jù)訪問采用的hibernate,dao層在這就不細講了)package com.service.impl;import java.util.
15、ArrayList;import java.util.List;import javax.jws.WebMethod;import javax.jws.WebService;import org.hibernate.criterion.DetachedCriteria;import org.hibernate.criterion.Restrictions;import file.dao.IEmployeeDAO;import file.domain.Employee;import com.service.CharacterSetToolkit;impor
16、t com.service.Person;import com.service.PersonService;import com.service.User;WebServicepublic class PersonServiceImpl implements PersonServicepublic IEmployeeDAO getEmployeeDAO() return employeeDAO;public void setEmployeeDAO(IEmployeeDAO employeeDAO) this.employeeDAO = employeeDAO;private IEmployee
17、DAO employeeDAO = null; WebMethodpublic String getPersonList(String inputsth) /inputsth="張" String s = CharacterSetToolkit.fromUnicode(inputsth.toCharArray(), 0, inputsth.length(), inputsth.toCharArray();System.out.println("fffffffffffgg="+s); DetachedCriteria dc = DetachedCriter
18、ia.forClass(Employee.class); dc.add(Restrictions.ilike(Employee.PROP_EMP_NAME, "%"+s+"%"); List<Employee> employee=employeeDAO.findByCriteria(dc); System.out.println("對象="+employee.size();if(employee!=null&&employee.size()>0)String name=""List
19、<Person> pl = new ArrayList();for(int i=0;i<employee.size();i+)name=employee.get(i).getEmpName();String code=employee.get(i).getEmpDistinctNo();String tel=employee.get(i).getEmpWorkPhone();System.out.println("111sss="+name);Person p=new Person();p.setName(name);p.setCode(code);p.s
20、etTel(tel);pl.add(p);/ return pl;return new com.service.DataSyncXml().personListXml(pl);/ List<Person> list = new ArrayList();/ list.add(new Person();/return list;return null; WebMethodpublic String getPersonInfo(String PROP_EMP_DISTINCT_NO) DetachedCriteria dc = DetachedCriteria.forClass(Empl
21、oyee.class);dc.add(Restrictions.eq(Employee.PROP_EMP_DISTINCT_NO, PROP_EMP_DISTINCT_NO);List<Employee> employee= employeeDAO.findByCriteria(dc);if(employee!=null&&employee.size()>0) String name=employee.get(0).getEmpName(); String tel=employee.get(0).getEmpWorkPhone(); Person p=new
22、Person(); p.setName(name); p.setTel(tel); System.out.println("1111="+p.getName()+"2222="+p.getTel(); return new com.service.DataSyncXml().personInfoXml(p);return null;注意以上CharacterSetToolkit這個方法,主要是當(dāng)時傳中文參數(shù)的時候,服務(wù)器端為亂碼,當(dāng)時花費了我好大的勁才解決的,先將中文轉(zhuǎn)換成unicode編碼,再將unicode編碼換成中文就ok了package com.
23、service;public class CharacterSetToolkit /* Creates a new instance of CharacterSetToolkit */ public CharacterSetToolkit() private static final char hexDigit = '0','1','2','3','4','5','6','7','8','9','A','B
24、9;,'C','D','E','F' ; private static char toHex(int nibble) return hexDigit(nibble & 0xF); /* * 將字符串編碼成 Unicode 。 * param theString 待轉(zhuǎn)換成Unicode編碼的字符串。 * param escapeSpace 是否忽略空格。 * return 返回轉(zhuǎn)換后Unicode編碼的字符串。 */ public static String toUnicode(String theString, boole
25、an escapeSpace) int len = theString.length(); int bufLen = len * 2; if (bufLen < 0) bufLen = Integer.MAX_VALUE; StringBuffer outBuffer = new StringBuffer(bufLen); for(int x=0; x<len; x+) char aChar = theString.charAt(x); / Handle common case first, selecting largest block that / avoids the spe
26、cials below if (aChar > 61) && (aChar < 127) if (aChar = '') outBuffer.append(''); outBuffer.append(''); continue; outBuffer.append(aChar); continue; switch(aChar) case ' ': if (x = 0 | escapeSpace) outBuffer.append(''); outBuffer.append('
27、39;); break; case 't':outBuffer.append(''); outBuffer.append('t'); break; case 'n':outBuffer.append(''); outBuffer.append('n'); break; case 'r':outBuffer.append(''); outBuffer.append('r'); break; case 'f':outBuffer.appen
28、d(''); outBuffer.append('f'); break; case '=': / Fall through case ':': / Fall through case '#': / Fall through case '!': outBuffer.append(''); outBuffer.append(aChar); break; default: if (aChar < 0x0020) | (aChar > 0x007e) outBuffer.appe
29、nd(''); outBuffer.append('u'); outBuffer.append(toHex(aChar >> 12) & 0xF); outBuffer.append(toHex(aChar >> 8) & 0xF); outBuffer.append(toHex(aChar >> 4) & 0xF); outBuffer.append(toHex( aChar & 0xF); else outBuffer.append(aChar); return outBuffer.toSt
30、ring(); /* * 從 Unicode 碼轉(zhuǎn)換成編碼前的特殊字符串。 * param in Unicode編碼的字符數(shù)組。 * param off 轉(zhuǎn)換的起始偏移量。 * param len 轉(zhuǎn)換的字符長度。 * param convtBuf 轉(zhuǎn)換的緩存字符數(shù)組。 * return 完成轉(zhuǎn)換,返回編碼前的特殊字符串。 */ public static String fromUnicode(char in, int off, int len, char convtBuf) if (convtBuf.length < len) int newLen = len * 2; if (new
31、Len < 0) newLen = Integer.MAX_VALUE; convtBuf = new charnewLen; char aChar; char out = convtBuf; int outLen = 0; int end = off + len; while (off < end) aChar = inoff+; if (aChar = '') aChar = inoff+; if (aChar = 'u') / Read the xxxx int value = 0; for (int i = 0; i < 4; i+)
32、aChar = inoff+; switch (aChar) case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': value = (value << 4) + aChar - '0' break; case 'a': case 'b'
33、;: case 'c': case 'd': case 'e': case 'f': value = (value << 4) + 10 + aChar - 'a' break; case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': value = (value << 4) + 10 + aChar - 'A' br
34、eak; default: throw new IllegalArgumentException( "Malformed uxxxx encoding."); outoutLen+ = (char) value; else if (aChar = 't') aChar = 't' else if (aChar = 'r') aChar = 'r' else if (aChar = 'n') aChar = 'n' else if (aChar = 'f') aCh
35、ar = 'f' outoutLen+ = aChar; else outoutLen+ = (char) aChar; return new String(out, 0, outLen); 最后將返回的東西,封裝成xml就行package com.service;import java.util.List;import org.dom4j.Document;import org.dom4j.DocumentHelper;import org.dom4j.Element;public class DataSyncXml /模糊查詢返回人員列表public String pers
36、onListXml(List pl)Document doc = DocumentHelper.createDocument();Element personList = doc.addElement("PersonList");for(int i=0;i<pl.size();i+)Person person = (Person)pl.get(i);Element p = personList.addElement("Person");p.addElement("NAME").addText(object2String(pers
37、on.getName();p.addElement("CODE").addText(object2String(person.getCode();p.addElement("TEL").addText(object2String(person.getTel();return doc.asXML(); /返回人員信息public String personInfoXml(Person p)Document doc = DocumentHelper.createDocument();Element personInfo = doc.addElement(&q
38、uot;PersonInfo");Element person = personInfo.addElement("Person");person.addElement("NAME").addText(object2String(p.getName();person.addElement("TEL").addText(object2String(p.getTel();return doc.asXML();private String object2String(Object o)return o=null?"&quo
39、t;:o.toString();怎樣在服務(wù)器端進行webservice的測試呢,首先在瀏覽器的地址欄中輸入webservice的地址http:/192.168.5.xxx:8080/xxx/service/PersonService?wsdl如果出現(xiàn)你所學(xué)的方法名稱,這說明你的webservice外圍環(huán)境搭建成功,現(xiàn)在看一下你寫的返回xml是否正確(我這是以返回對象0bject測試的)一下是我寫的mian方法,public class SpringUsersWsClient public static void main(String args) throws UnsupportedEncod
40、ingException 通過登錄的用戶名(工號)查詢用戶的姓名和辦公電話 JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean(); factory.setServiceClass(PersonService.class); factory.setAddress("http:/192.168.xxx.xxx:8080/xxx/service/PersonService"); PersonService service = (PersonService) factory.create(); Person p=se
41、rvice.getPersonInfo("TH505"); String name=p.getName(); String tel=p.getTel(); System.out.println("人員姓名="+name+"辦公電話="+tel); JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean(); factory.setServiceClass(PersonService.class); factory.setAddress("http:/192.xxx.
42、xxx.xxx:8080/xxx/service/PersonService"); PersonService service = (PersonService) factory.create(); String inputsth="張" String uname =new String( inputsth.getBytes(Charset.forName("GB2312") ); String uname=CharacterSetToolkit.toUnicode(inputsth, true); System.out.println(&qu
43、ot;uname="+uname); List<Person> personlist=service.getPersonList(uname); System.out.println("人員姓名總量22222="+personlist.size(); for(int i=0;i<personlist.size();i+) System.out.println("人員姓名2222222="+personlist.get(i).getName(); 在客戶端調(diào)用剛剛所寫的webservicepublic class SpringW
44、sClient /返回人員列表public static List<Person> getPersonName(String inputsth)throws UnsupportedEncodingException, ServiceException, MalformedURLException, RemoteException, DocumentException ClassLoader cl = Thread.currentThread().getContextClassLoader(); DynamicClientFactory dcf = DynamicClientFact
45、ory.newInstance(); Client client = dcf.createClient("http:/192.168.5.xxx:8080/xxx/service/PersonService?wsdl"); Thread.currentThread().setContextClassLoader(cl); Object reply = null; /String inputsth="張" String uname=CharacterSetToolkit.toUnicode(inputsth, true); try reply =clien
46、t.invoke("getPersonList", uname); catch (Exception e) e.printStackTrace(); String result=(String) reply0;/ System.out.println("2222222www="+result); Document document = DocumentHelper.parseText(result); List listObject = document.selectNodes("/PersonList/Person"); List<Person> pl = new ArrayList(); for (int i = 0; i < listObject.size(); i+) Element personElement = (Element) listObject.get(i); String name = personElement.element("NAME").get
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 2024年南京審計大學(xué)輔導(dǎo)員考試真題
- 2024年婁底雙峰縣林業(yè)局所屬事業(yè)單位選調(diào)真題
- 培養(yǎng)學(xué)生合作精神的計劃
- 2025屆廣東省廣州市廣州大附中數(shù)學(xué)八下期末考試試題含解析
- 明確職責(zé)與任務(wù)分配計劃
- 2024年北京市自來水集團招聘筆試真題
- 面對失敗的心態(tài)與反思2024年高考作文試題及答案
- 黑龍江省雞西市虎林市八五八農(nóng)場學(xué)校2025年八年級數(shù)學(xué)第二學(xué)期期末檢測模擬試題含解析
- 業(yè)務(wù)連續(xù)性與戰(zhàn)略風(fēng)險試題及答案
- 安徽省六安市名校2025屆七年級數(shù)學(xué)第二學(xué)期期末復(fù)習(xí)檢測模擬試題含解析
- 湖北省華大新高考聯(lián)盟2025屆5月名校高考預(yù)測卷高三語文試卷 含解析
- 四川西華師范大學(xué)招聘輔導(dǎo)員考試真題2024
- 貴州游船傾覆防災(zāi)減災(zāi)安全教育時事熱點
- 宏觀策略-專題報告:近年來中國基建投資趨勢與特征
- 黑龍江省大慶市石油高級中學(xué)2024-2025學(xué)年高二上學(xué)期期末語文試題 含解析
- 2025全國保密教育線上培訓(xùn)考試試題庫(含答案)
- 呼吸性酸中毒試題及答案
- 航天技術(shù)發(fā)展與應(yīng)用知識題庫
- 管理會計試題及答案英文
- 2025購車貸款合同范本
- 檢察院相關(guān)試題及答案
評論
0/150
提交評論