之前都是用soap协议搭建,最近学了下restful,以便日后翻阅,小生才疏学浅,不足之处请多见谅。

1.maven配置

<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</groupId>
<artifactId>cxf-demo</artifactId>
<version>1.0</version>
<packaging>war</packaging>
<name />
<description />
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.7</java.version>
<spring.version>3.2.5.RELEASE</spring.version>
<cxf.version>2.7.10</cxf.version>
</properties>
<dependencies>
<!-- spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- cxf jaxrs -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-bundle-jaxrs</artifactId>
<version>${cxf.version}</version>
<exclusions>
<exclusion>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-server</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.4.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.6</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
</project>

2.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" xmlns:web="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>cxf-demo</display-name> <!-- Spring config-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:applicationContext*.xml</param-value>
</context-param> <!-- Spring listener -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Add on a servlet to handle web service request -->
<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>/webservice/*</url-pattern>
</servlet-mapping>
</web-app>

3.java代码:

  (1)建一个HelloWordService的接口

package com.webservice;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType; @Path("/hello")
public interface HelloWordService { @GET
@Path("/sayHello")
@Produces(MediaType.APPLICATION_JSON)
public String sayHello(@QueryParam("name")String name);
}

  (2)新建实现类HelloWordServiceImpl

package com.webservice;

public class HelloWordServiceImpl implements HelloWordService {

    @Override
public String sayHello(String name) {
return "Hello Word,"+name;
} }

4..applicationContext.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"
<!-- 添加jaxrs的命名,不然会报jaxrs未绑定的错误 -->
xmlns:jaxrs="http://cxf.apache.org/jaxrs"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.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" />
<import resource="classpath:META-INF/cxf/cxf-extension-xml.xml"/> <bean id="helloWordServiceImpl" class="com.webservice.HelloWordServiceImpl"></bean> <jaxrs:server id="helloWordService" address="/helloWordService">
<jaxrs:serviceBeans>
<ref bean="helloWordServiceImpl"/>
</jaxrs:serviceBeans>
</jaxrs:server>
</beans>

6.部署到tomcat,然后测试:

  (1)浏览器直接访问:

    接口说明(类似soap的wsdl):http://localhost:8080/cxf-demo/webservice/helloWordService/hello/sayHello?_wadl

    接口测试:http://localhost:8080/cxf-demo/webservice/helloWordService/hello/sayHello?name=paul

  (2)键httpclient

package com.rs.client;

import java.io.IOException;
import java.net.URISyntaxException; import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils; public class RsCLient { public static void main(String[] args) { String URL = "http://localhost:8080/cxf-demo/webservice/helloWordService/hello/sayHello";
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
//添加参数
URIBuilder builder = new URIBuilder(URL);
builder.setParameter("name", "lining");
HttpGet httpGet = new HttpGet(builder.build()); //httpget配置
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(5000) //设置连接超时时间
.setConnectionRequestTimeout(5000) // 设置请求超时时间
.setSocketTimeout(5000)
.setRedirectsEnabled(true)//默认允许自动重定向
.build();
httpGet.setConfig(requestConfig); HttpResponse httpResponse = httpClient.execute(httpGet);
System.out.println(EntityUtils.toString(httpResponse.getEntity()));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
if(httpClient != null){
httpClient.close(); //释放资源
}
} catch (IOException e) {
e.printStackTrace();
}
} } }

7.JAX-RS的注解说明

  (1)@Path,标注资源类或方法的相对路径

  (2)@GET,@PUT,@POST,@DELETE,标注方法是用的HTTP请求的类型

  (3)@Produces,标注返回的MIME媒体类型,( 注解标注,这个注解可以包含一组字符串,默认值是*/*,它指定REST 服务的响应结果的MIME 类型,例如:application/xml、application/json、image/jpeg 等),你也可以同时返回多种类型,但具体生成结果时使用哪种格式取决于ContentType。CXF 默认返回的是JSON 字符串。

  (4)@PathParam,@QueryParam,@HeaderParam,@CookieParam,@MatrixParam,@FormParam,分别标注方法的参数来自于HTTP请求的不同位置,例如@PathParam来自于URL的路径,@QueryParam来自于URL的查询参数,@HeaderParam来自于HTTP请求的头信息,@CookieParam来自于HTTP请求的Cookie

cxf+spring+restful简单接口搭建的更多相关文章

  1. cxf+spring+soap简单接口开发

    最近学了cxf框架开发webservice,简单搭了个接口,方便后续翻阅,本人才疏学浅,若有不足,请多多谅解! 一.服务端: 1.所用到的jar包: maven的pom.xml配置: <proj ...

  2. cxf spring restful 问题解决(jar包冲突)

    SEVERE: Context initialization failedorg.springframework.beans.factory.BeanCreationException: Error ...

  3. 采用CXF+spring+restful创建一个web接口项目

    这篇文章是http://blog.csdn.net/zxnlmj/article/details/28880303下面,加入的基础上的restful特征 1.参加restful必jar包裹 jsr31 ...

  4. Spring Boot简单环境搭建

    #### 一.创建一个简单的Maven项目 使用`Maven`,通过导入`Spring Boot`的`starter`模块,可以将许多程序依赖的包自动导入到工程中.使用`Maven`的`parent ...

  5. CXF+Spring+JAXB+Json构建Restful服务

    话不多说,先看详细的样例: 文件文件夹结构: web.xml <?xml version="1.0" encoding="UTF-8"? > < ...

  6. SpringBoot2.0基础案例(01):环境搭建和RestFul风格接口

    一.SpringBoot 框架的特点 1.SpringBoot2.0 特点 1)SpringBoot继承了Spring优秀的基因,上手难度小 2)简化配置,提供各种默认配置来简化项目配置 3)内嵌式容 ...

  7. CXF+Spring+Hibernate实现RESTful webservice服务端实例

    1.RESTful API接口定义 /* * Copyright 2016-2017 WitPool.org All Rights Reserved. * * You may not use this ...

  8. Spring Boot入门系列(二十)快速打造Restful API 接口

    spring boot入门系列文章已经写到第二十篇,前面我们讲了spring boot的基础入门的内容,也介绍了spring boot 整合mybatis,整合redis.整合Thymeleaf 模板 ...

  9. Spring Boot入门系列(二十一)如何优雅的设计 Restful API 接口版本号,实现 API 版本控制!

    前面介绍了Spring Boot 如何快速实现Restful api 接口,并以人员信息为例,设计了一套操作人员信息的接口.不清楚的可以看之前的文章:https://www.cnblogs.com/z ...

随机推荐

  1. python全局变量

    定义函数里面的叫局部变量,出了函数外面就不能用了 局部变量函数被调用时,他的变量才生效 局部变量定义在内存里面,用完就会被释放,全局变量不会释放 当有相同名的局部变量和全局变量,函数会先找自己的变量, ...

  2. 【深入理解Java集合框架】红黑树讲解(上)

    来源:史上最清晰的红黑树讲解(上) - CarpenterLee 作者:CarpenterLee(转载已获得作者许可,如需转载请与原作者联系) 文中所有图片点击之后均可查看大图! 史上最清晰的红黑树讲 ...

  3. Convert BST to Greater Tree

    Given a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original B ...

  4. python笔记16-函数

    函数说白了,就是把一组代码合到一起,可以实现某种功能,需要再用到这个功能的话,直接调用这个函数就行了 1.定义函数def def my_open():#函数名,def定义函数,my_open给这个函数 ...

  5. 使用css时的一些技巧及注意事项

    <!-- TITLE: 使用css时的一些技巧及注意事项 --> # CSS推荐书写顺序: 1. 位置属性(position, top, right, z-index, display, ...

  6. 【leetcode】414. Third Maximum Number

    problem 414. Third Maximum Number solution 思路:用三个变量first, second, third来分别保存第一大.第二大和第三大的数,然后遍历数组. cl ...

  7. php环境和使用方法

    下载好所需要的软件 (含phpmywind  phpstudy  navicat for my sql ) 如果Navicat 的试用期过期,请使用通杀navicat 的通杀Navica11_2-XX ...

  8. grpc源码分析之域名解析

    环境: win7_x64,VS2015.grpc_1.3.1 场景: 在客户端中使用grpc连接服务器,在多次输入非法的地址后,再次输入正确的地址连出现连接超时的现象.侯捷先生说过“源码面前,了无秘密 ...

  9. 使用outflux 导入influxdb 的数据到timescaledb

    influxdb 以及timescaledb 都是不错的时序数据库,timescaledb 团队提供了直接从influxdb 导入 环境准备 docker-compose 文件 version: &q ...

  10. Session、Cookie、Cache、Token分别是什么及区别

    一.Session 1 )Session 解释 Session 是单用户的会话状态.当用户访问网站时,产生一个 sessionid.并存在于 cookies中.每次向服务器请求时,发送这个 cooki ...