使用cxf,spring,mybatis框架完成restful风格的webservice服务

使用cxf,spring,mybatis框架完成restful风格的webservice服务:

  • 使用maven管理项目的jar包,pom文件下载相关的jar

代码块

pom.xml

代码块语法遵循标准markdown代码,例如:

<project xmlns="http://maven.apache.org/POM/4.0.0" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.bst.basisApi</groupId>
  <artifactId>basisApi</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <name>basisApi Maven Webapp</name>
  <url>http://maven.apache.org</url>

  <properties>  
        <!-- spring版本号 -->  
        <spring.version>4.1.2.RELEASE</spring.version>  
        <!-- mybatis版本号 -->  
        <mybatis.version>3.4.1</mybatis.version>  
        <!-- log4j日志文件管理包版本 -->  
        <slf4j.version>1.7.7</slf4j.version>  
        <log4j.version>2.7</log4j.version> 
        <cxf.version>3.0.4</cxf.version>

  </properties> 

  <dependencies>

    <!-- spring core jar -->
    <dependency>  
        <groupId>org.springframework</groupId>  
        <artifactId>spring-core</artifactId>  
        <version>${spring.version}</version> 
    </dependency>  

    <dependency>  
        <groupId>org.springframework</groupId>  
        <artifactId>spring-web</artifactId>  
        <version>${spring.version}</version>  
    </dependency>  
    <dependency>  
        <groupId>org.springframework</groupId>  
        <artifactId>spring-oxm</artifactId>  
        <version>${spring.version}</version>  
    </dependency>  
    <dependency>  
        <groupId>org.springframework</groupId>  
        <artifactId>spring-tx</artifactId>  
        <version>${spring.version}</version>  
    </dependency>  

    <dependency>  
        <groupId>org.springframework</groupId>  
        <artifactId>spring-jdbc</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-aop</artifactId>  
        <version>${spring.version}</version>  
    </dependency>  

    <dependency>  
        <groupId>org.springframework</groupId>  
        <artifactId>spring-context-support</artifactId>  
        <version>${spring.version}</version>  
    </dependency>  

    <dependency>  
        <groupId>org.springframework</groupId>  
        <artifactId>spring-test</artifactId>  
        <version>${spring.version}</version>  
    </dependency>  

    <!-- mybatis/spring包 -->  
    <dependency>  
        <groupId>org.mybatis</groupId>  
        <artifactId>mybatis-spring</artifactId>  
        <version>1.3.1</version>  
    </dependency>  
    <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
    <!-- <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.40</version>
    </dependency> -->

    <!-- microsoft sql server -->
    <dependency>
        <groupId>com.microsoft.sqlserver</groupId>
        <artifactId>sqljdbc4</artifactId>
        <version>4.0</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core -->
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
        <version>${log4j.version}</version>
    </dependency>

    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>${mybatis.version}</version>
    </dependency>
    <!-- junit test jar -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.10</version>
    </dependency>


    <!-- 格式化对象,方便输出日志 -->  
    <dependency>  
        <groupId>com.alibaba</groupId>  
        <artifactId>fastjson</artifactId>  
        <version>1.1.41</version>  
    </dependency>  

    <!-- log console jar -->
    <dependency>  
        <groupId>org.slf4j</groupId>  
        <artifactId>slf4j-api</artifactId>  
        <version>${slf4j.version}</version>  
    </dependency>  

    <dependency>  
        <groupId>org.slf4j</groupId>  
        <artifactId>slf4j-log4j12</artifactId>  
        <version>${slf4j.version}</version>  
    </dependency>

    <!-- 导入dbcp的jar包,用来在applicationContext.xml中配置数据库 -->  
    <dependency>  
        <groupId>commons-dbcp</groupId>  
        <artifactId>commons-dbcp</artifactId>  
        <version>1.2.2</version>  
    </dependency>

    <!-- cxf core -->
    <!-- https://mvnrepository.com/artifact/org.apache.cxf/cxf-core -->
    <dependency>
        <groupId>org.apache.cxf</groupId>
        <artifactId>cxf-core</artifactId>
        <version>${cxf.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.cxf</groupId>
      <artifactId>cxf-rt-rs-service-description</artifactId>
      <version>${cxf.version}</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.cxf/cxf-rt-bindings-soap -->
    <dependency>
        <groupId>org.apache.cxf</groupId>
        <artifactId>cxf-rt-bindings-soap</artifactId>
        <version>${cxf.version}</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.cxf/cxf-rt-bindings-xml -->
    <dependency>
        <groupId>org.apache.cxf</groupId>
        <artifactId>cxf-rt-bindings-xml</artifactId>
        <version>${cxf.version}</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.apache.cxf/cxf-rt-frontend-simple -->
    <dependency>
        <groupId>org.apache.cxf</groupId>
        <artifactId>cxf-rt-frontend-simple</artifactId>
        <version>${cxf.version}</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.apache.cxf/cxf-rt-ws-addr -->
    <dependency>
        <groupId>org.apache.cxf</groupId>
        <artifactId>cxf-rt-ws-addr</artifactId>
        <version>${cxf.version}</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/javax.ws.rs/javax.ws.rs-api -->
    <dependency>
        <groupId>javax.ws.rs</groupId>
        <artifactId>javax.ws.rs-api</artifactId>
        <version>2.0</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.apache.cxf/cxf-rt-transports-http -->
    <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-frontend-jaxrs</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.codehaus.jackson</groupId>
        <artifactId>jackson-jaxrs</artifactId>
        <version>1.9.12</version>
    </dependency>

  </dependencies>


  <build>
    <finalName>basisApi</finalName>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <version>2.6</version>
            <configuration>  
                <skipTests>true</skipTests> 
                <includeEmptyDirectories>true</includeEmptyDirectories>  
            </configuration>  
        </plugin>
    </plugins>
   </build>
</project>

整个spring与mybatis

jdbc.properties 数据库信息配置文件

mysql_driver=com.mysql.jdbc.Driver
mysql_url=jdbc:mysql://localhost:3306/zyqg
mysql_username=root
mysql_password=root
#定义初始连接数
mysql_initialSize=0
#定义最大连接数
mysql_maxActive=20
#定义最大空闲
mysql_maxIdle=20
#定义最小空闲
mysql_minIdle=1
#定义最长等待时间
mysql_maxWait=60000

#定义接口请求的用户和密码(做访问验证)
webservice.webserviceId=test
webservice.webservicePasswd=MTIzIUAjZnNh

日志文件

#定义LOG输出级别
log4j.rootLogger=INFO,Console,File
#定义日志输出目的地为控制台
log4j.logger.java.sql.PreparedStatement=INFO
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.Target=System.out
#可以灵活地指定日志输出格式,下面一行是指定具体的格式
log4j.appender.Console.layout = org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n

#文件大小到达指定尺寸的时候产生一个新的文件
log4j.appender.File = org.apache.log4j.RollingFileAppender
#指定输出目录
log4j.appender.File.File = logs/ssm.log
#定义文件最大大小
log4j.appender.File.MaxFileSize = 10MB
# 输出所以日志,如果换成DEBUG表示输出DEBUG以上级别日志
log4j.appender.File.Threshold = ALL
log4j.appender.File.layout = org.apache.log4j.PatternLayout
log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n

spring与mybatis整合配置

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

    <!-- 配置扫描的路径-->  
    <context:component-scan base-package="com.bst.basis"/>
    <!-- 引入数据库配置文件 -->  
    <bean id="propertyConfigurer"  
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
        <property name="location" value="classpath:jdbc.properties" />  
    </bean>  

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"  
        destroy-method="close">  
        <property name="driverClassName" value="${ms_driver}" />  
        <property name="url" value="${ms_url}" />  
        <property name="username" value="${ms_username}" />  
        <property name="password" value="${ms_password}" />  
        <!-- 初始化连接大小 -->  
        <property name="initialSize" value="${ms_initialSize}"></property>  
        <!-- 连接池最大数量 -->  
        <property name="maxActive" value="${ms_maxActive}"></property>  
        <!-- 连接池最大空闲 -->  
        <property name="maxIdle" value="${ms_maxIdle}"></property>  
        <!-- 连接池最小空闲 -->  
        <property name="minIdle" value="${ms_minIdle}"></property>  
        <!-- 获取连接最大等待时间 -->  
        <property name="maxWait" value="${ms_maxWait}"></property>  
    </bean>  

    <!-- spring和MyBatis整合,不需要mybatis的配置映射文件 -->  
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
        <property name="dataSource" ref="dataSource" />  
        <!-- 自动扫描mapping.xml文件 -->  
        <property name="mapperLocations" value="classpath:com/bst/basis/mapping/*/*.xml"></property>  
    </bean>  

    <!-- DAO接口所在包名,Spring会自动查找其下的类 -->  
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
        <property name="basePackage" value="com.bst.basis.dao" />  
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>  
    </bean>  

    <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->  
    <bean id="transactionManager"  
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
        <property name="dataSource" ref="dataSource" />  
    </bean> 

    <bean id="sysparameter" class="com.bst.basis.common.util.SysParameter">
        <property name="webserviceId" value="${webservice.webserviceId}" />
        <property name="webservicePasswd" value="${webservice.webservicePasswd}" />
    </bean> 

</beans>  

web.xml

<?xml version="1.0" encoding="UTF-8"?>  
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xmlns="http://java.sun.com/xml/ns/javaee"  
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"  
    version="3.0">  
    <display-name>basisApi</display-name>  
    <!-- Spring和mybatis的配置文件 -->  
    <context-param>  
        <param-name>contextConfigLocation</param-name>  
        <param-value>classpath:spring-*.xml</param-value>

    </context-param>

    <!-- 编码过滤器 -->  
    <filter>  
        <filter-name>encodingFilter</filter-name>  
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
        <async-supported>true</async-supported>  
        <init-param>  
            <param-name>encoding</param-name>  
            <param-value>UTF-8</param-value>  
        </init-param>  
    </filter>  
    <filter-mapping>  
        <filter-name>encodingFilter</filter-name>  
        <url-pattern>/*</url-pattern>  
    </filter-mapping> 

    <!-- Spring监听器 -->  
    <listener>  
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
    </listener> 

    <!-- 防止Spring内存溢出监听器 -->  
    <listener>  
        <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>  
    </listener>  

    <!-- rest -->
    <servlet>
        <servlet-name>CXFServlet</servlet-name>
        <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
        <load-on-startup>1</load-on-startup>

        <!-- 配置需要隐藏的restful列表 -->
        <!-- <init-param>
            <param-name>service-list-path</param-name>
            <param-value>/cxf/serviceList</param-value>
        </init-param> -->

        <!-- <init-param>
            <param-name>hide-list-path</param-name>
            <param-value>true</param-value>
        </init-param> -->


    </servlet>


    <servlet-mapping>
        <servlet-name>CXFServlet</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>


    <welcome-file-list>  
        <welcome-file>/index.jsp</welcome-file>  
    </welcome-file-list>  

</web-app>  

好了至此我们就已经通过maven搭建好了spring+myBatis+cxf的整个框架了,放入tomcat测试一下是否可以正常启动。
这里写图片描述
可以正常启动,说明整合没有问题;
接下来编写代码
首先编写bean(伪代码)

package com.bst.basis.dto;

/**
 * 驾驶员信息
 *
 * @author henry
 * @date 2017年3月1日 上午11:27:57
 * @version 1.0.0
 *
 */
public class QueryDrvierDto {

    private static final long serialVersionUID = -7726421850126740662L;

    private String stationCode;
    private String code;
    private String name;
    private String gender;
    private String telephone;
    private String idCard;
    private String drivingLicence;
    private String drivingCarType;
    private String qualificationNo;
    private String companyCode;
    private String companyName;
    private String status;
    private String createdAt;
    private String updatedAt;
    private String remark;

    public String getStationCode() {
        return stationCode;
    }
    public void setStationCode(String stationCode) {
        this.stationCode = stationCode;
    }
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getGender() {
        return gender;
    }
    public void setGender(String gender) {
        this.gender = gender;
    }
    public String getTelephone() {
        return telephone;
    }
    public void setTelephone(String telephone) {
        this.telephone = telephone;
    }
    public String getIdCard() {
        return idCard;
    }
    public void setIdCard(String idCard) {
        this.idCard = idCard;
    }
    public String getDrivingLicence() {
        return drivingLicence;
    }
    public void setDrivingLicence(String drivingLicence) {
        this.drivingLicence = drivingLicence;
    }
    public String getDrivingCarType() {
        return drivingCarType;
    }
    public void setDrivingCarType(String drivingCarType) {
        this.drivingCarType = drivingCarType;
    }
    public String getQualificationNo() {
        return qualificationNo;
    }
    public void setQualificationNo(String qualificationNo) {
        this.qualificationNo = qualificationNo;
    }
    public String getCompanyCode() {
        return companyCode;
    }
    public void setCompanyCode(String companyCode) {
        this.companyCode = companyCode;
    }
    public String getCompanyName() {
        return companyName;
    }
    public void setCompanyName(String companyName) {
        this.companyName = companyName;
    }
    public String getStatus() {
        return status;
    }
    public void setStatus(String status) {
        this.status = status;
    }
    public String getCreatedAt() {
        return createdAt;
    }
    public void setCreatedAt(String createdAt) {
        this.createdAt = createdAt;
    }
    public String getUpdatedAt() {
        return updatedAt;
    }
    public void setUpdatedAt(String updatedAt) {
        this.updatedAt = updatedAt;
    }
    public String getRemark() {
        return remark;
    }
    public void setRemark(String remark) {
        this.remark = remark;
    }


}

dao交互,这里的方法名(selectDriver())需要与mybatis的mapper.xml中的必须完成一致,否则mybatis解析xml时将找不到

package com.bst.basis.dao;

import java.util.List;
import java.util.Map;

import com.bst.basis.dto.*;

/**
 * 
 * @author henry
 * @date 2017年2月28日 下午2:13:20
 * @version 1.0.0
 *
 */
public interface IStationBasisDao {


    /**
     * 驾驶员信息
     * @return
     */
    public List<QueryDrvierDto> selectDriver();

}

接口信息

package com.bst.basis.dao;

import java.util.List;
import java.util.Map;

import com.bst.basis.dto.*;

/**
 * 
 * @author henry
 * @date 2017年2月28日 下午2:13:20
 * @version 1.0.0
 *
 */
public interface IStationBasisDao {

    /**
     * 驾驶员信息
     * @return
     */
    public List<QueryDrvierDto> selectDriver();


}
<?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="com.bst.basis.dao.IStationBasisDao">

    <!-- 驾驶员 -->
    <select id="selectDriver"  statementType="CALLABLE" 
        resultType="com.bst.basis.dto.QueryDrvierDto">
        select *from test_table
    </select>
</mapper>
**定义需要暴露的接口*方法***
@GET 表示请求的方式 
@Path("/driver") 定义当前暴露的服务类请求根路径
@Produces({MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON}) 返回的格式,支持两种返回格式,但只在返回为对象或List时才支持xml格式,如果返回类型为String则只能支持json
package com.bst.basis.restful;

import java.sql.Date;

import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;


public interface IBasisService {

    /**
     * 驾驶员信息
     * @return
     */
    @GET
    @Path("/driver") 
    @Produces({MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON})
    public String queryDriver();

}

暴露接口业务实现

package com.bst.basis.restful;

import java.sql.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.ws.rs.PathParam;
import javax.ws.rs.ext.Provider;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSON;
import com.bst.basis.common.constant.ErrorCodeConstant;
import com.bst.basis.common.util.Result;
import com.bst.basis.dto.QueryDrvierDto;




/**
 * 
 * 小件对接,接口实现
 * @author henry
 * @date 2017年2月28日 下午2:25:48
 * @version 1.0.0
 *
 */
@Component("basisService")
@Provider  
public class BasisService implements IBasisService{

    protected  Logger log = Logger.getLogger(getClass());

    @Resource
    private IStationBasisDao stationBasisDao;//通过注解注入dao

    public String queryDriver() {
        log.info("queryDriver");
        List<QueryDrvierDto> list = null;
        String result = "";
        try {
            list = stationBasisDao.selectDriver();
            result = String.format(Result.RESULT_SUCCEED, JSON.toJSON(list));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("queryDriver :"+e.getMessage());
            result = String.format(Result.RESULT_FAIL, "001");
        }
        return result;
    }
}



package com.bst.basis.common.util;


/**
 * 统一定义所有服务接口返回格式
 *
 * @author henry
 * @date 2017年2月28日 下午8:19:45
 * @version 1.0.0
 *
 */
public class Result {

    /**成功:{\"success\":true,\"error_code\":\"\",\"data\":%s}**/
    public static final String RESULT_SUCCEED ="{\"success\":true,\"error_code\":\"\",\"data\":%s}";

    /**失败:{\"success\":true,\"error_code\":\"\",\"data\":%s}**/
    public static final String RESULT_FAIL =  "{\"success\":false,\"error_code\":\"%s\",\"data\":[]}";


    /**失败,带错误信息:{\"success\":true,\"error_code\":\"\",\"data\":%s}**/
    public static final String RESULT_FAIL_MS =  "{\"success\":false,\"error_code\":\"%s\",\"data\":[{message:\"%s\"}]}";

}

参数读取类

package com.bst.basis.common.util;


public class SysParameter {
    public static final int CODE_OK=0;
    public static final int CODE_USERNAMEPWD_ERROR=10;
    public static final int CODE_USERTOKEN_ERROR=11;
    public static final int CODE_FORMAT_ERROR=12;

    private static String stationId;
    private static String stationName;

    private static String webserviceId;
    private static String webservicePasswd;

    public static String getStationId() {
        return stationId;
    }
    public static void setStationId(String stationId) {
        SysParameter.stationId = stationId;
    }
    public static String getStationName() {
        return stationName;
    }
    public static void setStationName(String stationName) {
        SysParameter.stationName = stationName;
    }

    public static String getWebserviceId() {
        return webserviceId;
    }
    public static void setWebserviceId(String webserviceId) {
        SysParameter.webserviceId = webserviceId;
    }
    public static String getWebservicePasswd() {
        return webservicePasswd;
    }
    public static void setWebservicePasswd(String webservicePasswd) {
        SysParameter.webservicePasswd = webservicePasswd;
    }


}

权限拦截(最简单实现)

package com.bst.basis.restful.interceptor;


import java.util.List;
import java.util.Map;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.message.Message;
import org.apache.cxf.phase.Phase;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.log4j.Logger;

import com.bst.basis.common.util.SysParameter;


/**
 * 接口访问认证拦截器
 * @author henry
 * @date 2017年2月28日 下午8:21:44
 * @version 1.0.0
 *
 */
public class AuthInterceptor extends AbstractPhaseInterceptor<Message>{
    private final Logger logger = Logger.getLogger(getClass());  

    public AuthInterceptor() {
        super(Phase.PRE_INVOKE);
    }

    public void handleMessage(Message message) throws Fault {
        logger.info("AuthInterceptor Message=="+message);
        Map<String,List<String>> headers = (Map<String, List<String>>) message.get(Message.PROTOCOL_HEADERS);
        List<String> account = headers.get("AgentAccount");
        List<String> key = headers.get("AgentKey");
        if(account == null || key == null){
            throw new Fault(new IllegalArgumentException("未填写认证信息"));
        }else if(!account.get(0).equals(SysParameter.getWebserviceId()) || !key.get(0).equals(SysParameter.getWebservicePasswd())){
            throw new Fault(new IllegalArgumentException("认证信息填写错误,请联系接口服务商!"));
        }
    }

}

restful服务暴露配置

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

    <import resource="classpath:META-INF/cxf/cxf.xml" />
    <import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
    <!-- <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" /> -->
    <!-- 配置扫描的路径-->  
    <context:component-scan base-package="com.bst.basis"/>


    <bean id="inMessageInterceptor" class="org.apache.cxf.interceptor.LoggingInInterceptor" />  
    <bean id="outMessageInterceptor" class="org.apache.cxf.interceptor.LoggingOutInterceptor"/>
    <!-- 权限拦截器 -->
    <bean id="authInterceptor" class="com.bst.basis.restful.interceptor.AuthInterceptor"/>

    <!-- 接口发布 -->
    <jaxrs:server id="brServices" address="/services/carStation">
          <jaxrs:serviceBeans>
            <ref bean="basisService" />  
          </jaxrs:serviceBeans>
          <jaxrs:inInterceptors>  
            <ref bean="inMessageInterceptor"/>  
            <ref bean="authInterceptor"/>  
           </jaxrs:inInterceptors>  
           <!-- 输出日志拦截器 -->  
           <jaxrs:outInterceptors>  
              <ref bean="outMessageInterceptor"/>  
           </jaxrs:outInterceptors>  
          <jaxrs:providers>  
            <bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider" />  
          </jaxrs:providers>  

          <jaxrs:extensionMappings>
            <entry key="json" value="application/json"/>
            <entry key="xml" value="application/xml"/>
          </jaxrs:extensionMappings>
          <jaxrs:languageMappings>
             <entry key="en" value="en-gb"/>  
          </jaxrs:languageMappings>
    </jaxrs:server> 
 </beans>

到此我们就已完成所有编码工作,下面部署到tomcat进行测试;

启动如图

通过google浏览器插件rest插件测试
1.
设置头信息

查询结果

简单的demo,若有错误多谢指出。

评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值