cxf spring mybiats

原创
2015/05/27 10:26
阅读数 183

spring里面的dao啊service啊 什么的还有mybiats配置文件之类的 这里就只列一个例子 
主要的还是webservice cxf

先把重点拿出来

最下面会把整个例子项目打包给大家

先是webservice接口方法实现类

package org.wsdl.cxf.ws.impl;

import java.util.Date;
import java.util.List;

import javax.jws.WebParam;
import javax.jws.WebService;

import org.wsdl.domain.ArrayOf_tns2_SubInfo;
import org.wsdl.domain.Cat;
import org.wsdl.domain.User;
import org.wsdl.service.UserService;
import org.wsdl.service.test;
import org.wsdl.until.LogUntil;
import org.wsdl.cxf.ws.HelloWord;
/**
 * 此类是webservice的实现接口,在此类中定义需要暴露的方法,
 * 其中的service需要在applicationContext.xml里配置spring注入
 * 如果自定义参数名需要在接口HelloWord里参数前加@WebParam(name="name")来标识此元素,防止参数自动变成arg0
 * @param zhouxs
 */

@WebService(endpointInterface="org.wsdl.cxf.ws.HelloWord",serviceName="Ws")
public class HelloWordWs implements HelloWord{
    private UserService us;
    private test test;
    
 
    @Override
    public String SayHi( String name) {
          LogUntil loginfo= new LogUntil();
          loginfo.writeLogInfo("进入SayHi方法");
        return name+",你好 现在时间是"+new Date();
    }

    @Override
    public List<Cat> getCatsByUser(User user) {
          LogUntil loginfo= new LogUntil();
          loginfo.writeLogInfo("进入getCatsByUser方法");
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        return us.getCatByUser(user);
    }

    @Override
    public  void insertCat(List<Cat>  s) {
          LogUntil loginfo= new LogUntil();
          loginfo.writeLogInfo("进入insertCat方法");
         test.insertCat(s);
    }
    

    @Override
    public List<Cat> Test(User user) {
          LogUntil loginfo= new LogUntil();
          loginfo.writeLogInfo("进入Test方法");
          try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return  test.getCatsByUser(user);
    }
    

    public UserService getUs() {
        return us;
    }

    public void setUs(UserService us) {
        this.us = us;
    }

    public test getTest() {
        return test;
    }

    public void setTest(test test) {
        this.test = test;
    }

    @Override
    public String orderRelationUpdateNotifyRequest(String recordSequenceId,
            ArrayOf_tns2_SubInfo subNotify) {
        // TODO Auto-generated method stub
        return null;
    }


   
}

接口

package org.wsdl.cxf.ws;

import java.util.List;

import javax.jws.WebParam;
import javax.jws.WebService;

import org.wsdl.domain.ArrayOf_tns2_SubInfo;
import org.wsdl.domain.Cat;
import org.wsdl.domain.User;

@WebService
public interface HelloWord {
  String SayHi(@WebParam(name="name") String name );
  List <Cat> getCatsByUser(User user);
  List <Cat> Test(User user);
 void insertCat(List<Cat> s);
 
 
 public String orderRelationUpdateNotifyRequest(String recordSequenceId,ArrayOf_tns2_SubInfo subNotify);


}

拦截器

package org.wsdl.cxf.ws.auth;

import java.util.List;

import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.headers.Header;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;


/*
 *此拦截器用于添加消息帐号密码验证(可不用) 
 * 
 * 
 * 
 */

//通过PhaseInterceptor可以指定拦截器在哪个阶段起作用
public class AuthInterceptor extends AbstractPhaseInterceptor<SoapMessage> {

    public AuthInterceptor() {
        //显式调用父类有参数构造器
        //显式调用父类构造器后程序将不会隐式调用无参数构造器
        super(Phase.PRE_INVOKE);//在调用之前获取soap消息
    }

    //实现自己拦截器时,需要实现handleMessage方法
    //handleMessage形参就是得到的sopa消息
    @Override
    public void handleMessage(SoapMessage msg) throws Fault {

        System.out.println("==========="+msg);
    /*    //得到消息的head
        List<Header> headers=msg.getHeaders();
        if(headers==null||headers.size()<1){
            throw new Fault(new IllegalArgumentException("没有账号密码不允许访问"));
        }*/
    }

}

dao的实现类

package org.wsdl.dao.impl;

import java.util.List;

import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.wsdl.dao.TestDao;
import org.wsdl.domain.Cat;
import org.wsdl.domain.User;

public class TestDaoImpl extends SqlSessionDaoSupport implements TestDao {

    @Override
    public List<Cat> getCatsByUser(User user) {
        return getSqlSession().selectList("getCatsByUser", user);
    }

    @Override
    public void insertCat(Cat cat) {
        getSqlSession().insert("insertCat", cat);
    }

}

service实现类

package org.wsdl.service.impl;

import java.util.List;

import org.springframework.transaction.annotation.Transactional;
import org.wsdl.dao.TestDao;
import org.wsdl.domain.Cat;
import org.wsdl.domain.User;
import org.wsdl.service.test;

@Transactional
public class testImpl implements test {
private TestDao testDao;
    @Override
    public List<Cat> getCatsByUser(User user) {
        
        return testDao.getCatsByUser(user);
    }
    public TestDao getTestDao() {
        return testDao;
    }
    public void setTestDao(TestDao testDao) {
        this.testDao = testDao;
    }
    @Override
    public void insertCat(List<Cat> s) {
        for (int i=0;i<s.size();i++)
        {
            testDao.insertCat(s.get(i));
        }
    }

}

sql文件getCatmap.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> 
<mapper namespace="test">


 <select id="getCatsByUser" parameterType="org.wsdl.domain.User" resultType="org.wsdl.domain.Cat">
        <![CDATA[
        SELECT * FROM cat where  id=#{id}
                     ]]>
</select>
<insert id="insertCat" parameterType="org.wsdl.domain.Cat" >
<![CDATA[  
insert into cat (id,name,color)values (#{ID},#{NAME},#{COLOR})
 ]]>
</insert>
</mapper>

sql的配置文件Configuration.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <mappers>
        <!--查猫  -->
    <mapper resource="org/wsdl/maps/getCatmap.xml"/>
      
    </mappers> 

</configuration>

spring配置文件applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:jaxws="http://cxf.apache.org/jaxws"
    xmlns:tx="http://www.springframework.org/schema/tx"
     xmlns:context="http://www.springframework.org/schema/context"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
    http://cxf.apache.org/jaxws
    http://cxf.apache.org/schemas/jaxws.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">
         <context:component-scan base-package="com.mtea" /> 
      <!--数据库连接池  -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
        destroy-method="close">
        <property name="driverClass" value="oracle.jdbc.driver.OracleDriver" />
        <property name="jdbcUrl" value="jdbc:oracle:thin:@XXXXXXXXXX:1521:orcl" /> 
        <property name="user" value="XXXX" />
        <property name="password" value="XXXX" />
        <property name="minPoolSize" value="1" />
        <property name="maxPoolSize" value="30" />
        <property name="initialPoolSize" value="1" />
        <property name="testConnectionOnCheckout" value="false" />
        <property name="maxIdleTime" value="2400" />
        <property name="maxStatements" value="0" />
    </bean>
    
    
    
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="configLocation" value="classpath:Configuration.xml" />
        <property name="dataSource" ref="dataSource" />
    </bean>  
         
       <!-- transaction support-->
    <!-- PlatformTransactionMnager -->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
        <!-- enable transaction annotation support -->
    <tx:annotation-driven transaction-manager="txManager" />
             
         
         <!-- web应用类加载路径 -->
    <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 name="userService" class="org.wsdl.service.impl.UserServiceImpl">
    </bean>  
    
         <bean name="Test" class="org.wsdl.service.impl.testImpl">
         <property name="testDao" ref="tDao"></property>
    </bean>  
         <!-- implementor指定webservice服务提供形式
         A。直接给定服务器提供者的类名   
         B。设置为容器中一个bean 采用
         #后不认为是类名-->
         <bean id="helloWordWs" class="org.wsdl.cxf.ws.impl.HelloWordWs">
         <property name="test" ref="Test"></property>
         <property name="us" ref="userService"></property>
         </bean>
         
             <bean id="tDao" class="org.wsdl.dao.impl.TestDaoImpl">
             <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
            </bean>  
    
    
   <jaxws:endpoint implementor="#helloWordWs" address="/ws">
           <jaxws:inInterceptors>
               <bean class="org.apache.cxf.interceptor.LoggingInInterceptor" />
           </jaxws:inInterceptors>
    </jaxws:endpoint>
   
</beans>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <context-param>
        <param-name>contextConfigLoction</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>
    <listener>
        <!--保证在web应用启动时加载spring容器 -->
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!-- 下面配置表明所有来自/ws/*请求都交给CXFServlet处理 -->
    <servlet>
    <servlet-name>cxf</servlet-name>
    <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
    </servlet>
    <servlet-mapping>
    <servlet-name>cxf</servlet-name>
    <url-pattern>/ws/*</url-pattern>
    </servlet-mapping>
    
    
</web-app>

cxf-spring 下载


如果大家不用web程序 也可以写成小程序来执行 这时候配置文件变化下  再写个服务端就ok啦 

详情也会给大家在最下面发出来

applicationContext.xml内容

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:sec="http://cxf.apache.org/configuration/security"
  xmlns:http="http://cxf.apache.org/transports/http/configuration"
  xmlns:httpj="http://cxf.apache.org/transports/http-jetty/configuration"
    xmlns:jaxws="http://cxf.apache.org/jaxws"
    xmlns:tx="http://www.springframework.org/schema/tx"
     xmlns:context="http://www.springframework.org/schema/context"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
    http://cxf.apache.org/configuration/security
      http://cxf.apache.org/schemas/configuration/security.xsd
    http://cxf.apache.org/transports/http/configuration
    http://cxf.apache.org/schemas/configuration/http-conf.xsd
    http://cxf.apache.org/transports/http-jetty/configuration
    http://cxf.apache.org/schemas/configuration/http-jetty.xsd
    http://cxf.apache.org/jaxws
    http://cxf.apache.org/schemas/jaxws.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">
         <context:component-scan base-package="com.mtea" /> 
      <!--数据库连接池  -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
        destroy-method="close">
        <property name="driverClass" value="oracle.jdbc.driver.OracleDriver" />
        <property name="jdbcUrl" value="jdbc:oracle:thin:@133.224.7.162:1521:orcl" /> 
        <property name="user" value="ca_new" />
        <property name="password" value="ca_new" />
        <property name="minPoolSize" value="1" />
        <property name="maxPoolSize" value="30" />
        <property name="initialPoolSize" value="1" />
        <property name="testConnectionOnCheckout" value="false" />
        <property name="maxIdleTime" value="2400" />
        <property name="maxStatements" value="0" />
    </bean>
    
    
    
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="configLocation" value="classpath:Configuration.xml" />
        <property name="dataSource" ref="dataSource" />
    </bean>  
         
       <!-- 注解支持-->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
    <tx:annotation-driven transaction-manager="txManager" />
             
   <!--       
         web应用类加载路径
    <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 name="userService" class="org.wsdl.service.impl.UserServiceImpl">
    </bean>  
    
         <bean name="Test" class="org.wsdl.service.impl.testImpl">
         <property name="testDao" ref="tDao"></property>
    </bean>  
         <!-- implementor指定webservice服务提供形式
         A。直接给定服务器提供者的类名   
         B。设置为容器中一个bean 采用
         #后不认为是类名-->
         <bean id="helloWordWs" class="org.wsdl.cxf.ws.impl.HelloWordWs">
         <property name="test" ref="Test"></property>
         <property name="us" ref="userService"></property>
         </bean>
         
             <bean id="tDao" class="org.wsdl.dao.impl.TestDaoImpl">
             <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
            </bean>  
    
    <!-- jetty服务器配置文件 -->
<!--     <httpj:engine-factory bus="cxf" >
    
    <httpj:engine port="9090">
    
      <httpj:tlsServerParametersRef id="secure" />
      <httpj:threadingParameters minThreads="5"
                                 maxThreads="15" />
      <httpj:connector>
        <bean class="org.eclipse.jetty.server.bio.SocketConnector">
        <property name = "port" value="9090"></property>
        </bean>
      </httpj:connector>
      <httpj:handlers>
        <bean class="org.eclipse.jetty.server.handler.DefaultHandler"/>        
      </httpj:handlers>
      <httpj:sessionSupport>true</httpj:sessionSupport>
    </httpj:engine>
  </httpj:engine-factory>  -->
    
   
</beans>

服务器端

Server.java

package ServerMain;

import java.io.IOException;

import javax.xml.ws.Endpoint;


import org.apache.cxf.interceptor.LoggingInInterceptor;
import org.apache.cxf.interceptor.LoggingOutInterceptor;
import org.apache.cxf.jaxws.JaxWsServerFactoryBean;
import org.apache.cxf.transport.Destination;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.wsdl.cxf.ws.HelloWord;
import org.wsdl.cxf.ws.auth.AuthInterceptor;
import org.wsdl.cxf.ws.auth.AuthInterceptorOut;
import org.wsdl.cxf.ws.impl.HelloWordWs;
import org.wsdl.until.LogUntil;

public class Server {

    /**
     * webservice启动方法
     * 若更改发布地址或增加新方法的话需要重新生成客户端
     * 自定义拦截器可加可不加,在拦截器内可获取或者修改soap消息报文头的信息,用来验证
     * 
     * 若做多媒体数据支持请参照http://yufenfei.iteye.com/blog/1685910   用注解@XmlMimeType("application/octet-stream")修改实体类中的参数类型
     * 并在jaxws:endpoint 标签内添加如下配置文件启用MTOM支持(客户端和服务器端都需要开启MTOM的支持)
     *     <jaxws:properties>  
     *   <entry key="mtom-enabled" value="true" />  
     *    </jaxws:properties>  
     * MTOM将数据转换成无编码格式的二进制数据传输,速度更快
     *    
     * @param zhouxs
     * @throws InterruptedException 
     * @throws IOException 
     */
    public static void main(String[] args) throws InterruptedException, IOException {
        ApplicationContext context = new FileSystemXmlApplicationContext("classpath:applicationContext.xml");//手动加载spring
        HelloWord hw=context.getBean("helloWordWs", HelloWordWs.class);//spring注入实现类
        
        //Endpoint e=Endpoint.publish("http://10.64.4.202:9090/cxf_spring/ws/ws?wsdl", hw);//此发布方法无法添加拦截器,若不需要拦截器的话可以打开,删除下面的发布方法
        //调用Endpoint发布webservers
        JaxWsServerFactoryBean factory = new JaxWsServerFactoryBean();

        //设置Service Class

        factory.setServiceClass(HelloWordWs.class);//实现类

        factory.setAddress("http://10.64.4.202:9090/cxf_spring/ws/ws");
       
        //设置ServiceBean对象
        factory.getInInterceptors().add(new AuthInterceptor());//添加自定义进入权限拦截器
          factory.getInInterceptors().add(new LoggingInInterceptor());//添加日志拦截器
        factory.getOutInterceptors().add(new LoggingOutInterceptor());//添加日志拦截器
        factory.getOutInterceptors().add(new AuthInterceptorOut());//添加自定义推出拦截器
         factory.setServiceBean(hw);
        org.apache.cxf.endpoint.Server server= factory.create();
        server.start();
           System.out.println("WebServices 启动成功!");
        LogUntil loginfo= new LogUntil();
        loginfo.writeLogInfo("WebServices 启动成功!服务地址是http://133.224.7.164:9090/cxf_spring/ws/ws");
     
    }

}


两个拦截器一个拦截进来的请 一个拦截出去的消息

AuthInterceptor.java

package org.wsdl.cxf.ws.auth;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;



import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.apache.cxf.tools.common.extensions.soap.SoapBody;
import org.wsdl.until.LogUntil;


/*
 *此拦截器用于添加消息帐号密码验证(可不用) 
 * 
 * 
 * 
 */

//通过PhaseInterceptor可以指定拦截器在哪个阶段起作用
public class AuthInterceptor extends AbstractPhaseInterceptor<SoapMessage> {

    public AuthInterceptor() {
        //显式调用父类有参数构造器
        //显式调用父类构造器后程序将不会隐式调用无参数构造器
        super(Phase.PRE_INVOKE);//在调用之前获取soap消息
    }

    //实现自己拦截器时,需要实现handleMessage方法
    //handleMessage形参就是得到的sopa消息
    @Override
    public void handleMessage(SoapMessage msg) throws Fault {

         LogUntil loginfo= new LogUntil();
            loginfo.writeLogInfo("handleMessage接收消息时触发:");
        /*//得到消息的head
        List<Header> headers=msg.getHeaders();
        
        if(headers==null||headers.size()<1){ 
            throw new Fault(new IllegalArgumentException("没有账号密码不允许访问"));
        }//要求第一个header里携带了用户名密码
            Header firstHeader=  headers.get(0);
            Element ele=   (Element) firstHeader.getObject();
            NodeList  userId= ele.getElementsByTagName("userID");
            NodeList  password= ele.getElementsByTagName("password");
            if(userId.getLength()!=1){
                throw new Fault(new IllegalArgumentException("用户帐号名格式不对"));
            }
            if(userId.getLength()!=1){
                throw new Fault(new IllegalArgumentException("密码格式不对"));
            }
            String uid=userId.item(0).getTextContent();
            String pass=password.item(0).getTextContent();
            //查询数据库看用户名密码是否正确
            //TODO*/
    }

}

AuthInterceptorOut.java拦截出去的请求

package org.wsdl.cxf.ws.auth;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;



import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.apache.cxf.tools.common.extensions.soap.SoapBody;
import org.wsdl.until.LogUntil;


/*
 *此拦截器用于添加消息帐号密码验证(可不用) 
 * 
 * 
 * 
 */

//通过PhaseInterceptor可以指定拦截器在哪个阶段起作用
public class AuthInterceptorOut extends AbstractPhaseInterceptor<SoapMessage> {

    public AuthInterceptorOut() {
        //显式调用父类有参数构造器
        //显式调用父类构造器后程序将不会隐式调用无参数构造器
        super(Phase.WRITE_ENDING);//在写出之后获取soap消息
    }

    //实现自己拦截器时,需要实现handleMessage方法
    //handleMessage形参就是得到的sopa消息
    @Override
    public void handleMessage(SoapMessage msg) throws Fault {

         LogUntil loginfo= new LogUntil();
            loginfo.writeLogInfo("handleMessage发送消息后触发:");
    }

}

app-cxf 下载

展开阅读全文
加载中

作者的其它热门文章

打赏
1
1 收藏
分享
打赏
0 评论
1 收藏
1
分享
返回顶部
顶部
返回顶部
顶部