• cxf restful


    Restful 服务端

    1 创建好pojo、dao、service, dao进行数据库操作,service提供服务

      

    @Path("/roomservice")
    @Produces("application/xml")
    public class RoomService {
        
        @GET
        @Path("/room/{id}")
        @Consumes("application/xml")
        public Room getRoom(@PathParam("id")String id )
        {
            System.out.println("get room by id= "+id);
            Room room=RoomDAO.getRoom(id);
            return room;
        }
    
        @POST
        @Path("/room")
        @Consumes("application/xml")
        public void addRoom(Room room)
        {
    ...
    
    
    通常需要使用注解: GET/POST/PUT/DELETE, Path, Consumes, 有参数的方法需要加上 @PathParam

    2 通过JAXRSServerFactoryBean来发布服务 —— 一个类即可!  

    public class Server {
    
        public static void main(String[] args) {
            RoomService service = new RoomService();
    
            // Service instance
            JAXRSServerFactoryBean restServer = new JAXRSServerFactoryBean();
            restServer.setResourceClasses(Room.class,Person.class,Room.class);
            restServer.setServiceBean(service);
            restServer.setAddress("http://localhost:9999/");
            restServer.create();
        }
    }

    restful 客户端

    使用一个类即可:org.apache.cxf.jaxrs.client.WebClient ! 非常方便

    public class Client {
        static WebClient client;
    
        public static void main(String[] args) {
            client = WebClient.create("http://localhost:9999/");
            put();
        }
    
        static void get() {
            Room room = client.path("roomservice/room/001")
                    .accept("application/xml").get(Room.class);
            System.out.println("get the room which id is:" + room.getId());
        }
    
        static void post() {
            Room room = new Room();
            room.setId("003");
            client.path("roomservice/room").accept("application/xml")
                    .post(room, Room.class);
        }
    
        static void delete() {
            client.path("roomservice/room/002").accept("application/xml").delete();
        }
    
        static void put() {
            Room room = new Room();
            room.setId("009");
            client.path("roomservice/room/003").accept("application/xml").put(room);
        }
    }

    总结

     服务端开发:

     1 创建web项目

    2 写好接口、实现类

    3 通过与spring集成或者直接发布、或者启动server类

    客户端开发:

    1 根据服务器发布的服务,使用wsdl2java创建客户端代码stub

    2 通过cxfapi访问,服务端的服务

    参考

    http://borissun.iteye.com/blog/765869

    http://www.cnblogs.com/i-bugs/p/3755615.html

    疑问

    如果是js端访问呢?

  • 相关阅读:
    web中的安全编码
    网站安全(学习)
    head 命令(转)
    less 命令(转)
    简单网站优化
    Yahoo团队总结的关于网站性能优化的经验(转)
    more命令(转)
    linux安装oracle
    Ubuntu系统环境变量配置文件(转)
    nl命令(转)
  • 原文地址:https://www.cnblogs.com/FlyAway2013/p/3859380.html
Copyright © 2020-2023  润新知