Representational State Transfer
(REST).
Java API for RESTful Web Services (JAX-RS), is a set if APIs to developer REST service. JAX-RS is part of the Java EE6, and make developers to develop REST web application easily.
Both Jersey and RESTEasy, popular JAX-RS implementation.
RESTful web services are built to work best on the Web.
The following principles encourage RESTful applications to be simple, lightweight, and fast:
Resource identification through URI: A RESTful web service exposes a set of resources that identify the targets of the interaction with its clients. Resources are identified by URIs, which provide a global addressing space for resource and service discovery.
Here is the Sample Application where Username
and password are captured through JQUERY and when button is clicked throught AJAX calling Rest calls.
Which returns result in JSON
index.html
Java API for RESTful Web Services (JAX-RS), is a set if APIs to developer REST service. JAX-RS is part of the Java EE6, and make developers to develop REST web application easily.
Both Jersey and RESTEasy, popular JAX-RS implementation.
Java API for XML Web Services (JAX-WS) is a set of APIs for creating web services in XML format (SOAP). JAX-WS provides many annotation to simplify the development and deployment for both web service clients and web service providers (endpoints).
The following principles encourage RESTful applications to be simple, lightweight, and fast:
Resource identification through URI: A RESTful web service exposes a set of resources that identify the targets of the interaction with its clients. Resources are identified by URIs, which provide a global addressing space for resource and service discovery.
Creating a RESTful Root Resource Class
Root resource classes are POJOs that are either annotated with @Path or have at least one method annotated with @Path or a request method designator, such as @GET, @PUT, @POST, or @DELETE. Resource methods are methods of a resource class annotated with a request method designator. This section explains how to use JAX-RS to annotate Java classes to create RESTful web services.import javax.ws.rs.GET; import javax.ws.rs.Produces; import javax.ws.rs.Path; // The Java class will be hosted at the URI path "/helloworld" @Path("/helloworld") public class HelloWorldResource { // The Java method will process HTTP GET requests @GET // The Java method will produce content identified by the MIME Media // type "text/plain" @Produces("text/plain") public String getClichedMessage() { // Return some cliched textual content return "Hello World"; } }
- The @Path annotation’s value is a relative URI path. In the preceding example, the Java class will be hosted at the URI path /helloworld. This is an extremely simple use of the @Path annotation, with a static URI path. Variables can be embedded in the URIs. URI path templates are URIs with variables embedded within the URI syntax.
- The @GET annotation is a request method designator, along with @POST, @PUT, @DELETE, and @HEAD,
defined by JAX-RS and corresponding to the similarly named HTTP
methods. In the example, the annotated Java method will process HTTP GET requests. The behavior of a resource is determined by the HTTP method to which the resource is responding.
- The @Produces annotation is used to specify the MIME
media types a resource can produce and send back to the client. In this
example, the Java method will produce representations identified by the
MIME media type "text/plain".
- The @Consumes annotation is used to specify the MIME media types a resource can consume that were sent by the client. The example could be modified to set the message returned by the
getClichedMessage method, as shown in this code example: @POST @Consumes("text/plain") public void postClichedMessage(String message) { // Store the message }
The @Path Annotation and URI Path Templates
URI path templates are URIs with variables embedded within the URI syntax. These variables are substituted at runtime in order for a resource to respond to a request based on the substituted URI. Variables are denoted by braces ({ and }). For example, look at the following @Path annotation:@Path("/users/{username}") public class UserResource { @GET @Produces("text/xml") public String getUser(@PathParam("username") String userName) { ... } }
Here is the Sample Application where Username
and password are captured through JQUERY and when button is clicked throught AJAX calling Rest calls.
Which returns result in JSON
index.html
<!DOCTYPE html> <head> <title>SIMS MOBILE APPS</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="Content-type" content="text/html; charset=utf-8"/> <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script> <style> body,ul,section,header, nav, h1, li { display: block; margin: 0; padding: 0; } body { background: #f6f5de; color: #100; font: 100%/1.4 Helvetica, Arial, sans-serif; } header { background: #4b8fcf; color: #dedcb9; padding: 0.5em 0; padding:0; position: absolute; top: 0; left: 0; width: 100%; z-index:2; } #logo { float:left; } #headertitle { float:left; font-size:12px; font-weight:bold; padding-left:10px; } #logout1 { float:right; } footer { text-align: center; background: #4b8fcf; color: #dedcb9; position: fixed; bottom: 0; left: 0; width: 100%; height:40px; bottom:0; left:0; } #serverlogo { float:left; } #status { float:left; font-size:12px; font-weight:bold; padding-left:10px; } #technobrainlogo { float:right; } section { padding: 3.3em 0; } /*Scrollable Regions Pages*/ .scrollable header { position: static; } .scrollable section { padding-top: 0; height: 500px; overflow: scroll; } form{ text-align:center; background-color: rgba(250,250,250,0.5); box-shadow: 2px 2px 5px 10px rgba(0, 0, 0, 0.2), inset 0px 1px 0px 0px rgba(250, 250, 500, 0.5); border: 15px solid rgba(0, 0, 0, 0.3); background-color: #f6f5de; } #btnLogin{ height:40px; width:100px; background-color: #60a2df; } input:required{ background: #fff url(red_asterisk.png) no-repeat 100% center; } #wrapper { position:absolute; z-index:1; top:80px; bottom:70px; left:0; width:100%; overflow:auto; } #main-content { position:absolute; z-index:1; width:100%; padding:0; } </style> </head> <body> <header style="vertical-align:text-top;"> <img id="logo" src="headerlogo.png"/> <p id="headertitle" > Sales Inventory and Management</p> </header> <section> <div id="wrapper"> <div id="main-content"> <form action="#" method="post" id="loginform"> <div> <p style="font-weight:bold;text-align:center;">Login</p></div> <span >Username<input type="text" id="username" required placeholder="Username" autofocus /></span><br/><br/> <span>Password <input type="password" placeholder="Password" id="password" onkeypress="return runScript(event)" required /></span></br></br> <label id="requiredError" style="font-weight:bold;"></label><br /> <input type="button" id="btnLogin" value="Log In" /> <a href="CNU.html">Create New User</a> </form><!-- form --> </div> </div> </section><!-- content --> <footer class="footer"> <img src="server.png" id="serverlogo"/> <p id="status">Server Status</p> <div><img src="Logo_transp.png" id="technobrainlogo" style="padding-right:5px;"/> </div> </footer> </body> </html> <script type="text/javascript" language="javascript"> $(document).ready(function() { var data= ''; $("#btnLogin").click(function() { var USER_NAME = $('#username').val(); var PASSWORD = $('#password').val(); if(USER_NAME =='' && PASSWORD =='') { var div = document.getElementById("requiredError"); div.innerHTML = "Warning:Please Enter All Fields"; div.style.color = "red"; }else if(USER_NAME =='' ) { var div = document.getElementById("requiredError"); div.innerHTML = "Warning:Please Enter Username"; div.style.color = "red"; }else if(PASSWORD =='') { var div = document.getElementById("requiredError"); div.innerHTML = "Warning:Please Enter password"; div.style.color = "red"; }else if(USER_NAME =='' && PASSWORD =='' ){ var div = document.getElementById("requiredError"); div.innerHTML = "Warning:Enter username or password is incorrect"; div.style.color = "red"; } else{ $.ajax({ type: "GET", url: "http://192.0.0.1:8080/RESTfulExample/users/getAuthUser?callback=success&USER_NAME="+USER_NAME+"&PASSWORD="+PASSWORD, dataType: 'jsonp', crossDomain: true, cache: false, success: success }); } }); }); function success(response){ //alert(response); var obj = jQuery.parseJSON(response); //alert( obj.Customer); //alert( obj.License); if (obj.Customer == "False" ){ alert("Access Denied,User tried to access with wrong input"); }else if(obj.expiry!="False"){ alert("Your License has been expired."); } else if(obj.status=="Deactivated" && obj.Customer != "False" &&obj.License != "False" ){ alert("Your account has been deactivated please consult Admin"); } else if(obj.Customer != "False" && obj.status=="Deactivated" &&obj.License == "False" && obj.uuid == "False"){ alert("Please wait till the licence is generated"); }else if(obj.Customer != "False" && obj.status != "Deactivated" &&obj.License != "False" && obj.uuid == "False"){ var query = obj.License; var query1= obj.Customer; var firstPart = "HomePage.html?License="+query+"&Customer="+query1; window.location.href = firstPart; } else if(obj.uuid != "False"){ window.location.href="MenuPage.html"; } } </script>
//CreateNewUser method calls String DBase_URL =
"jdbc:sqlserver://192.0.0.1\\testing;database=SAMPLE;integratedSecurity=false"; //userlogin @GET @Path("/getAuthUser") public String getAuthUser(@Context HttpServletRequest request,@Context HttpServletResponse response)throws Exception { String callBackJavaScripMethodName = request.getParameter("callback"); String USER_NAME= request.getParameter("USER_NAME"); String PASSWORD= request.getParameter("PASSWORD"); Connection conn = null; String Customermsg="False"; String Licencemsg="False"; String Uuidmsg="False"; String status="Deactivated"; String expiry="False"; Date todayDate= new Date(); Date dbDate = null; Long cid=new Long(0); PreparedStatement stmt = null; try{ Class.forName(JDBC_DRIVER); conn = DriverManager.getConnection(DBase_URL,USER,PASS); String sql ="select * from CUSTOMER where USER_NAME='"+USER_NAME+"' and PASSWORD='"+PASSWORD+"'" ; stmt = conn.prepareStatement(sql); ResultSet res=stmt.executeQuery(); List<Customer> list = new ArrayList<Customer>(); while (res.next()) { Customer cust=new Customer(); cid=res.getLong("CUSTOMER_ID"); cust.setCustomerId(cid); Uuidmsg=res.getString("UUID"); status=res.getString("STATUS"); cust.setUuid(Uuidmsg); list.add(cust); } if(list.size()==1){ Customermsg=cid.toString(); if(Uuidmsg==null || Uuidmsg.length()<16) Uuidmsg="False"; } Class.forName(JDBC_DRIVER); conn = DriverManager.getConnection(DBase_URL,USER,PASS); String sql1 = "select * from LICENSE_DETAILS where CUSTOMER_ID='"+cid+"'" ; stmt = conn.prepareStatement(sql1); ResultSet res1=stmt.executeQuery(); List<LicenseDetails> list1 = new ArrayList<LicenseDetails>(); while (res1.next()) { LicenseDetails cust=new LicenseDetails(); Licencemsg=res1.getString("LICENSE_NO"); dbDate=res1.getDate("EXPIRY_DATE"); cust.setLicenseNo(Licencemsg); list1.add(cust); } if(list1.size()==1){ Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(dbDate.getTime()); if(cal.getTime().compareTo(todayDate)<0){ expiry = "Expired"; } } Map<String,String> map = new HashMap<String, String>(); map.put("Customer",Customermsg); map.put("License", Licencemsg); map.put("uuid", Uuidmsg); map.put("status",status); map.put("expiry", expiry); String jsonString = new Gsn().toJson(map); String jsonPoutput = callBackJavaScripMethodName + "(\'"+jsonString+"\')"; response.setContentType("text/javascript"); return jsonPoutput; }catch (Exception e) { e.printStackTrace(); return null; }finally{ try{ if(stmt!=null) stmt.close(); if(conn!=null) conn.close(); }catch(SQLException se2){ se2.printStackTrace(); } }}
No comments:
Post a Comment