cxf+spring+restful简单接口搭建

之前都是用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

原文地址:https://www.cnblogs.com/ctsx/p/9261616.html