Rest-based Web Services and Ajax-based clients

Source: Internet
Author: User
Introduction

In Roy Fielding's paper, he willRestThis is a basic concept of the current Web architecture. He sets the following standards for rest:

1. A set of constraints for modeling modern web architectures.
2. The rest principle has been applied to HTTP and Uri specifications.
3. It is visible in the Development of HTTP.

Rest is not a protocol, but an architectural style, which is a very important difference.

ForWeb ServicesW3C formal definitions of Web services are as follows:

"A Web Service is a software system identified by a URI and uses XML to define and describe its public interfaces and bindings. Other software systems can find its definition. Then, these systems can interact with the Web service in a predetermined manner, and use XML-based messages transmitted over the Internet ."

Common sense tells us that Web services are mainly used for communication between computers, rather than between computers and users. Rest-based Web services are Web Services created using the rest architecture. The next section uses an example to illustrate how to build a rest-based Web service. To master this content, you must first understand Ajax, which is very important. (If you are a newbie in Ajax, please refer to references for valuable information links .)

  Create a rest-based Web Service

To create a rest-based Web service, you must first determine all resources that you want to make public as a web service. Examples of some resources include the employee list, employee details, purchase orders, and so on. In rest, each type of resource is identified by a unique Uniform Resource Identifier (URI. You need to determine a unique URI for each resource. For example, the employee list can be identified as follows: http://www.employee-details.com/employees-list. Employee details can be identified by using the URI shown below: http://www.employee-details.com/employees/01234.

Use http get, put, post, and delete operations to retrieve and modify your resources. Provide some hyperlinks in your resource representation to provide more information. Specify the format for the request and response data of these resources, which requires put and post operations.

  Implement rest-based Web Services

You can use HTTP servlet to implement rest-based Web Services. This article uses a virtual service to demonstrate the implementation process, which provides detailed information about the company's employees. The employee list resource is represented by a logical Uri, http: // localhost: 9080/ajax_rest_demo/restdemoservlet/employee-list. When this service is called through http get, it returns the list of employees as shown in Listing 1.

Listing 1. Using http get to call the employee list

<? XML version = '1. 0' encoding = 'utf-8'?>
<P: Employees xmlns: P = 'HTTP: // www.employee-details.com '>
<Employee ID = '000000' href = '/employees/6666'/>
<Employee ID = '000000' href = '/employees/6666'/>
<Employee ID = '000000' href = '/employees/6666'/>
<Employee ID = '000000' href = '/employees/6666'/>
</P: Employees>

Similarly, employee details can be expressed using a logical Uri, such as http: // localhost: 9080/ajax_rest_demo/restdemoservlet/employee/0124. When this service is called through http get, it returns the employee details shown in Listing 2.

List 2. Call employee details using HTTP GET

<? XML version = '1. 0' encoding = 'utf-8'?>
<Empdetail xmlns: P = 'HTTP: // www.employee-details.com '>
<Emp-ID> 00345 </EMP-ID>
<Name> David Henry </Name>
<Department> Finance </Department>
</P: empdetail>

Listing 3 shows the servlet code. All operations adopt hard encoding, but they can be easily extended to interact with the database to become a real-time, rest-based service.

Listing 3. servlet code

Public class restdemoservlet extends httpservlet implements servlet {
/* (Non-Java-Doc)
* @ See javax. servlet. http. httpservlet # httpservlet ()
*/
Map map = new hashmap ();

/* (Non-javadoc)
* @ See javax. servlet. genericservlet # Init ()
*/
Public void Init () throws servletexception {
// Todo auto-generated method stub
Super. INIT ();

Employee emp0 = new employee ("David", "finance ");
Employee emp1 = new employee ("Smith", "Healthcare ");
Employee emp2 = new employee ("Adam", "Information Technology ");
Employee emp3 = new employee ("Stephen", "Life Sciences ");

Map. Put ("00345", emp0 );
Map. Put ("00346", emp1 );
Map. Put ("00347", emp2 );
Map. Put ("00348", emp3 );
}

/* (Non-Java-Doc)
* @ See javax. servlet. http. httpservlet # doget
(Httpservletrequest arg0, httpservletresponse arg1)
*/
Protected void doget (httpservletrequest arg0, httpservletresponse arg1)
Throws servletexception, ioexception {
// Todo auto-generated method stub
Arg1.setcontenttype ("text/XML ");
Printwriter out = arg1.getwriter ();
System. Out. println (MAP );
If (arg0.getpathinfo ()! = NULL ){
String empid = arg0.getpathinfo (). substring (1, arg0.getpathinfo (). Length ());
System. Out. println (empid );

Out. Write ("<? XML version = '1. 0' encoding = 'utf-8'?> "+"/N ");
Out. Write ("<P: empdetail xmlns: P = 'HTTP: // www.employee-details.com '>" + "/N ");
Out. Write ("<emp-ID>" + empid + "</EMP-ID>" + "/N ");
Out. Write ("<Name>" + (employee) map. Get (empid). Name + "</Name>" + "/N ");
Out. Write ("<Department>" + (employee) map. Get (empid). Dept + "</Department>" + "/N ");
Out. Write ("</P: empdetail>" + "/N ");
Out. Flush ();
} Else {
Out. Write ("<? XML version = '1. 0' encoding = 'utf-8'?> "+"/N ");
Out. Write ("<P: Employees xmlns: P = 'HTTP: // www.employee-details.com '>" + "/N ");
Out. Write ("<employee ID = '000000' href = 'HTTP: // localhost: 00345/
Ajax_rest_demo/restdemoservlet/employees/00345 '/> "+"/N ");
Out. Write ("<employee ID = '000000' href = 'HTTP: // localhost: 00346/
Ajax_rest_demo/restdemoservlet/employees/00346 '/> "+"/N ");
Out. Write ("<employee ID = '000000' href = 'HTTP: // localhost: 00347/
Ajax_rest_demo/restdemoservlet/employees/00347 '/> "+"/N ");
Out. Write ("<employee ID = '000000' href = 'HTTP: // localhost: 00348/
Ajax_rest_demo/restdemoservlet/employees/00348 '/> "+"/N ");
Out. Write ("</P: Employees> ");
Out. Flush ();
}
}

/* (Non-Java-Doc)
* @ See javax. servlet. http. httpservlet # dopost
(Httpservletrequest arg0, httpservletresponse arg1)
*/
Protected void dopost (httpservletrequest arg0, httpservletresponse arg1)
Throws servletexception, ioexception {
// Todo auto-generated method stub
}

}

In the next section, learn how to write an Ajax client for this rest-based Web service.

  Compiling Ajax clients for rest-based Web Services

As mentioned above, Ajax indicates Asynchronous JavaScript + XML. It is also known as xml http technology. In Ajax, the core technology is to implement asynchronous communication with the server without page refreshing. The XMLHTTPRequest object supports asynchronous get, post, put, and delete operations on the server. This does not show any content to the user. In other words, the status message is not displayed. You can specify a handler method for the status change and notify the handler when the following request occurs:

Initialization
Start
In the returned Process
Complete

Listing 4 shows an Ajax-based HTML page code, which can be used as the rest-based Web service client:

Listing 4. Ajax-based HTML page code

<Script language = "JavaScript" type = "text/JavaScript">
VaR Req = NULL;
// This function initializes xhr
Function initxhr (){
If (navigator. appname. indexof ("Microsoft")>-1 ){
Try {
Req = new activexobject ("Microsoft. XMLHTTP ");
} Catch (E1 ){
Alert ("failed to create xhr in IE ");
}
} Else {
Try {
Req = new XMLHttpRequest ();
} Catch (error ){
Alert ("failed to create xhr in Firefox ");
}
}
}
// Get an employee detail
Function getempdetails (empurl ){
Initxhr ();
Req. Open ("get", empurl, true );
Req. onreadystatechange = handleempdetailresponse;
Req. Send (null );
}

// Get employee list
Function getemployeelist (listurl ){
Initxhr ();
Req. Open ("get", listurl, true );
Req. onreadystatechange = handleemplistresponse;
Req. Send (null );
}
Function handleempdetailresponse (){
// If response is complete
If (req. readystate = 4 ){
// Response is OK
If (req. Status = 200 ){
VaR STR = "";
VaR response = Req. responsexml;
VaR root=response.doc umentelement;
For (I = 0; I <root. childnodes. length; I ++ ){
If (root. childnodes [I]. nodetype! = 1) continue;
VaR name = root. childnodes [I]. nodename;
VaR value = root. childnodes [I]. firstchild. nodevalue;
STR = STR + name + "--->" + value + "<br> ";
}
Document. getelementbyid ("emp-Div"). style. Display = "";
Document. getelementbyid ("emp-detail-Div"). innerhtml = STR;
} Else {
Document. getelementbyid ("messagediv"). innerhtml = "<span style = 'color: # ff0000;
Font-size: 12pt; text-Decoration: none; '<Invalid URL or partid </span> ";
}
Req. Abort ();
}
}

Function handleemplistresponse (){
// If response is complete

If (req. readystate = 4 ){
// Response is OK
If (req. Status = 200 ){
VaR pstr = "";
VaR response = Req. responsexml;
VaR root=response.doc umentelement;
For (I = 0; I <root. childnodes. length; I ++ ){
If (root. childnodes [I]. nodetype! = 1) continue;
VaR id = root. childnodes [I]. getattribute ("ID ");
VaR href = root. childnodes [I]. getattribute ("href ");
Pstr = pstr + "empid" + "--->" + ID + "<input type = 'bucket' value ='
Getempdetails 'onclick = "+ '"' + "getempdetails ('" + href + "')" + '"' +"> "+" <br> ";
}
Document. getelementbyid ("emp-list-Div"). style. Display = "";
Document. getelementbyid ("emp-List"). innerhtml = pstr;
} Else {
Document. getelementbyid ("messagediv"). innerhtml = "<span style = 'color: # ff0000;
Font-size: 12pt; text-Decoration: none; '> invalid employee ID. </span> ";
}
}
}
</SCRIPT>
<Center>
<Input type = "button" value = "getemployee-list" onclick = "getemployeelist
'Http: // localhost: 9080/ajax_rest_demo/restdemoservlet/employee-list') "> <br>
<Div id = "messagediv"> </div>
<Div id = "emp-list-Div" style = 'color: # ff0000; font-size: 12pt; text-Decoration: none;
Display: none; '> employee list: </div> <br>
<Div id = "emp-list"> </div> <br>
<Div id = "emp-Div" style = 'color: # ff0000; font-size: 12pt; text-Decoration: none;
Display: none; '> selected employee detail: </div> <br>
<Div id = "emp-detail-Div"> </div>
</Center>

In Listing 4, when you click the getemployee-list button, an xml http request is sent to the server. Specify the handler function handleemplistresponse for the xml http request to handle readystate changes. When the server completes the response (readystate = 4) and the response is OK, you can parse the XML and add it to the end of the Document Object Model (DOM) on the page, to display the list of employees. Similarly, when you click the getempdetails button, the handler function handleempdetailresponse processes the XML response from the server and modifies the DOM of the page to display the details of a specific employee.

  Conclusion

In this article, you learned how to use Servlet and Ajax-based clients to write rest-based Web Services. We hope you can find that you can easily understand and implement rest-based Web Services. Please refer to the valuable links provided in the reference section below.

Related Article

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.