By S.Luann
Define resources:
Resources are represented by Uris. we will implement the following two resources and use HTTP GET access method. Response using XML serialization.
1. Employee list:
"http://localhost:9080/AJAX_REST_Demo/RESTDemoServlet/employee-list"
Response:
<?xml version='1.0' encoding='UTF-8'?>
<p:Employees xmlns:p='http://www.employee-details.com'>
<Employee id='00345' href='/employees/00345'/>
<Employee id='00346' href='/employees/00346'/>
<Employee id='00347' href='/employees/00347'/>
<Employee id='00348' href='/employees/00348'/>
</p:Employees>
2. A employee:
"http://localhost:9080/AJAX_REST_Demo/RESTDemoServlet/employee/0124"
Response:
<?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>
Implementation of the client
var req=null;
// initialize the requester ---------------
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");
}
}
}
// Request functions ----------------------
//get an employee
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);
}
// Callback handlers -------------------
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.documentElement;
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.documentElement;
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='button' 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 >";
}
}
}
// HTML Page ----------------------
<div id="container">
<input type="button" value="getEmployee-List" onclick="getEmployeeList
'http://localhost:9080/AJAX_REST_Demo/RESTDemoServlet/employee-list')" > <br > <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 > <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 >
</div>
Implementation of Servlet
The following code is staightforward. First code the init method which is called when initialize a Servlet. here the dummy data is prepared.
Next, override the doGet method of the HttpServlet class, from the passing in parameter get the stream writer and put the expected result in.
HttpServletRequest, HttpServletResponse are two objects passed in representing request and response states respectively. these two give the all environment for handing a request.
public class RESTDemoServlet extends HttpServlet implements Servlet {
Map map =new HashMap();
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("Stephan","Life Sciences");
map.put("00345",emp0);
map.put("00346",emp1);
map.put("00347",emp2);
map.put("00348",emp3);
}
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='00345' href='http://localhost:9080/
AJAX_REST_Demo/RESTDemoServlet/employees/00345'/ >"+"\n");
out.write("<Employee id='00346' href='http://localhost:9080/
AJAX_REST_Demo/RESTDemoServlet/employees/00346'/ >"+"\n");
out.write("<Employee id='00347' href='http://localhost:9080/
AJAX_REST_Demo/RESTDemoServlet/employees/00347'/ >"+"\n");
out.write("<Employee id='00348' href='http://localhost:9080/
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
}
}
Reference
1. Shailesh K. Mishra, RESTful Web services and their Ajax-based clients
http://www.ibm.com/developerworks/webservices/library/ws-restajax/
No comments:
Post a Comment