2. Create a restful Web Service

Source: Internet
Author: User
Tags representational state transfer ibm developerworks

Introduction:Use the open-source Web service framework Apache cxf to create a restful web service defined as spring bean. This article explores the features and benefits of the representational state transfer (rest) architecture and demonstrates how to easily develop a restful service using rest APIs in cxf.

Introduction

In this article, we will build an Order application. The functions of this application are made public as a restful web service using cxf and spring. This Web service executes an order ResourcereadAndaddOperation. After reading this article, you will be able to apply concepts and features of the rest architecture and build and develop a restful web service using the rest API Based on cxf.

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

Rest is a Web architecture

Web services can be very complex, because Web service development often involves implementing a variety of infrastructure components, such as Web Services Description Language (WSDL) and soap, these components are bound to various other standards. To create a robust web service infrastructure model, each web server that provides a Web service solution must make significant investment. From the perspective of developers, it is increasingly complicated to master this technology. But don't be afraid! Rest can help you.

Restful Web services are only XML-over-HTTP Services. Generally, Web services require various contracts to be defined and negotiated between providers and customers. In contrast, restful services encapsulate data in a simple XML format and transmit data over HTTP, just like a web page request sent to a Web server.

Rest is more like an architecture than an implementation or standard. The rest architecture style is associated with web resources and is a representation identified by the Uniform Resource indicator (URI) (for example, http://myweb.com/myresource. A resource can be any persistent entity, including order, customer, and employee. The client queries or updates this resource through this URI, which affects its representative state changes. In short, client programs can use various HTTP methods to access, update, add, or delete a web resource through a URI, and then change its concrete state. HTTP methods includeGET,POST,PUTAndDELETE.

In short, rest is just a specification and provides a standard method for users to use HTTP request methods in the Web service style to call operations on web resources. Rest is closely related to HTTP and utilizes all HTTP features, such as methods, headers, and types.

Rest and cxf

Cxf is an open-source Web service framework that provides a simple API to easily build and develop web services. In part 1 of this series, you can see how simple it is to use spring-based cxf configuration to develop Web Services. This article will show you how easy it is to develop a restful service.

Cxf provides three restful Web Services:

  • JAX-RS (JSR-311)
  • HTTP binding
  • Java API for XML Web Services (JAX-WS)ProviderAndDispatchAPI
 

Back to Top

Order application

Now you can create an Order application that allows you to create and read or view order details. You can use restful Architecture styles and cxf to call these functions and manage your order applications. Before developing this application, define the use case:

  1. Create an order (generate a unique order ID ).
  2. The user queries the Order details (based on the order ID ).
  3. The user queries all orders.

Use URI to call each operation, which is usually the method of calling the web service. Each operation corresponds to one of the following HTTP request methods:GET,POST,PUTAndDELETE. This API uses Java rest annotations (JRA) ing to operate on HTTP/uri predicate combinations. Table 1 lists JRA/predicate combinations.


Table 1. JRA/predicate ing table

Jra HTTP Request Method Verb
@ Get GET Get
@ Post POST Add/create
@ Put PUT Update
@ Delete DELETE Delete

Develop a restful Service

To develop a restful web service, you must first create a service endpoint interface (SEI) and an implementation class. Then use a spring-based cxf configuration file for connection. Perform the following steps:

  1. Create an SEI and annotate it with rest annotations.
  2. Create this implementation class.
  3. Create beans. XML, use HTTP binding to define this service class as spring bean and publish it as a JAX-WS endpoint.
  4. Create web. xml.

The created SEI is namedOrderProcessAnd acts as a resource to indicate an interface.OrderClass is a resource class. Listing 1 shows thisOrderProcessSei.



Listing 1. orderprocess sei

@WebService(targetNamespace = "http://demo.order")public interface OrderProcess {  // Get all the orders  @Get @HttpResource(location = "/orders") @WebResult(name = "Orders") public Orders getOrders();  // Get order data based on the specified order ID  @Get @HttpResource(location = "/orders/{id}") public Order getOrder(@WebParam(name = "GetOrder") GetOrder getOrder);  // Add an order  @Post @HttpResource(location = "/orders") public void addOrder(@WebParam(name = "Order") Order order);}

 

OrderProcessThere are three methods for sei:

  • getOrderReturn order data based on the specified order ID.
  • getOrdersReturn all orders.
  • addOrderYou can add an order. This method accepts order bean as a parameter.

These methods can be defined using rest annotations, identified by Uris. @ Get annotationgetOrderAndgetOrdersMethod, @ post is usedaddOrderMethod. Each method can be identified by the URI defined by @ httpresource annotation. Now, Uri ing is available, as shown in table 2.



Table 2. method/uri ing table

Method Uri
getOrder /Orders/{ID}
getOrders /Orders
addOrder /Orders

Now you can createOrderProcessImplImplementation class, as shown in Listing 2.



List 2. orderprocessimpl service implementation

@WebService(endpointInterface = "demo.order.OrderProcess")public class OrderProcessImpl implements OrderProcess { Map<String, Order> orders = new HashMap<String, Order>();  private int i;  public Orders getOrders() {   Orders o = new Orders();   o.setOrder(orders.values());   return o;  }  public Order getOrder(GetOrder order) {   String orderID = order.getId();   return orders.get(orderID);  }  public void addOrder(Order order) {   String orderID = "ORD0" + (++i);   // Added as a POST request   String customerName = order.getName();    Order newOrder = new Order();   newOrder.setOrderID(orderID);   newOrder.setName(customerName);   orders.put(orderID, newOrder);   System.out.println("Order added successfully"); }}

 

The rest interface is ready. Let's take a look at its implementation.OrderProcessImplClass to implement this SEI and its method.addOrderThe method fills the Order details in hashmap, uses the order ID as the key, and uses the order instance as the value. Order bean has two attributes: orderid and customer name. Customer name usagePOSTThe request method is added, while the order ID is generated.getOrderThe method accepts the order ID as a parameter, obtains the corresponding order from hashmap, and returns the order.getOrdersMethod to return all orders of hashmap.

The next step is to create the beans. xml configuration file, as shown in listing 3.



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-http-binding.xml" /> <import resource="classpath:META-INF/cxf/cxf-servlet.xml" />  <jaxws:endpoint   id="orderProcess"   implementor="demo.order.OrderProcessImpl"   address="/"  bindingUri="http://apache.org/cxf/binding/http" >    <jaxws:serviceFactory >    <bean class="org.apache.cxf.jaxws.support.JaxWsServiceFactoryBean"> <property name="wrapped" value="false" />   </bean>    </jaxws:serviceFactory >  </jaxws:endpoint >  </beans>

 

OrderProcessImplThe bean definition of is encapsulated as a JAX-WS endpoint and the bound URI is http://apache.org/cxf/binding/http. This binding URI indicates that the service is bound to a resource using the HTTP binding method. The address is/, Relative to the web context.JaxWsServiceFactoryBeanA packaging property set to false is specified. This bean's XML-based request/response data should not be packaged as the root element of the operation name.



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, create web. xml and load the cxf configuration file. Then, you need to use the spring context loader to load the configuration file. You must also register a cxfservlet to process all requests from the client program.

Develop a client

For post requests, create a client classClient. Listing 5 showsClientClass.



Listing 5. Client class for processing post requests

public final class Client { public static void main(String[] args) throws Exception {  String xml = null;  try {   // Make an HTTP connection to the server   URL u = new URL("http://localhost:8080/orderapp_rest/orders");   HttpURLConnection httpCon = (HttpURLConnection)    u.openConnection();   // Set the request method as POST   httpCon.setRequestMethod("POST");    httpCon.setDoOutput(true);   OutputStream os = httpCon.getOutputStream();   // XML encoded in UTF-8 format   OutputStreamWriter wout = new OutputStreamWriter(os, "UTF-8");    wout.write("<?xml version=\"1.0\"?>\r\n");     // Add customer name as XML fragment   wout.write("<order xmlns=\"http://demo.order\">   <name>Rajeev</name></order>r\n");    wout.flush();   // Make implicit connection to the server   httpCon.getContentLength();    httpCon.disconnect();      os.close();  } catch (IOException e) {    e.printStackTrace();  } }}

 

This class creates an HTTP connection to http: // localhost: 8080/orderapp_rest/orders and sends XML data as post requests. This XML contains the Order details to be added. The customer name must be manually added and the order ID is automatically generated. Once this URL is called, the Order ID and customer name are added to the map set.

For GET requests, you only need to navigate to http: // localhost: 8080/orderapp_rest/orders/ord01 in the browser to obtain order details. The XML Element displayed contains the order data with the order ID ord01. Similarly, to display all orders placed by a customer, you only need to navigate to http: // localhost: 8080/orderapp_rest/orders in the browser.

Figure 1 shows the output when the browser navigating to Uri http: // localhost: 8080/orderapp_rest/orders/ord01.



Figure 1. GET request browser output

 

Back to Top

Conclusion

This article showsGETAndPOSTMethod. You have learned about the features and concepts of the rest architecture and how to use it to develop restful services with cxf.

Restful HTTP provides a unique concept for accessing and processing resources and a new perspective for Web service development. As web-based development becomes increasingly popular and common, rest technology will surely get better and better.



 

Back to Top

Download

Description Name Size Download Method
Order application Orderapp_rest.zip 12kb HTTP

Information about the Download Method



References

Learning

    • Read the tutorial design and development JAX-WS 2.0 web services (developerworks, September 2007) to get a step-by-step guide to developing web services using JAX-WS technology.

    • Read hands on web services to learn about how to design and develop practical Web service applications.
    • Read the article "MVC-style Web Service Architecture" (developerworks, November February 2002) to learn how to use the Model-View-controller (MVC) architecture to call static or dynamic Web Services.
    • The tutorial deliver web services to mobile apps explains how to access web services using mobile devices that support Java 2 platform and Micro Edition (j2s.
    • The IBM developerworks SOA and Web Services area provides a large number of articles and tutorials on how to develop Web service applications.
    • Experiment with ibm soa sandbox! 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.
    • Stay tuned to developerworks technical events and network broadcasts.
    • Visit the safari bookstore to read books on these and other technical topics. .
    • View the web services on demand demo.

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.