首先需必备:mysql、myeclipse6.5、apache-cxf-2.6.2
一、建数据库,库名:cxf_demo;表名:book
- CREATE DATABASE `cxf_demo` --数据库
- --表
- CREATE TABLE `book` (
- `id` varchar(32) NOT NULL COMMENT 'id',
- `book_name` varchar(100) DEFAULT NULL COMMENT '名称',
- `author` varchar(100) DEFAULT NULL COMMENT '作者',
- `status` int(11) DEFAULT NULL COMMENT '状态',
- `type_id` varchar(32) DEFAULT NULL COMMENT '类型',
- `price` double DEFAULT NULL COMMENT '金额',
- `brief` varchar(100) DEFAULT NULL COMMENT '简介',
- `book_No` int(11) DEFAULT NULL COMMENT '编号',
- `create_time` datetime DEFAULT NULL COMMENT '创建时间',
- PRIMARY KEY (`id`)
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8
二、好了,现在来建一个web项目名为:myWebservice,大概的package结构如下,大家就将package创建出来吧:
三、建了项目后要将cxf的jar包导入哦,呵呵我不知道哪些cxf jar是必要的,所以就将所有的jar包都导入了,apache-cxf-2.6.2这个版本的。。。
四、好了,现在我们来写resource这个包下面的配置文件,⊙0⊙噢,resource的结构是酱紫滴,看如下图:
我们先来配置数据库jdbc.properties这个文件
- jdbc.driverClassName=com.mysql.jdbc.Driver
- jdbc.url=jdbc:mysql://localhost:3306/cxf_demo?useUnicode=true&characterEncoding=UTF-8&failOverReadOnly=false&maxReconnects=10&autoReconnect=true
- jdbc.username=root
- jdbc.password=root
然后是配置applicationContext-common.xml
- <?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:jee="http://www.springframework.org/schema/jee"
- xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
- xmlns:aop="http://www.springframework.org/schema/aop"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
- http://www.springframework.org/schema/tx
- http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
- http://www.springframework.org/schema/jee
- http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
- http://www.springframework.org/schema/aop
- http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.0.xsd"
- default-lazy-init="true">
- <description>Spring配置</description>
- <!-- 使用annotation 自动注册bean,并检查@Required,@Autowired的属性已被注入 -->
- <context:component-scan base-package="com.cy" />
- <!-- 加载JDBC property文件 -->
- <context:property-placeholder location="classpath*:config/jdbc.properties" ignore-unresolvable="true"/>
- <!-- 连接数据库 -->
- <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
- <property name="driverClassName" value="${jdbc.driverClassName}"/>
- <property name="url" value="${jdbc.url}"/>
- <property name="username" value="${jdbc.username}"/>
- <property name="password" value="${jdbc.password}"/>
- <!-- Connection Pooling Info -->
- <!-- <property name="initialSize" value="1" /> 初始化连接数量 -->
- <property name="maxIdle" value="5" /><!-- 最大等待连接中的数量,设 0 为没有限制 -->
- <property name="minIdle" value="1"/><!-- 最小等待连接中的数量,设 0 为没有限制 -->
- <property name="maxActive" value="25" /><!-- 连接池的最大数据库连接数。设为0表示无限制。 -->
- <!-- <property name="maxWait" value="60000"/> 最大建立连接等待时间。如果超过此时间将接到异常。设为-1表示无限制。 -->
- <!-- <property name="timeBetweenEvictionRunsMillis" value="3600000" /> -->
- <!-- <property name="minEvictableIdleTimeMillis" value="3600000" /> -->
- <!-- <property name="removeAbandoned" value="true" />强制自我中断避免dbcp自身bug出现连接过久资源耗尽-->
- <!-- <property name="removeAbandonedTimeout" value="60" />自我中断时间秒 -->
- </bean>
- <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
- <property name="dataSource" ref="dataSource"/>
- </bean>
- <!-- 使用annotation定义事务 -->
- <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />
- <!-- ibatis -->
- <bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
- <property name="configLocation" value="classpath:sqlmap-config.xml"/>
- <property name="dataSource" ref="dataSource"/>
- </bean>
- <!-- 配置切面 -->
- <aop:config>
- <aop:aspect id="logAspecter" ref="logAspcet">
- <aop:pointcut id="mypointcut" expression="execution(* com.cy.*.service.impl.*.*(..))"/>
- </aop:aspect>
- </aop:config>
- </beans>
五、好啦,现在我们来写dto在Book.java文件里
- package com.cy.business.dto;
- import java.util.Date;
- public class Book {
- private static final long serialVersionUID = -2672626820160275114L;
- private String id;
- private String bookName;
- private String author;
- private String typeId;
- private Double price;
- private String brief;
- private Integer bookNo;
- private Integer status;
- private Date createTime;
- public String getId() {
- return id;
- }
- public void setId(String id) {
- this.id = id;
- }
- public String getBookName() {
- return bookName;
- }
- public void setBookName(String bookName) {
- this.bookName = bookName;
- }
- public String getAuthor() {
- return author;
- }
- public void setAuthor(String author) {
- this.author = author;
- }
- public String getTypeId() {
- return typeId;
- }
- public void setTypeId(String typeId) {
- this.typeId = typeId;
- }
- public Double getPrice() {
- return price;
- }
- public void setPrice(Double price) {
- this.price = price;
- }
- public String getBrief() {
- return brief;
- }
- public void setBrief(String brief) {
- this.brief = brief;
- }
- public Integer getBookNo() {
- return bookNo;
- }
- public void setBookNo(Integer bookNo) {
- this.bookNo = bookNo;
- }
- public Integer getStatus() {
- return status;
- }
- public void setStatus(Integer status) {
- this.status = status;
- }
- public Date getCreateTime() {
- return createTime;
- }
- public void setCreateTime(Date createTime) {
- this.createTime = createTime;
- }
- }
然后咧,就是在sqlmap文件夹里写Book_SqlMap.xml与dto关联哦:
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE sqlMap PUBLIC "-//iBATIS.com//DTD SQL Map 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-2.dtd">
- <!-- 定义命名空间 -->
- <sqlMap namespace="BookNS">
- <!-- 定义缓存 -->
- <cacheModel id="Book_Cache" type="OSCACHE" readOnly="true">
- <flushInterval hours="24" />
- <!-- 配置哪些SQL将清空缓存 -->
- <flushOnExecute statement="saveBook" />
- <flushOnExecute statement="deleteBook" />
- <flushOnExecute statement="updateBook" />
- <flushOnExecute statement="changeBookStatus" />
- <property name="size" value="1000" />
- </cacheModel>
- <!-- 对象引用 -->
- <typeAlias alias="BookPo" type="com.cy.business.dto.Book"/>
- <!-- 定义结果 -->
- <resultMap class="BookPo" id="BookPo_Result">
- <result column="id" property="id" />
- <result column="book_name" property="bookName" />
- <result column="author" property="author" />
- <result column="type_id" property="typeId" />
- <result column="price" property="price" />
- <result column="brief" property="brief" />
- <result column="book_No" property="bookNo" />
- <result column="status" property="status" />
- <result column="create_time" property="createTime"/>
- </resultMap>
- <select id="queryBook" parameterClass="BookPo" resultMap="BookPo_Result" cacheModel="Book_Cache">
- select * from book
- <dynamic prepend=" WHERE ">
- <isNotEmpty property="id" prepend="and">
- id=#id:VARCHAR#
- </isNotEmpty>
- <isNotEmpty property="bookName" prepend="and">
- instr(book_Name,#bookName:VARCHAR#)
- </isNotEmpty>
- <isNotEmpty property="author" prepend="and">
- instr(author,#author:VARCHAR#)
- </isNotEmpty>
- <isNotEmpty property="bookNo" prepend="and">
- book_No=#bookNo:VARCHAR#
- </isNotEmpty>
- </dynamic>
- </select>
- <insert id="saveBook" parameterClass="BookPo">
- insert into book(id,book_name,author,type_id,price,brief,book_no,status,create_time)
- values(#id#,#bookName#,#author#,#typeId#,#price#,#brief#,#bookNo#,0,sysdate());
- </insert>
- <update id="changeBookStatus" parameterClass="BookPo">
- <![CDATA[
- update book set status=#status# where id=#id#
- ]]>
- </update>
- <update id="updateBook" parameterClass="BookPo">
- <![CDATA[
- update book set book_name=#bookName#,author=#author#,type_id=#typeId#
- ,price=#price#,brief=#brief#,book_no=#bookNo# where id=#id#
- ]]>
- </update>
- <delete id="deleteBook" parameterClass="BookPo">
- <![CDATA[
- delete from book where id=#id#
- ]]>
- </delete>
- </sqlMap>
写完这些,然后来实现业务逻辑层,这些添删改查功能。。。
接口IBookService.java
- package com.cy.business.service;
- import java.util.List;
- import com.cy.business.dto.Book;
- public interface IBookService {
- public List<Book> findBook(Book book);
- public boolean updateBook(Book book);
- public boolean deleteBook(Book book);
- public boolean changeBookStatus(Book book);
- public boolean saveBook(Book book);
- }
实现接口方法BookService.java
- package com.cy.business.service.impl;
- import java.util.List;
- import javax.annotation.Resource;
- import javax.inject.Inject;
- import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;
- import org.springframework.stereotype.Service;
- import org.springframework.transaction.annotation.Transactional;
- import com.cy.business.dto.Book;
- import com.cy.business.service.IBookService;
- import com.ibatis.sqlmap.client.SqlMapClient;
- @Service
- @Transactional
- public class BookService extends SqlMapClientDaoSupport implements IBookService {
- //及其重要,完成进行注入
- @Inject
- @Resource(name="sqlMapClient")
- public void setSuperSqlMapClient(SqlMapClient sqlMapClient) {
- super.setSqlMapClient(sqlMapClient);
- }
- public boolean changeBookStatus(Book book) {
- try {
- int result = this.getSqlMapClientTemplate().update("changeBookStatus", book);
- if (result > 0) {
- return true;
- } else {
- return false;
- }
- } catch (Exception e) {
- return false;
- }
- }
- public boolean deleteBook(Book book) {
- try {
- int result = this.getSqlMapClientTemplate().delete("deleteBook", book);
- if (result > 0) {
- return true;
- } else {
- return false;
- }
- } catch (Exception e) {
- return false;
- }
- }
- @SuppressWarnings("unchecked")
- public List<Book> findBook(Book book) {
- try {
- return this.getSqlMapClientTemplate().queryForList("queryBook", book);
- } catch (Exception e) {
- e.printStackTrace();
- return null;
- }
- }
- public boolean saveBook(Book book) {
- try {
- this.getSqlMapClientTemplate().insert("saveBook", book);
- return true;
- } catch (Exception e) {
- e.printStackTrace();
- return false;
- }
- }
- public boolean updateBook(Book book) {
- try {
- int result = this.getSqlMapClientTemplate().update("updateBook", book);
- if (result > 0) {
- return true;
- } else {
- return false;
- }
- } catch (Exception e) {
- e.printStackTrace();
- return false;
- }
- }
- }
嗯,完成这些,就开始来写webservice接口咯,在package名为webservice下,
接口IMyWebservice.java
- package com.cy.webservice;
- import javax.jws.WebMethod;
- import javax.jws.WebParam;
- import javax.jws.WebService;
- import org.springframework.stereotype.Component;
- import com.cy.business.dto.Book;
- @WebService(name = "IMyWebservice", targetNamespace = "http://webservice.cy.com/")
- @Component()
- public interface IMyWebservice {
- @WebMethod(operationName = "pushData", action = "urn:PushData")
- public boolean pushData(@WebParam(name="book")Book book);
- }
实现类MyWebService.java
- package com.cy.webservice.impl;
- import java.util.List;
- import javax.annotation.Resource;
- import javax.jws.WebService;
- import com.cy.business.dto.Book;
- import com.cy.business.service.IBookService;
- import com.cy.webservice.IMyWebservice;
- @WebService(targetNamespace = "http://impl.webservice.cy.com/", portName = "MyWebservicePort", serviceName = "MyWebservice")
- public class MyWebService implements IMyWebservice {
- @Resource
- private IBookService bookService;
- public boolean pushData(Book book) {
- try {
- System.out.println("进入webservice了。。。");
- boolean flag = bookService.saveBook(book);//先保存数据
- if(flag){
- Book bk = new Book();
- bk.setBookNo(89757);
- List<Book> list = bookService.findBook(book);
- if(list!=null && !list.isEmpty()){//然后更改数据。。。
- bk = new Book();
- bk = list.get(0);
- bk.setStatus(1);
- bk.setBookName("岑逸951560368");
- return bookService.updateBook(bk);
- }else{
- return false;
- }
- }else{
- return false;
- }
- } catch (Exception e) {
- e.printStackTrace();
- return false;
- }
- }
- }
⊙0⊙这样我们就写完了?还木有哦,别忘了在resource包下还有个配置文件还木有写哈。。。applicationContext-cxf.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:jaxws="http://cxf.apache.org/jaxws" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:jee="http://www.springframework.org/schema/jee"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
- http://cxf.apache.org/jaxws
- http://cxf.apache.org/schemas/jaxws.xsd"
- default-lazy-init="true">
- <bean id="myWebservice" class="com.cy.webservice.impl.MyWebService"></bean>
- <jaxws:endpoint address="/myWebservice" implementor="#myWebservice"></jaxws:endpoint>
- </beans>
六、好啦,我们的工作做了一大半了!现在来让我们运行一下这个webservice吧,在项目http://localhost:8080/myWebservice/后边需要加上"service",这是因为在web.xml中我们这么配置的,大家还记得吧继续
- <servlet-mapping>
- <servlet-name>cxf</servlet-name>
- <url-pattern>/service/*</url-pattern>
- </servlet-mapping>
能够打开这个就说明你成功了................................................................一大半,为嘛这么说呢,因为还需要测试啊!!!
你打开超链接WSDL : {http://impl.webservice.cy.com/}MyWebservice会来到这个界面
哈哈,你的webservice写的差不多了,开心吧。。。
七、那俺们现在开始写客户端来测试一下,要有耐心哦。。。马上就成功鸟。。。
建一个名为myWebclient的JavaProject,大家跟着我建吧。。。看如下图package结构:
我们通过myeclipse6.5来快捷的创建客户端。。。
来看图操作。我们将编译文件放在webservice这个包下,选择webservice这个包,new->other
搜索出这个工具哦,然后next->next会有如下界面 wsdl url这个地址就是刚才打开的http://localhost:8080/myWebservice/service/myWebservice?wsdl
然后next->到下一个图了,切记myWebservice这个项目一定是部署了正在运行的哦!!!
finish之后,所以的文件编译完成了!
八、我们现在来完成webUtil这个package下的文件吧!
Util.java文件
- package com.cy.client.webUtil;
- import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
- public class Util {
- @SuppressWarnings({ "unchecked" })
- public static Object getService(Class clazz, String url){
- JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
- Object srv = null;
- factory.setServiceClass(clazz);
- factory.setAddress(url);
- srv=(Object) factory.create();
- return srv;
- }
- }
UtilWebService.java文件是连接webservice的接口地址:
- package com.cy.client.webUtil;
- import com.cy.client.webservice.IMyWebservice;
- public class UtilWebService {
- public static IMyWebservice getMyWebService(){
- String url="http://localhost:8080/myWebservice/service/myWebservice?wsdl";
- IMyWebservice service = (IMyWebservice) Util.getService(IMyWebservice.class,url);
- return service;
- }
- }
现在我们在client包下建Client.java客户端
- package com.cy.client;
- import java.util.UUID;
- import com.cy.client.webUtil.UtilWebService;
- import com.cy.client.webservice.Book;
- import com.cy.client.webservice.IMyWebservice;
- public class Client {
- private IMyWebservice myWebservice;
- public boolean getBookInfo(){
- myWebservice = UtilWebService.getMyWebService();
- // 创建 GUID 对象
- UUID uuid = UUID.randomUUID();
- // 得到对象产生的ID
- String a = uuid.toString();
- // 转换为大写
- a = a.replaceAll("-", "");
- Book book = new Book();
- book.setId(a);
- book.setAuthor("岑逸");
- book.setBookName("随园诗话");
- book.setBookNo(89757);
- book.setBrief("哈哈");
- return myWebservice.pushData(book);
- }
- public static void main(String[] args) {
- boolean flag = new Client().getBookInfo();
- System.out.println("推送:"+flag);
- }
- }
运行一下吧。。。哈哈成功了!!!数据库也有数据了!!!有木有花了一个多小时
非常感谢本文的作者,原文地址:http://blog.csdn.net/cenyi2013/article/details/17315755