Apache cxf rs

1、CXF介绍

CXF 框架是一种基于 Servlet 技术的 SOA 应用开发框架,要正常运行基于 CXF 应用框架开发的企业应用,除了 CXF 框架本身之外,还需要 JDK 和 Servlet 容器的支持。

Apache CXF 是一个开源的 Services 框架,CXF 帮助您利用 Frontend 编程 API 来构建和开发 Services ,像 JAX-WS 。这些 Services 可以支持多种协议,比如:SOAP、XML/HTTP、RESTful HTTP 或者 CORBA ,并且可以在多种传输协议上运行,比如:HTTP、JMS 或者 JBI,CXF 大大简化了 Services 的创建,同时它继承了 XFire 传统,一样可以天然地和 Spring 进行无缝集成。

2、下面是一个JAX-RS实现的简单例子:

(1)、创建实体类

package com.cxf.entity;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "UserInfo")
public class User {

    private int id;
    private String name;
    private String password;
    private String address;
    private String email;

    public int getId() {

        return id;
    }

    public void setId(int id) {

        this.id = id;
    }

    public String getName() {

        return name;
    }

    public void setName(String name) {

        this.name = name;
    }

    public String getPassword() {

        return password;
    }

    public void setPassword(String password) {

        this.password = password;
    }

    /** 
     * 获取address    
     * @return address
     */
    
    public String getAddress() {
    
        return address;
    }

    /**  
     * 设置address      
     * @param address
     */
    public void setAddress(String address) {
    
        this.address = address;
    }

    /** 
     * 获取email    
     * @return email
     */
    
    public String getEmail() {
    
        return email;
    }

    /**  
     * 设置email      
     * @param email
     */
    public void setEmail(String email) {
    
        this.email = email;
    }

}

package com.cxf.entity;

import java.util.HashMap;
import java.util.List;

public class Users {

    private List<User> users;
    private User[] userArr;
    private HashMap<String, User> maps;
    
    /** 
     * 获取users    
     * @return users
     */
    
    public List<User> getUsers() {
    
        return users;
    }
    /**  
     * 设置users      
     * @param users
     */
    public void setUsers(List<User> users) {
    
        this.users = users;
    }
    /** 
     * 获取userArr    
     * @return userArr
     */
    
    public User[] getUserArr() {
    
        return userArr;
    }
    /**  
     * 设置userArr      
     * @param userArr
     */
    public void setUserArr(User[] userArr) {
    
        this.userArr = userArr;
    }
    /** 
     * 获取maps    
     * @return maps
     */
    
    public HashMap<String, User> getMaps() {
    
        return maps;
    }
    /**  
     * 设置maps      
     * @param maps
     */
    public void setMaps(HashMap<String, User> maps) {
    
        this.maps = maps;
    }
    
    
}

package com.cxf.entity;


import java.util.Map;

import javax.xml.bind.annotation.XmlRootElement;


@XmlRootElement
public class MapBean {

    private Map<String, User> map;

    //@XmlElement(type = User.class)

    public Map<String, User> getMap() {

        return map;

    }

    public void setMap(Map<String, User> map) {

        this.map = map;

    }

} 

(2)、创建rest的接口

package com.cxf.webService;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
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.core.Context;
import javax.ws.rs.core.MediaType;

import com.cxf.entity.MapBean;
import com.cxf.entity.User;
import com.cxf.entity.Users;

@Path(value = "/services")
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("/list")
    @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
    public Users getList();

    @GET
    @Path("/map")
    @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
    public MapBean getMap();

    /*
        @Consumes:声明该方法使用 HTML FORM。 
        @FormParam:注入该方法的 HTML 属性确定的表单输入。 
        @Response.created(uri).build(): 构建新的 URI 用于新创建的联系人(/contacts/{id})并设置响应代码(201/created)。
                            您可以使用 http://localhost:8080/Jersey/rest/contacts/<id> 访问新联系人
     */
    @POST
    @Path("/postData")
    public User postData(User user) throws IOException;

    @PUT
    @Path("/putData/{id}")
    @Consumes(MediaType.APPLICATION_XML)
    public User putData(@PathParam("id") int id, User user);

    @DELETE
    @Path("/removeData/{id}")
    public void deleteData(@PathParam("id") int id);

}

(3)、创建rest服务类实现类

package com.cxf.webService.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.DELETE;
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.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.UriInfo;

import com.cxf.entity.MapBean;
import com.cxf.entity.User;
import com.cxf.entity.Users;
import com.cxf.webService.RESTSample;


@Path(value = "/services")
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
    @Path("/request/{param}")
    @Produces(MediaType.TEXT_PLAIN)
    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("/list")
    @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
    public Users getList() {

        System.out.println("####getList#####");
        System.out.println("Method:" + request.getMethod());
        System.out.println("uri:" + uriInfo.getPath());
        System.out.println(uriInfo.getPathParameters());
        

        List<User> list = new ArrayList<User>();
        User user = null;
        for (int i = 0; i < 4;i ++) {

            user = new User();
            user.setId(i);
            user.setName("JojO-" + i);
            list.add(user);
        }

        Users users = new Users();
        users.setUsers(list);

        return users;

    }

    @GET
    @Path("/map")
    @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
    public MapBean getMap() {

        System.out.println("####getMap#####");
        System.out.println("Method:" + request.getMethod());
        System.out.println("uri:" + uriInfo.getPath());
        System.out.println(uriInfo.getPathParameters());

        Map<String, User> map = new HashMap<String, User>();
        User user = null;
        for (int i = 0; i < 4;i ++) {
            
            user = new User();
            user.setId(i);
            user.setName("JojO-" + i);
            map.put("key-" + i, user);

        }

        MapBean bean = new MapBean();
        bean.setMap(map);

        return bean;

    }    

    

    /*
        @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("[email protected]");
        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);

    }

}

(4)、applicationContext-rs.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"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans.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" />


	<!-- 这里的地址很重要,客户端需要通过这个地址来访问WebService -->
	<jaxrs:server id="restServiceContainer" address="/">
		<jaxrs:serviceBeans>
			<ref bean="restSample" />
		</jaxrs:serviceBeans>
		<!-- <jaxrs:providers>
			<ref bean="authenticationFilter" />
		</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>

	<bean id="restSample" class="com.cxf.webService.impl.RESTSampleSource" />
	
</beans>

(5)、启动tomcat之后通过rul可以访问这些


这里以注解的形式把服务注册到Tomcat容器中,各注解的基本解释如下:

@Path:访问该Service的Service名
@POST @GET:访问该Service的某个方法时使用的HTTP请求方式
@Produces:访问Service中某个具体方法时需要提供的路径
@PathParam:从URL中传递过来的参数信息

你可能感兴趣的:(apache,spring,AOP,CXF,rs)