




版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1、结合Spring框架的 CXF WebService编程实例1. 需要的jar包,除了以上的jar包以外,还需要Spring包,这里就不一一列出了,根据项目的不同可能还需要其他的jar包,后期调试的时候根据控制台出现的问题,找出原因。2. Web.xml的配置:<!- 加载Spring容器配置 -><listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><!- 设置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中的配置),当然不一定非要新建applicationContext-server.xml,也可以写在applicationContext.xml中.如果applicationContext-server.xml没有写在src下面则web.xml中的文件应该这样写<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中的内容:<?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的类名和服务名 -> <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服务器端外围的webservice环境;下面介绍具体的编码实例;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 /根据输入的字符串对数据库中的人员进行模糊查询WebParam(name="inputsth") String
14、 inputsthpublic String getPersonList(WebParam(name="inputsth") String inputsth);/根据登录的Code,获得人员信息public String getPersonInfo(WebParam(name="PROP_EMP_DISTINCT_NO") String PROP_EMP_DISTINCT_NO);以下是具体两个方法的实现类:(这里数据访问采用的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这个方法,主要是当时传中文参数的时候,服务器端为乱码,当时花费了我好大的劲才解决的,先将中文转换成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 待转换成Unicode编码的字符串。 * param escapeSpace 是否忽略空格。 * return 返回转换后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 码转换成编码前的特殊字符串。 * param in Unicode编码的字符数组。 * param off 转换的起始偏移量。 * param len 转换的字符长度。 * param convtBuf 转换的缓存字符数组。 * return 完成转换,返回编码前的特殊字符串。 */ 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();怎样在服务器端进行webservice的测试呢,首先在浏览器的地址栏中输入webservice的地址http:/192.168.5.xxx:8080/xxx/service/PersonService?wsdl如果出现你所学的方法名称,这说明你的webservice外围环境搭建成功,现在看一下你写的返回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(); 在客户端调用刚刚所写的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. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 北京市朝阳区2023-2024学年七年级上学期期末质量监测道德与法制考题及答案
- 安徽省芜湖市繁昌区2022-2023学年高三上学期期末考试生物题库及答案
- 中考英语满分初中生能否骑电动自行车12篇范文
- 时间与管理课件讲解
- 农村信息技术应用与智能化改造合作合同
- 春节的作文600字14篇
- 实践中创新话题的作文高三(7篇)
- 员工培训需求分析与评估工具
- 早期阅读虫虫飞课件
- 早教培训知识点总结课件
- 2025年新钢铁安全员考试题库及答案
- 2025版电子购销合同模板
- 消防安装居间合同协议书
- 2025年度江苏行政执法资格考试模拟卷及答案(题型)
- 续保团队职场管理办法
- 2025年中煤电力有限公司招聘笔试参考题库含答案解析
- 动词教学课件
- 2025至2030直接甲醇燃料电池(DMFC)行业发展趋势分析与未来投资战略咨询研究报告
- 盐雾测试报告
- 维修工培训课件
- 外科学教案-腹外疝
评论
0/150
提交评论