maven+cxf编写RESTful风格webservice

来源:互联网 发布:淘宝店铺层级怎么算 编辑:程序博客网 时间:2024/05/22 06:43



pom.xml添加maven依赖

   <dependency>      <groupId>org.apache.servicemix.bundles</groupId>      <artifactId>org.apache.servicemix.bundles.json-lib</artifactId>      <version>2.4_1</version>    </dependency>    <dependency>      <groupId>javax.ws.rs</groupId>      <artifactId>jsr311-api</artifactId>      <version>1.1.1</version>    </dependency>    <dependency>      <groupId>org.apache.cxf</groupId>      <artifactId>apache-cxf</artifactId>      <version>3.1.7</version>    </dependency>    <dependency>      <groupId>javax.servlet</groupId>      <artifactId>javax.servlet-api</artifactId>      <version>4.0.0-b01</version>    </dependency>    <dependency>      <groupId>org.codehaus.jackson</groupId>      <artifactId>jackson-jaxrs</artifactId>      <version>1.2.1</version>    </dependency>    <dependency>      <groupId>org.springframework</groupId>      <artifactId>spring-core</artifactId>      <version>4.3.2.RELEASE</version>    </dependency>    <dependency>      <groupId>org.springframework</groupId>      <artifactId>spring-web</artifactId>      <version>4.3.2.RELEASE</version>    </dependency>    <dependency>      <groupId>junit</groupId>      <artifactId>junit</artifactId>      <version>4.12</version>    </dependency>



一、编写服务端接口


1、编写服务接口(下面将会说到客户端调用服务接口的两种方式,服务接口中的注解是为第二种调用方式服务的,如果采用第一种调用方式,服务接口可以是一个空接口或者不要,但我们编写面向接口的程序)

import net.sf.json.JSONObject;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.ws.rs.*;import javax.ws.rs.core.Context;import javax.ws.rs.core.MediaType;import javax.ws.rs.core.Request;import javax.ws.rs.core.UriInfo;import java.io.IOException;@Path(value = "/sample")public interface RESTSample   {    @GET    @Produces(MediaType.TEXT_PLAIN)    public String doGet();    @GET    @Produces(MediaType.TEXT_PLAIN)    @Path("/request/{param}")    public String doRequest(@PathParam("param") String param,                            @Context HttpServletRequest servletRequest, @Context HttpServletResponse servletResponse) ;    @GET    @Path("/bean/{id}")    @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})    public User getBean(@PathParam("id") int id) ;    @GET    @Path("/message/{id}")    @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})    public String getMessage(@PathParam("id") int id);    /*        @Consumes:声明该方法使用 HTML FORM。        @FormParam:注入该方法的 HTML 属性确定的表单输入。        @Response.created(uri).build(): 构建新的 URI 用于新创建的联系人(/contacts/{id})并设置响应代码(201/created)。        您可以使用 http://localhost:8080/Jersey/rest/contacts/<id> 访问新联系人     */    @POST    @Path("/postData")    @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})    public User postData(User user) throws IOException ;    @PUT    @Path("/putData/{id}")    @Produces({MediaType.APPLICATION_XML})    public User putData(@PathParam("id") int id, User user);    @DELETE    @Path("/removeData/{id}")    public void deleteData(@PathParam("id") int id) ;}



2、编写服务接口实现类

import javax.servlet.http.HttpServletRequest;import net.sf.json.JSONObject;import javax.servlet.http.HttpServletResponse;import javax.ws.rs.*;import javax.ws.rs.core.Context;import javax.ws.rs.core.MediaType;import javax.ws.rs.core.Request;import javax.ws.rs.core.UriInfo;import java.io.IOException;/*     注释(Annotation):在 javax.ws.rs.* 中定义,是 JAX-RS (JSR 311) 规范的一部分。    @Path:定义资源基 URI。由上下文根和主机名组成,资源标识符类似于 http://localhost:8080/RESTful/rest/hello。    @GET:这意味着以下方法可以响应 HTTP GET 方法。    @Produces:以纯文本方式定义响应内容 MIME 类型。    @Context: 使用该注释注入上下文对象,比如 Request、Response、UriInfo、ServletContext 等。    @Path("{contact}"):这是 @Path 注释,与根路径 “/contacts” 结合形成子资源的 URI。    @PathParam("contact"):该注释将参数注入方法参数的路径,在本例中就是联系人 id。其他可用的注释有 @FormParam、@QueryParam 等。    @Produces:响应支持多个 MIME 类型。在本例和上一个示例中,APPLICATION/XML 将是默认的 MIME 类型。 */@Path(value = "/sample")public class RESTSampleSource implements RESTSample {    @Context    private UriInfo uriInfo;    @Context    private Request request;    @GET    @Produces(MediaType.TEXT_PLAIN)    public String doGet() {        return "this is get rest request";    }    @GET    @Produces(MediaType.TEXT_PLAIN)    @Path("/request/{param}")    public String doRequest(@PathParam("param") String param,                            @Context HttpServletRequest servletRequest, @Context HttpServletResponse servletResponse) {        System.out.println(servletRequest);        System.out.println(servletResponse);        System.out.println(servletRequest.getParameter("param"));        System.out.println(servletRequest.getContentType());        System.out.println(servletResponse.getCharacterEncoding());        System.out.println(servletResponse.getContentType());        return "success";    }    @GET    @Path("/bean/{id}")    @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })    public User getBean(@PathParam("id") int id) {        System.out.println("####getBean#####");        System.out.println("id:" + id);        System.out.println("Method:" + request.getMethod());        System.out.println("uri:" + uriInfo.getPath());        System.out.println(uriInfo.getPathParameters());        User user = new User();        user.setId(id);        user.setName("JojO");        return user;    }    @GET    @Path("/message/{id}")    @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })    public String getMessage(@PathParam("id") int id) {        JSONObject jsonObject=new JSONObject();        User user = new User();        user.setId(id);        user.setName("JojO");        return  jsonObject.fromObject(user).toString();    }    /*        @Consumes:声明该方法使用 HTML FORM。        @FormParam:注入该方法的 HTML 属性确定的表单输入。        @Response.created(uri).build(): 构建新的 URI 用于新创建的联系人(/contacts/{id})并设置响应代码(201/created)。        您可以使用 http://localhost:8080/Jersey/rest/contacts/<id> 访问新联系人     */    @POST    @Path("/postData")    @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })    public User postData(User user) throws IOException {        System.out.println(user);        user.setName("jojo##12321321");        return user;    }    @PUT    @Path("/putData/{id}")    @Produces({ MediaType.APPLICATION_XML })    public User putData(@PathParam("id") int id, User user) {        System.out.println("#####putData#####");        System.out.println(user);        user.setId(id);        user.setAddress("hoojo#gz");        user.setEmail("hoojo_@126.com");        user.setName("hoojo");        System.out.println(user);        return user;    }    @DELETE    @Path("/removeData/{id}")    public void deleteData(@PathParam("id") int id) {        System.out.println("#######deleteData#######" + id);    }}


User实体类

package jaxRs;import javax.xml.bind.annotation.XmlRootElement;import java.io.Serializable;/** * Created by oracle on 2016/8/1. */@XmlRootElement(name = "UserInfo")public class User implements Serializable {    private static final long serialVersionUID = 677484458789332877L;    private int id;    private String name;    private String email;    private String address;    //getter/setter    public void setId(int id) {        this.id = id;    }    public void setName(String name) {        this.name = name;    }    public void setEmail(String email) {        this.email = email;    }    public void setAddress(String address) {        this.address = address;    }    public static long getSerialVersionUID() {        return serialVersionUID;    }    public int getId() {        return id;    }    public String getName() {        return name;    }    public String getEmail() {        return email;    }    public String getAddress() {        return address;    }    @Override    public String toString() {        return this.id + "#" + this.name + "#" + this.email + "#" + this.address;    }}


3、配置文件

applicationContext-cxf-server.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: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-3.0.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsdhttp://cxf.apache.org/jaxrshttp://cxf.apache.org/schemas/jaxrs.xsd"><context:annotation-config/><jaxrs:server address="/RESTWebService" id="RESTWebService"><jaxrs:serviceBeans><bean class="jaxRs.RESTSampleSource"></bean></jaxrs:serviceBeans><jaxrs:providers><bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider" /><bean class="org.apache.cxf.jaxrs.provider.JAXBElementProvider" /></jaxrs:providers></jaxrs:server></beans>


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" xmlns:context="http://www.springframework.org/schema/context"xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"xmlns:oscache="http://www.springmodules.org/schema/oscache"xmlns:p="http://www.springframework.org/schema/p"     xmlns:cache="http://www.springframework.org/schema/cache" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.1.xsd"><context:annotation-config/><import resource="applicationContext-cxf-server.xml"/><context:component-scan base-package="jaxRs" /><bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/><bean id="webClient" class="org.apache.cxf.jaxrs.client.WebClient" factory-method="create"><constructor-arg type="java.lang.String" value="http://localhost:8080/webservice/RESTWebService/" /></bean><bean id="rESTSample" class="org.apache.cxf.jaxrs.client.JAXRSClientFactory" factory-method="create"><constructor-arg type="java.lang.String" value="http://localhost:8080/webservice/RESTWebService/" /><constructor-arg type="java.lang.Class" value="jaxRs.RESTSample" /></bean></beans>



4、编写测试类

import org.apache.cxf.jaxrs.client.WebClient;import org.junit.Before;import org.junit.Test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import javax.annotation.Resource;/** * Created by oracle on 2016/8/1. */public class Client {@Autowired    private RESTSample rESTSample;    private WebClient webClient;    @Before    public void initContext(){        ApplicationContext ac=new ClassPathXmlApplicationContext("classpath:applicationContext.xml");        webClient=(WebClient)ac.getBean("webClient");        rESTSample=(RESTSample)ac.getBean("rESTSample");    }    @Test    public void testWebService(){      //第一种调用接口方式        String user=  webClient.path("sample/message/6").accept("MediaType.APPLICATION_JSON").get(String.class);        System.out.println(user);    }    @Test    public void testWebService2(){     //第二种调用接口方式        String user=  rESTSample.getMessage(6);        System.out.println(user);    }}






0 0
原创粉丝点击