package ws; import javax.ws.rs.core.Context; import javax.ws.rs.core.UriInfo; import javax.ws.rs.Path; import javax.ws.rs.GET; import javax.ws.rs.Produces; import javax.ws.rs.core.MultivaluedMap; @Path("/employee/{empno}") // make this class processes this url. empno is a variable that represents employee number. public class EmployeeResource { public EmployeeResource() { } @GET // this method process GET request from client @Produces("application/json") // sends JSON public String getJson( @PathParam("empno") int empno) { // empno represents the empno sent from client switch(empno) { case 1 : return "{'name':'George Koch', 'age':58}"; case 2: return "{'name':'Peter Norton', 'age':50}"; default: return "{'name':'unknown', 'age':-1}"; } // end of switch } // end of getJson() }
<servlet> <servlet-name>ServletAdaptor</servlet-name> <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Converter</servlet-name> <url-pattern>/Converter</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>ServletAdaptor</servlet-name> <url-pattern>/resources/*</url-pattern> </servlet-mapping>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script language="javascript"> var xmlhttp; function init() { // put more code here in case you are concerned about browsers that do not provide XMLHttpRequest object directly xmlhttp = new XMLHttpRequest(); } function getdetails() { var empno = document.getElementById("empno"); var url = "http://localhost:8084/webservicedemo/resources/employee/" + empno.value; xmlhttp.open('GET',url,true); xmlhttp.send(null); xmlhttp.onreadystatechange = function() { var empname = document.getElementById("empname"); var age = document.getElementById("age"); if (xmlhttp.readyState == 4) { if ( xmlhttp.status == 200) { var det = eval( "(" + xmlhttp.responseText + ")"); if (det.age > 0 ) { empname.value = det.name; age.value = det.age; } else { empname.value = ""; age.value =""; alert("Invalid Employee ID"); } } else alert("Error ->" + xmlhttp.responseText); } }; } </script> </head> <body onload="init()"> <h1>Call Employee Service </h1> <table> <tr> <td>Enter Employee ID : </td> <td><input type="text" id="empno" size="10"/> <input type="button" value="Get Details" onclick="getdetails()"/> </tr> <tr> <td>Enter Name : </td> <td><input type="text" readonly="true" id="empname" size="20"/> </td> </tr> <tr> <td>Employee Age : </td> <td><input type="text" readonly="true" id="age" size="10"/> </td> </tr> </table> </body> </html>