Spring+Apache CXF+MyBatis+Maven实例

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/liuxing9345/article/details/77983755

概述

  • 本实例是一个简单的Spring+Apache CXF+MyBatis+Maven的集成小项目,可以略作参考
  • 数据库使用的是mysql,ORM框架使用的是MyBatis。其中实体类和mapper接口以及映射文件可以使用MyBatis-Generator工具生成,就不在此赘述了
  • 本实例将springmvc的使用简单配置了一下,包括数据源、mybatis session 工厂、spring事务管理等等。深入使用请参考官网开发文档或者书籍
  • 案例最后我会将源代码以及数据库sql文件上传。另外,在cxf的实现中加了一个简单的拦截器UserCheckInterceptor,该拦截器可以实现用户名密码验证功能。初次运行的朋友可能会有点儿疑惑,不明白这个拦截器的逻辑,这里简单说明一下。我是将用户与服务进行了绑定。打个比方,用户root只能访问/userService,用户admin只能访问/calculateService。因此,在客户端调用服务的时候,不仅要将正确的用户名密码传过去,并且还只能访问该用户可以访问的服务,其他服务则不能访问。

第1节 引入maven依赖

<dependencies>
    <dependency>
        <groupId>commons-lang</groupId>
        <artifactId>commons-lang</artifactId>
        <version>2.6</version>
    </dependency>
    <!-- 用于处理restful json转换 -->
    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-jaxrs</artifactId>
        <version>1.9.2</version>
    </dependency>
    <!-- 
        https://mvnrepository.com/artifact/javax.ws.rs/javax.ws.rs-api 
        用于实现 restful 风格的 API
    -->
    <dependency>
        <groupId>javax.ws.rs</groupId>
        <artifactId>javax.ws.rs-api</artifactId>
        <version>2.0.1</version>
    </dependency>
    <!--================= apache cxf begin =================-->
    <dependency>
        <groupId>org.apache.cxf</groupId>
        <artifactId>cxf-rt-frontend-jaxws</artifactId>
        <version>${cxf.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.cxf</groupId>
        <artifactId>cxf-rt-transports-http</artifactId>
        <version>${cxf.version}</version>
    </dependency>
    <dependency>  
        <groupId>org.apache.cxf</groupId>  
        <artifactId>cxf-rt-frontend-jaxrs</artifactId>  
        <version>${cxf.version}</version>  
    </dependency>
    <dependency>
        <groupId>org.apache.cxf</groupId>
        <artifactId>cxf-rt-ws-security</artifactId>
        <version>${cxf.version}</version>
    </dependency>
    <!--================= apache cxf end =================-->

    <!--================= spring begin =================-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aop</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-expression</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aspects</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <!--================= spring end =================-->

    <!--================= servlet begin =================-->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>jsp-api</artifactId>
        <version>2.1</version>
    </dependency>
    <!--================= servlet end =================-->

    <!--================= database begin =================-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.38</version>
    </dependency>
    <dependency>
        <groupId>c3p0</groupId>
        <artifactId>c3p0</artifactId>
        <version>0.9.1.2</version>
    </dependency>
    <!--================= database end =================-->

    <!--================= mybatis begin =================-->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.4.2</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>1.3.1</version>
    </dependency>
    <!--================= mybatis end =================-->

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>
</dependencies>

另外,建议在maven中加上bundle插件,可能有些依赖是以bundle形式发布,如下

<plugin>
    <groupId>org.apache.felix</groupId>
    <artifactId>maven-bundle-plugin</artifactId>
    <version>3.3.0</version>
</plugin>

第2节 数据库设计,数据库名spring_cxf,表截图如下

这里写图片描述

数据库sql文件会放在打包的项目文件当中一起上传

第3节 在web.xml文件中加上springmvc、spring容器以及cxf的配置

3-1 在web.xml文件中配置springmvc容器

<servlet>
    <servlet-name>DispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:beans-mvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>DispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

另外,beans-mvc.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:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd">

    <context:component-scan base-package="com.study.springcxf.action" />

    <mvc:default-servlet-handler/>
    <mvc:annotation-driven />

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/" />
        <property name="suffix" value=".jsp" />
    </bean>

</beans>

3-2 在web.xml文件中配置spring容器

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:beans-core.xml</param-value>
</context-param>
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

beans-core.xml文件配置如下,其中<import resource="classpath:beans-cxf.xml"/>即引入的Apache CXF配置文件

<?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:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd">

    <import resource="classpath:beans-cxf.xml"/>

    <context:component-scan base-package="com.study.springcxf">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!-- 1.配置数据源 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="user" value="root" />
        <property name="password" value="0000"/>
        <property name="jdbcUrl" value="jdbc:mysql:///spring_cxf" />
        <property name="driverClass" value="com.mysql.jdbc.Driver" />
        <property name="initialPoolSize" value="5" />
        <property name="minPoolSize" value="5"/>
        <property name="maxPoolSize" value="10" />
    </bean>

    <!-- 2.配置 sessionFactory -->
    <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="mapperLocations" value="classpath:com/study/springcxf/mapper/*Mapper.xml" />
        <property name="configLocation" value="classpath:mybatis-config.xml" />
    </bean>

    <!-- 3.配置自动扫描映射文件的bean -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.study.springcxf.mapper" />
        <property name="sqlSessionFactoryBeanName" value="sessionFactory" />
    </bean>

    <!-- 4.配置事务管理器 -->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- 5.配置事务通知属性 -->
    <tx:advice id="txAdvice" transaction-manager="txManager">
        <tx:attributes>
            <tx:method name="insert*" propagation="REQUIRED"/>
            <tx:method name="update*" propagation="REQUIRED"/>
            <tx:method name="edit*" propagation="REQUIRED"/>
            <tx:method name="save*" propagation="REQUIRED"/>
            <tx:method name="add*" propagation="REQUIRED"/>
            <tx:method name="new*" propagation="REQUIRED"/>
            <tx:method name="modify*" propagation="REQUIRED"/>
            <tx:method name="remove*" propagation="REQUIRED"/>
            <tx:method name="delete*" propagation="REQUIRED"/>
            <tx:method name="change*" propagation="REQUIRED"/>
            <tx:method name="check*" propagation="REQUIRED"/>

            <tx:method name="get*" propagation="REQUIRED" read-only="true"/>
            <tx:method name="find*" propagation="REQUIRED" read-only="true"/>
            <tx:method name="load*" propagation="REQUIRED" read-only="true"/>
            <tx:method name="*" propagation="REQUIRED" read-only="true"/>
        </tx:attributes>
    </tx:advice>

    <!-- 6.配置事务切面 -->
    <aop:config>
        <aop:pointcut id="pointcut" expression="execution(* com.study.springcxf.service.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"/>
    </aop:config>

</beans>

3-3 在web.xml文件中配置cxf servlet。cxf用于提供webservice服务的servlet

<servlet>
    <servlet-name>CXFServlet</servlet-name>
    <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>CXFServlet</servlet-name>
    <url-pattern>/webservices/*</url-pattern>
</servlet-mapping>

beans-cxf.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:jaxws="http://cxf.apache.org/jaxws"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jaxrs="http://cxf.apache.org/jaxrs"
    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-4.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
        http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd">

    <import resource="classpath:META-INF/cxf/cxf.xml" />
    <import resource="classpath:META-INF/cxf/cxf-servlet.xml" />

    <!-- 
        使用注解扫描,可以替换如下 bean 配置
        另外, loggingInInterceptor bean 通过 @Bean注解生成,在类 MyBeanFactory.java 中实现
    -->
    <!-- <bean id="calculateService" class="com.study.springcxf.service.CalculateServiceImpl"></bean>
    <bean id="loggingInInterceptor" class="org.apache.cxf.interceptor.LoggingInInterceptor"></bean>
    <bean id="userCheckInterceptor" class="com.study.springcxf.interceptor.UserCheckInterceptor"></bean> -->

    <!-- 方式一:相当于使用JaxWsServerFactoryBean进行服务发布 -->
    <jaxws:server address="/calculateService" serviceClass="com.study.springcxf.service.CalculateService"
        serviceBean="#calculateService">
        <jaxws:inInterceptors>
            <ref bean="loggingInInterceptor"/>
            <ref bean="userCheckInterceptor"/>
        </jaxws:inInterceptors>
    </jaxws:server>
    <!-- 方式一(配置方式不同):相当于使用JaxWsServerFactoryBean进行服务发布 -->
    <!-- <jaxws:server serviceClass="com.study.springcxf.service.CalculateService"
        address="/service">
        <jaxws:serviceBean>
            <ref bean="calculateService"/>
        </jaxws:serviceBean>
    </jaxws:server> -->

    <!-- 方式二:相当于使用Endpoint.publish()进行服务发布 -->
    <!-- <jaxws:endpoint address="/service" implementor="com.study.springcxf.service.CalculateServiceImpl">
        <jaxws:inInterceptors>
            <ref bean="userCheckInterceptor"/>
        </jaxws:inInterceptors>
    </jaxws:endpoint> -->

    <jaxws:endpoint address="/userService" implementor="com.study.springcxf.service.UserServiceImpl">
        <jaxws:inInterceptors>
            <ref bean="userCheckInterceptor"/>
        </jaxws:inInterceptors>
    </jaxws:endpoint>

    <jaxrs:server address="/restful">
        <jaxrs:serviceBeans>
            <ref bean="customerService"/>
        </jaxrs:serviceBeans>
        <jaxrs:providers>
            <bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider"></bean>
        </jaxrs:providers>
    </jaxrs:server>
</beans>

第4节 Apache CXF拦截器的使用

  • 使用Apache CXF拦截器,我们首先得知道什么是Apache CXF拦截器。在Apache CXF中,拦截器有几种分类方式,系统拦截器、用户自定义拦截器;出拦截器、入拦截器等等。读者需要理解出入拦截器会更容易使用CXF的这个功能,怎么说呢。说明一下,无论相对于客户端还是服务器,拦截器都是在消息进入或者离开端点(端点表示网络中一台主机,可能是客户端,也可能是服务器)之前或者之后对消息进行我们需要的处理。打个比方,比如日志拦截器,在服务端可能存在一个入日志拦截器A,也可能存在一个出日志拦截器B,A或者B都可能是在消息处理之前或者之后或者某个时间点进行的。对于客户端同样如此。在此就不作深入讲解了,读者可以自行参考官网文档,下面简单把实现步骤说明一下
  • 首先需要一个实现了接口org.apache.cxf.interceptor.Interceptor的java类,这个类可以通过继承AbstractPhaseInterceptor类来完成。其中泛型T是一个org.apache.cxf.message.Message接口类型,我们自定义的类型中泛型简单指定为SoapMessage即可。拦截器中主要有两个选择性实现的方法handleFault和handleMessage,分别用于拦截不同方面,前者用于出错的异常拦截,后者是用于消息处理的。用户名密码的验证就是放在后面那个方法当中,代码如下
    @Override
    public void handleMessage(SoapMessage message) throws Fault {
        Header header = message.getHeader(new QName("user"));
        if (header!=null) {
            Element userElement = (Element) header.getObject();
            String username = userElement.getElementsByTagName("username").item(0).getTextContent();
            String password = userElement.getElementsByTagName("password").item(0).getTextContent();

            // 实际发送的请求 uri
            String uri = message.getDestination().getAddress().getAddress().getValue();
            try {
                boolean permit = permissionService.checkUserPermission(username, password, uri);
                if (permit) {
                    logger.log(Level.INFO, "验证权限通过...");
                    return ;
                }
            } catch (Fault e) {
                throw e;
            }
        } else {
            throw new Fault("请输入用户名密码!", logger);
        }
    }
  • 验证的逻辑以PermissionService接口形式封装在方法checkUserPermission中,代码如下
    @Override
    public boolean checkUserPermission(String username, String password, String accessedResource) {

        List<String> resourceUris = new ArrayList<String>();
        User user = userService.findUserByUsernameAndPassword(username, password);
        if (user==null) {
            throw new Fault("用户名密码不正确!", logger);
        }
        List<UserResource> userResources = userResourceService.findResourceByUserId(user.getId());
        if (userResources==null || userResources.size()<1) {
            throw new Fault("该用户没有访问任何资源的权限!", logger);
        }
        List<Integer> resourceIds = new ArrayList<Integer>();
        for (UserResource e : userResources) {
            resourceIds.add(e.getResourceId());
        }
        List<Resource> resources = resourceService.findResourceIn(resourceIds);
        if (resources==null || resources.size()<1) {
            throw new Fault("对应资源已被禁用或者移除!", logger);
        }
        for (Resource e : resources) {
            resourceUris.add(e.getResourceUri());
        }

        if (resourceUris.size()>0 && resourceUris.contains(accessedResource)) {
            return true;
        } else {
            throw new Fault("该用户没有权限访问对应资源,该用户能访问的资源路径如下:" + resourceUris, logger);
        }
    }
  • java类编写完成后在第3节的beans-cxf.xml文件中进行配置。比如
<jaxws:server address="/calculateService" serviceClass="com.study.springcxf.service.CalculateService"
        serviceBean="#calculateService">
    <jaxws:inInterceptors>
        <ref bean="loggingInInterceptor"/>
        <ref bean="userCheckInterceptor"/>
    </jaxws:inInterceptors>
</jaxws:server>

表示通过接口CalculateService在/calculateService提供服务,实现类的实例为calculateService,注意前面要加上#,或者用上面配置的方式二。两个ref元素表示日志拦截器和用户名密码检查拦截器,配置在jaxws:inInterceptors元素中。另外如果需要对异常问题进行处理,那么让拦截器类重写handleFault方法,并在配置文件中加上jaxws:inFaultInterceptors元素即可。最后,本实例还实现了一个restful webservice,在beans-cxf.xml文件的最后address为/restful部分

猜你喜欢

转载自blog.csdn.net/liuxing9345/article/details/77983755