CXF(2.7.10) - RESTful Services

1. 定义 JavaBean。注意 @XmlRootElement 注解,作用是将 JavaBean 映射成 XML 元素。

package com.huey.demo.bean;

import javax.xml.bind.annotation.XmlRootElement;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
@XmlRootElement
public class Book {

    private String title;
    private String author;
    private String publisher;
    private String isbn;

}
package com.huey.demo.bean;

import javax.xml.bind.annotation.XmlRootElement;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
@XmlRootElement
public class ResultMsg {

    private String resultCode;
    private String message;

}

2. 定义服务接口。注意各个注解的作用。

package com.huey.demo.ws;

import java.util.List;

import javax.jws.WebService;
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.MediaType;

import com.huey.demo.bean.Book;
import com.huey.demo.bean.ResultMsg;

@WebService
public interface BookService {

    @GET                                                    // 指定请求方式
    @Path("/book/{isbn}")                                   // 指定资源的 URI
    @Produces( { MediaType.APPLICATION_XML } )              // 指定请求/响应的媒体类型
    public Book getBook(@PathParam("isbn") String isbn);

    @GET
    @Path("/books")
    @Produces( { MediaType.APPLICATION_XML } )
    public List<Book> getBooks();

    @POST
    @Path("/book")
    @Produces( { MediaType.APPLICATION_XML } )
    public ResultMsg addBook(Book book);

    @PUT
    @Path("/book/{isbn}")
    @Produces( { MediaType.APPLICATION_XML } )
    public ResultMsg updateBook(@PathParam("isbn") String isbn, Book book);

    @DELETE
    @Path("/book/{isbn}")
    @Produces( { MediaType.APPLICATION_XML } )
    public ResultMsg deleteBook(@PathParam("isbn") String isbn);
}

3. 实现服务接口。

package com.huey.demo.ws.impl;

import java.util.ArrayList;
import java.util.List;

import javax.jws.WebService;

import org.apache.commons.lang.StringUtils;

import com.huey.demo.bean.Book;
import com.huey.demo.bean.ResultMsg;
import com.huey.demo.ws.BookService;
import com.sun.org.apache.commons.beanutils.BeanUtils;

@WebService
public class BookServiceImpl implements BookService {

    List<Book> books = new ArrayList<Book>();

    public BookServiceImpl() {
        books.add(new Book("嫌疑人X的献身", "东野圭吾", "南海出版公司", "9787544245555"));
        books.add(new Book("追风筝的人", "卡勒德·胡赛尼 ", "上海人民出版社", "9787208061644"));
        books.add(new Book("看见", "柴静 ", "广西师范大学出版社", "9787549529322"));
        books.add(new Book("白夜行", "东野圭吾", "南海出版公司", "9787544242516"));
    }    

    public Book getBook(String isbn) {
        for (Book book : books) {
            if (book.getIsbn().equals(isbn)) {
                return book;
            }
        }
        return null;
    }

    public List<Book> getBooks() {
        return books;
    }

    public ResultMsg addBook(Book book) {
        if (book == null || StringUtils.isEmpty(book.getIsbn())) {
            return new ResultMsg("FAIL", "参数不正确!");
        }
        if (getBook(book.getIsbn()) != null) {
            return new ResultMsg("FAIL", "该书籍已存在!");
        }
        books.add(book);
        return new ResultMsg("SUCCESS", "添加成功!");
    }

    public ResultMsg updateBook(String isbn, Book book) {
        Book target = getBook(isbn);
        if (target != null) {
            ResultMsg resultMsg = new ResultMsg("SUCCESS", "更新成功!");
            try {
              BeanUtils.copyProperties(target, book);
            } catch (Exception e) {
                resultMsg = new ResultMsg("FAIL", "未知错误!");
            }
            return resultMsg;
        }
        return new ResultMsg("FAIL", "该书籍不存在!");
    }

    public ResultMsg deleteBook(String isbn) {
        Book book = getBook(isbn);
        if (book != null) {
            books.remove(book);
            return new ResultMsg("SUCCESS", "删除成功!");
        }
        return new ResultMsg("FAIL", "该书籍不存在!");
    }
}

4. Spring 配置。

<?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:jaxws="http://cxf.apache.org/jaxws"
    xmlns:jaxrs="http://cxf.apache.org/jaxrs" xmlns:cxf="http://cxf.apache.org/core"
    xsi:schemaLocation="
     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
     http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd
     http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd
     http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd">

    <bean id="bookRestService" class="com.huey.demo.ws.impl.BookServiceImpl" />

    <jaxrs:server id="bookService" address="/rest">
        <jaxrs:serviceBeans>
            <ref bean="bookRestService" />
        </jaxrs:serviceBeans>
    </jaxrs:server>

</beans>

5. web.xml 配置。

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <servlet>
        <servlet-name>CXFServlet</servlet-name>
        <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>CXFServlet</servlet-name>
        <url-pattern>/ws/*</url-pattern>
    </servlet-mapping>
</web-app>

6. 启动 Tomcat 运行 web 工程。

7. 测试。

a) getBooks

b) getBook

c) addBook

d) updateBook

e) deleteBook

时间: 2025-01-15 10:13:12

CXF(2.7.10) - RESTful Services的相关文章

CXF(2.7.10) - RESTful Services, JSON Support

在 CXF(2.7.10) - RESTful Services 介绍了 REST 风格的 WebService 服务,数据传输是基于 XML 格式的.如果要基于 JSON 格式传输数据,@Produces("application/xml") 修改为 @Produces("application/json"). package com.huey.demo.ws; import java.util.List; import javax.jws.WebService;

CXF结合spring发布WS服务,含SOAP services、RESTful services

1.访问:http://localhost:8088/sniperWS/services/查看有哪些服务,包含Available SOAP services.Available RESTful services 2.客户端调用RESTful services:http://localhost:8088/sniperWS/services/address/getSuggestions.query 调用示例:$.ajax({    url: "http://ip:port/sniperWS/serv

WebService框架CXF实战一发布RESTFul服务(七)

JAX-RS概述 JAX-RS是Java提供用于开发RESTful Web服务基于注解(annotation)的API.JAX-RS旨在定义一个统一的规范,使得Java程序员可以使用一套固定的接口来开发REST应用,避免了依赖第三方框架.同时JAX-RS使用POJO编程模型和基于注解的配置并集成JAXB,可以有效缩短REST应用的开发周期.JAX-RS只定义RESTful API,具体实现由第三方提供,如Jersey.Apache CXF等. JAX-RS包含近五十多个接口.注解和抽象类: ja

Service Station - An Introduction To RESTful Services With WCF

Learning about REST An Abstract Example Why Should You Care about REST? WCF and REST WebGetAttribute and WebInvokeAttribute UriTemplate and UriTemplateTable WebHttpBinding and WebHttpBehavior WebServiceHost and WebServiceHostFactory Using the Example

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

1.RESTful API接口定义 /* * Copyright 2016-2017 WitPool.org All Rights Reserved. * * You may not use this file except in compliance with the License. * A copy of the License is located at * http://www.witpool.org/licenses * * or in the "license" file

CXF(2.7.10) - WSDL2Java generated Client

以调用 http://www.webxml.com.cn/ 提供的 IpAddressSearchWebService 服务为例. 1. 使用 wsdl2java 工具,根据 wsdl 生成 JAX-WS 客户端 wsdl2java -client "http://webservice.webxml.com.cn/WebServices/IpAddressSearchWebService.asmx?wsdl" 2. 将生成代码导入工程.(可能报错,需要修改) 3. 访问服务. pack

开发基于CXF的 RESTful WebService web 项目 webservice发布

配置步骤 开发基于CXF的 RESTful WebService 1.创建Web项目并导入CXF的jar 2.在Web.xml中配置 CXFServlet <servlet> <servlet-name>cxf</servlet-name> <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class> </servlet> <servlet-

Web Service笔记(五):CXF开发RESTful风格的Web Service

前言: 1.Web Service笔记(五):利用CXF结合Spring开发web service 2.XML学习笔记(三):Jaxb负责xml与javaBean映射 3.jax-rs详解 4.可以使用浏览器的工具调试:如 Firefox 的RESTClient 和chrome的REST Console. 一.配置Spring的配置文件 1.需要引入新的 jar 包. 2.配置 applicationContext-server.xml 文件.使用 jaxrs:server ,记得引入jaxrs

WebService框架CXF实战一RESTFul服务(七)

JAX-RS概述 JAX-RS是Java提供用于开发RESTful Web服务基于注解(annotation)的API.JAX-RS旨在定义一个统一的规范,使得Java程序员可以使用一套固定的接口来开发REST应用,避免了依赖第三方框架.同时JAX-RS使用POJO编程模型和基于注解的配置并集成JAXB,可以有效缩短REST应用的开发周期.JAX-RS只定义RESTful API,具体实现由第三方提供,如Jersey.Apache CXF等. JAX-RS包含近五十多个接口.注解和抽象类: ja