转载

WebService CXF学习(高级篇2):CXF+Spring+Hibernate

前一节仅仅只讲了与spring整合,没有涉及到数据库,而且是直接将Java象传递到服务端。这一节我起到一个回顾前面章节的作用。用在客户端运用JABX将JAVA对象编组成XML文件,在客户端将XML解组成JAVA并存入数据库。下面我们就着手开发这个Demo: 服务端开发 第一步,编写数据资源层相关接口 DAO编写:
public interface HibernateDao {   public void save(UserInfo object); public void delete(UserInfo object); public void update(UserInfo object); public UserInfo get(int id); }  
DAO实现类:
public class HibernateDaoImpl extends HibernateDaoSupport implements HibernateDao {   public void delete(UserInfo object) { this.getHibernateTemplate().delete(object); }   public void save(UserInfo object) { this.getHibernateTemplate().save(object); }   public void update(UserInfo object) { this.getHibernateTemplate().update(object); }   public UserInfo get(int id) { return (UserInfo) this.getHibernateTemplate().get(UserInfo.class, id); }   }
实体对象:
@Entity @Table(name = "userinfo") public class UserInfo implements java.io.Serializable {   private static final long serialVersionUID = 2281022190032353574L;   @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private String name; private Integer age; private Integer address;   public UserInfo() { }   public UserInfo(String name, Integer age) { this.name = name; this.age = age; }   public UserInfo(String name, Integer age, Integer address) { this.name = name; this.age = age; this.address = address; }   public Integer getId() { return this.id; }   public void setId(Integer id) { this.id = id; }   public String getName() { return this.name; }   public void setName(String name) { this.name = name; }   public Integer getAge() { return this.age; }   public void setAge(Integer age) { this.age = age; }   public Integer getAddress() { return this.address; }   public void setAddress(Integer address) { this.address = address; }   }
第二步:业务逻辑层接口编写 业务逻辑接口:
@WebService public interface IService {   //public void save(@WebParam(name="info")String xml); public void save(@WebParam(name="dto")UserInfoDTO dto,@WebParam(name="flag")boolean flag); public void update(@WebParam(name="info")String xml); public void delete(@WebParam(name="id")int id); public @WebResult(name="String")String get(@WebParam(name="id")int id); }
接口实现类:
@WebService public class ServiceImpl implements IService { private Logger log = LoggerFactory.getLogger(ServiceImpl.class); private HibernateDao dao; //  public void setDao(HibernateDao dao) { //      this.dao = dao; //  } public void delete(int id) { log.info("delete id is {} user"+id); //UserInfo userInfo = (UserInfo)object; //log.info("this username is:"+userInfo.getName()); //log.info("delete {} information..."+userInfo.getName()); //dao.delete(userInfo); } //  public void save(String xml) { //      //UserInfo userInfo = (UserInfo)object; //      log.info("add {} user..."+xml); //      //dao.save(userInfo); //      System.out.println("ssss"); //  } public void save(UserInfoDTO dto,boolean flag) { System.out.println("name:"+dto.getName()); } public void update(String xml){ ApplicationContext context = new ClassPathXmlApplicationContext( "applicationContext-resources.xml"); this.dao = (HibernateDao)context.getBean("dao"); try { JAXBContext jaxbContext = JAXBContext.newInstance("com.itdcl.model"); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); StringReader reader = new StringReader(xml); Customers cus = (Customers)unmarshaller.unmarshal(reader); Customer cust = cus.getCustomer(); UserInfo userInfo = new UserInfo(); System.out.println("Address:"+cust.getAddress()); userInfo.setAddress(cust.getAddress()); System.out.println("Age:"+cust.getAge()); userInfo.setAge(Integer.valueOf(cust.getAge())); System.out.println("Name:"+cust.getName()); //userInfo.setId(2); userInfo.setName(cust.getName()); dao.save(userInfo); } catch (JAXBException e) { e.printStackTrace(); } } public String get(int id){ //return dao.get(id); return null; } }
DAO与Service接口配置:
<?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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jaxws="http://cxf.apache.org/jaxws" xsi:schemaLocation=" http://cxf.apache.org/jaxws  http://cxf.apache.org/schemas/jaxws.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd"> <!--*******************Hibernate数据库持久层配置文件***********************--> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:jdbc.properties</value> </list> </property> </bean> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="${driverClassName}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource"> <ref local="dataSource" /> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect"> ${hibernate.dialect} </prop> <prop key="hibernate.show_sql">${show_sql}</prop> <prop key="hibernate.format_sql">${format_sql}</prop> <!-- 缓存设置 --> <prop key="cache.use_query_cache"> ${cache.use_query_cache} </prop> <prop key="cache.use_second_level_cache"> ${cache.use_second_level_cache} </prop> <prop key="cache.provider_class"> ${cache.provider_class} </prop> <!-- C3P0连接池配置 --> <prop key="c3p0.acquire_increment"> ${c3p0.acquire_increment} </prop> <prop key="c3p0.max_statements"> ${c3p0.max_statements} </prop> <prop key="c3p0.min_size">${c3p0.min_size}</prop> <prop key="c3p0.max_size">${c3p0.max_size}</prop> <prop key="c3p0.timeout">${c3p0.timeout}</prop> <prop key="c3p0.idle_test_period"> ${c3p0.idle_test_period} </prop> </props> </property> <property name="namingStrategy"> <bean class="org.hibernate.cfg.ImprovedNamingStrategy" /> </property> <property name="packagesToScan" value="com.itdcl.pojo" /> </bean> <bean id="dao" class="com.itdcl.dao.HibernateDaoImpl"> <property name="sessionFactory" ref="sessionFactory" /> </bean> </beans>
WebService接口发布:
<?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" xsi:schemaLocation=" http://www.springframework.org/schema/beans  http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://cxf.apache.org/jaxws  http://cxf.apache.org/schemas/jaxws.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" /> <bean id="serverUserInfo" class="com.itdcl.model.UserInfoDTO" /> <jaxws:endpoint id="helloWorld" implementor="com.itdcl.service.HelloWorldImpl" address="/HelloWorld" /> <jaxws:endpoint id="myTest" implementor="com.itdcl.service.MyTestImpl" address="/MyTest" /> <jaxws:endpoint id="service" implementor="com.itdcl.service.ServiceImpl" address="/Service"> <!--  jaxws:serviceFactory> <ref bean="jaxWsServiceFactoryBean" /> </jaxws:serviceFactory>--> </jaxws:endpoint> <bean id="jaxWsServiceFactoryBean" class="org.apache.cxf.jaxws.support.JaxWsServiceFactoryBean"> <property name="wrapped" value="true" /> <property name="dataBinding" ref="aegisBean" /> </bean> <bean id="aegisBean" class="org.apache.cxf.aegis.databinding.AegisDatabinding" /> </beans>
第三步:服务端程序编写了,打包部署 客户端开发 第一步:WebService客户端生成,可以手工编写。这里我就通过配置Ant文件来生成WebService客户端:
<?xml version="1.0"?> <project name="cxf" basedir="." default="usage"> <property name="webroot.dir" value="E:/workspace3/CXFSpring" /> <!-- webservice接口 --> <property name="target.class" value="com.itdcl.service.IService" /> <property name="wsdl.name" value="Service.wsdl" /> <property name="src.dir" value="src" /> <property name="client.dir" value="client" /> <property name="server.dir" value="server" /> <property name="compile.dir" value="${webroot.dir}/bin" />   <target name="usage"> <echo message="java2wsdl         -->java文件生成wsdl文件,java2wsdl -Ddir=com/starit/cxf/java2wsdl -Dsrc=com.starit.cxf.java2wsdl.Hello" /> <echo message="wsdl2javaClient       -->java文件生成client,java2wsdl -Ddir=com/starit/cxf/java2wsdl -Dwsdl=hello.wsdl" /> </target> <target name="java2wsdl"> <echo message="生成wsdl文件" /> <exec dir="${compile.dir}" executable="cmd.exe"> <arg line="/c java2ws" /> <arg line="-o ${wsdl.name} -wsdl ${target.class}" /> </exec> <!-- copy资源文件 --> <move todir="${src.dir}" preservelastmodified="true"> <fileset dir="${compile.dir}"> <include name="**/*.wsdl" /> </fileset> </move> </target>   <target name="wsdl2javaClient"> <echo message="生成java client文件" /> <mkdir dir="${client.dir}" /> <exec dir="." executable="cmd.exe"> <arg line="/c wsdl2java" /> <!-- 生成的java所存目录 --> <arg line="-d ${client.dir}"/> <!-- wsdl文件所在路径 --> <arg line="-client src/*.wsdl" /> </exec> </target> </project>
第二步:WebService接口注册配置
<?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" xsi:schemaLocation=" http://www.springframework.org/schema/beans  http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://cxf.apache.org/jaxws  http://cxf.apache.org/schemas/jaxws.xsd">   <!--  jaxws:client id="helloWorldClient" address="http://localhost:9999/cxf/HelloWorld" serviceClass="com.itdcl.service.IHelloWorld" />-->   <!--  jaxws:client id="myTestClient" address="http://localhost:9999/cxf/MyTest" serviceClass="com.itdcl.service.IMyTest" />-->   <jaxws:client id="service" address="http://localhost:9999/cxf/Service" serviceClass="com.itdcl.service.IService" /> </beans>
剩下的事就测试我们整合是否成功了,编写一个JUnit测试类或写一个Main函数测试一下。
public class JaxbSampleClient { private final static String MODEL = "com.itdcl.model"; public static void main(String[] args) throws FileNotFoundException, JAXBException, ParserConfigurationException, TransformerException { ApplicationContext context = new ClassPathXmlApplicationContext( "beans.xml"); IService service = (IService) context.getBean("service");     ObjectFactory factory = new ObjectFactory(); Customer customer = factory.createCustomer(); customer.setId(1); customer.setAge("26"); customer.setName("Josen"); customer.setAddress(100);   Customers customers = factory.createCustomers(); customers.setCustomer(customer);   DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.newDocument();   // 转换 JAXBContext jaxbContext = JAXBContext.newInstance(MODEL); Marshaller marshaller = jaxbContext.createMarshaller(); //将customers数据与doc绑定 marshaller.marshal(customers, doc);   DOMSource domSource = new DOMSource(doc); StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.transform(domSource, result); String xmlString = writer.toString(); //System.out.println(xmlString);   service.update(xmlString); }   }
运行一下,看插入数据库没有。这节到此就靠一段落啦,下节讲解WS-Security
正文到此结束
Loading...