1. Use cxf and spring to create Web Services

Source: Internet
Author: User
Tags ibm developerworks wsdl

Introduction:With the open-source Web service framework Apache cxf, you can easily create Web Services in the plain old Java object (pojo) style. This article is part 1 of this series and will show you how to use spring and cxf to publish pojo as a web service. This article also demonstrates the integration of cxf and Spring framework.

Introduction

In this article, you will use cxf and spring to build and develop an order processing web service. The Web service processes or verifies the order placed by the customer and returns a unique order ID. After reading this article, you will be able to apply the cxf concepts and functions to build and develop web services.

System Requirements

To run the example in this article, make sure that you have installed and configured the following software on your computer:

  • Java 5 or later
  • Tomcat 5 or later
  • Ant build tool
  • Cxf binary distribution 2.1

After the distribution version is installed, set the following environment variables:

  • Java_home (for Java)
  • Catalina_home (for Tomcat)
  • Ant_home (for ant)
  • Cxf_home (for cxf)

For example, you can set cxf_home = c: \ apache-cxf-2.1 and add the following content to the PATH environment variable:

  • Java_home \ bin
  • Catalina_home \ bin
  • Ant_home \ bin
 

Back to Top

Why cxf?

Apache cxf is an open-source framework that provides a reliable infrastructure for easy construction and development of Web Services. It allows you to create high-performance and scalable services. You can deploy such services in Tomcat, spring-based lightweight containers, and more advanced servers, for example, JBoss, IBM WebSphere, or BEA WebLogic.

Function

The framework provides the following functions:

  • Web service standard support:Cxf supports the following Web Service Standards:

    • Java API for XML Web Services (JAX-WS)
    • Soap
    • Web Service Description Language (WSDL)
    • Message transmission optimization mechanism (MTOM)
    • WS-basic profile
    • WS-Addressing
    • WS-Policy
    • WS-reliablemessaging
    • WS-Security
  • Frontend Modeling:Cxf provides the concept of frontend modeling, allowing you to use different frontend APIs to create Web Services. API allows you to use simple factory beans and create web services through JAX-WAS implementations. It also allows you to create dynamic web service clients.
  • Tool support:Cxf provides different tools for conversion between Java Bean, Web Service, and WSDL. It provides support for Maven and ant integration and seamlessly supports spring integration.
  • Restful service support:Cxf supports the concept of representative State Transfer (restful) services and the JAX-RS Implementation of the Java platform. (Part 1 of this series will provide more information about restful services .)
  • Support for different transmission and binding:Cxf supports different types of transmission, from XML to comma-separated values (CSV ). In addition to binding soap and HTTP, it also supports binding Java architecture for XML binding (jaxb) and Aegis data.
  • Support for non-XML binding:Cxf supports non-XML binding, such as JavaScript Object Notation (JSON) and Common Object Request Broker Architecture (CORBA ). It also supports Java business integration (jbi) architecture and service component architecture (SCA ).
 

Back to Top

Develop Web Services

Next let's take a deeper look at how to use the JAX-WS front-end to create order processing web services and then register them as spring beans. You will use the code priority method, which means that you will first develop a Java class and mark it as a web service. To do this, follow these steps:

  1. Create a service endpoint interface (SEI) and define a method that will be exposed as a web service.
  2. Create an implementation class and mark it as a web service.
  3. Create beans. xml and define the service class as spring bean using the JAX-WS frontend.
  4. Create web. XML to integrate Spring and cxf.

First, let's create an order processing Web Service sei.

Create order processing Web Service sei

Create a project namedOrderProcessSei, it will have a methodprocessOrderThis method accepts an order bean and returns a string.processOrderThe purpose of this method is to process the order placed by the customer and return a unique order ID.


Listing 1. orderprocess sei

                package demo.order;import javax.jws.WebService;@WebServicepublic interface OrderProcess {  String processOrder(Order order);}

 

As you can see in Listing 1,OrderProcessSEI is only a standard Java interface labeled as a web service.@WebServiceAnnotation only makes this interface a web service interface. The client or user uses this interface to call the service method.OrderProcessSEI has a service methodprocessOrder, This method acceptsOrderReturn the order ID as a parameter and a string.


List 2. orderprocess service implementation

                package demo.order;import javax.jws.WebService;@WebService(endpointInterface = "demo.order.OrderProcess")public class OrderProcessImpl implements OrderProcess { public String processOrder(Order order) {  return order.validate(); }}

 

Compile sei implementation

To compile the SEI implementation in the previous section, you must also set your implementation classOrderProcessImplMark as a web service and provide PropertiesendpointInterfaceThe value is the fully qualified name of the SEI created in the previous step. This tells the implementation of this classOrderProcessSei. Because it is the implementation of SEI, you must provideprocessOrderMethod implementation.

You have created an SEI and its implementation. With cxf, you can now use the JAX-WS front-end to make it an actual service component.


Listing 3. Beans. xml configuration file

                <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxws="http://cxf.apache.org/jaxws" xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd"> <import resource="classpath:META-INF/cxf/cxf.xml" /> <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" /> <import resource="classpath:META-INF/cxf/cxf-servlet.xml" />  <jaxws:endpoint   id="orderProcess"   implementor="demo.order.OrderProcessImpl"   address="/OrderProcess" />  </beans>

 

Create a configuration file for cxf

The cxf configuration file actually contains the spring configuration file defined by bean. You will use the JAX-WS front-end configurationOrderProcessCreate bean definitions for Web Services. In the beans. xml file<jaxws:endpoint>MarkOrderProcessThe Web Service is specified as a JAX-WS endpoint. This actually means that cxf uses the JAX-WS internally to publish this web service. You must provide the name of the implementation class, that isOrderProcessImpl, And<jaxws:endpoint>The marked address. The address you provide is related to the web context.


Listing 4. Web. XML Web configuration file

                <web-app> <context-param>  <param-name>contextConfigLocation</param-name>  <param-value>WEB-INF/beans.xml</param-value> </context-param> <listener>  <listener-class>   org.springframework.web.context.ContextLoaderListener  </listener-class> </listener> <servlet>  <servlet-name>CXFServlet</servlet-name>  <display-name>CXF Servlet</display-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>/*</url-pattern> </servlet-mapping></web-app>

 

Finally, you must perform the following operations:

  • Create a web. xml file that loads the cxf configuration file.
  • Use the spring context loader to load the configuration file.
  • Register the cxfservlet to process all requests from the client program.

You have completed the development of necessary server components. Now you can developOrderProcessThe client component that the Service sends the request.

 

Back to Top

Development Client

As shown in listing 5, it is very easy to create a client bean, just like creating a service endpoint.JaxWsProxyFactoryUsed to createOrderProcessThe client bean of the web service. The factory bean is expected to obtain the service class (OrderProcess) And your service URL. Then, create the client bean stub by using the factory bean reference.OrderProcess.


Listing 5. client-bean.xml client web configuration file

                <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxws="http://cxf.apache.org/jaxws" xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.0.xsdhttp://cxf.apache.org/jaxwshttp://cxf.apache.org/schema/jaxws.xsd"> <bean id="client" class="demo.order.OrderProcess"   factory-bean="clientFactory" factory-method="create"/> <bean id="clientFactory" class="org.apache.cxf.jaxws.JaxWsProxyFactoryBean">  <property name="serviceClass" value="demo.order.OrderProcess"/>  <property name="address" value="http://localhost:8080/orderapp/OrderProcess"/> </bean>  </beans>

 

You will create a Java main program, which uses spring context to obtain the defined client bean, and then callsprocessOrderMethod.


Listing 6. client code

                public final class Client { public Client() { } public static void main(String args[]) throws Exception {  ClassPathXmlApplicationContext context    = new ClassPathXmlApplicationContext(new String[]      {"demo/order/client/client-beans.xml"});  OrderProcess client = (OrderProcess)context.getBean("client");    Order order = new Order();  String orderID = client.processOrder(order);  System.out.println("Order ID: " + orderID);  System.exit(0); }}

 

 

Back to Top

Run the program

Before running the program, create the directory structure shown in 1 in your c: \ disk root folder and place the components described in this article in it:

  • Put the Java code in the package folder.
  • Put Beans. XML and Web. xml in the web \ Web-INF folder.
  • The client-beans.xml is placed in the demo \ order \ Client folder.


Figure 1. Code directory structure
 

For building, deploying, and runningOrderProcessWeb Service and client, you will use ant tool. The code will be deployed on the Tomcat server. In the c: \ orderapp folder, useant deployCommand to deploy the code.

The application folder (C: \ orderapp) has an ant build file. After running the preceding commandorderappThe code will be deployed in the Tomcat server environment as the orderapp. War file. Now, you can providecatalina startCommand to start the Tomcat web server.

The orderapp folder is created under the webapps folder of Tomcat. After the server is started, enterant clientCommand to run the application. The output displays the order ID (see figure 2 ).



Figure 2. program output
 

Conclusion

This article briefly describes the functions of the cxf framework and demonstrates how it allows you to create web services without much coding effort. You understand the integration of spring and cxf Using Bean context files. You also studied how the framework abstracts the actual semantics of the web service infrastructure component and provides a simpler API shell that is only concentrated on Web Service creation.

Now you know the basics of using cxf to create Web Services. Continue to Part 1 of this series, which will show you how to use cxf and spring to publish pojo as a restful service.



 

Back to Top

Download

Description Name Size Download Method
Order application Orderapp.zip 11kb HTTP

Information about the Download Method



References

Learning

    • For more information, see the original article on the developerworks global site.

    • Read the tutorial design and development JAX-WS 2.0 web services to get a step-by-step guide to developing web services using JAX-WS technology.
    • ReadHands on Web ServicesThis book describes how to design and develop practical Web service applications.
    • Read the article "MVC-style Web Service Architecture" to learn how to use the Model-View-controller (MVC) architecture to call static or dynamic Web Services.
    • "Deliver web services to mobile apps" explains how to use mobile devices that support Java 2 platform and Micro Edition (j2s) to access web services.
    • The IBM developerworks SOA and Web Services area provides a large number of articles and tutorials on how to develop Web service applications.
    • Use the ibm soa sandbox for testing! Improve your SOA skills through practical hands-on practices of ibm soa.
    • The ibm soa website provides an overview of SOA and describes how IBM helps you implement SOA.
    • Learn about the latest developerworks technical events and network broadcasts.
    • Visit the safari bookstore and browse books on these technical topics and other topics.
    • See the developerworks demo center.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.