1 / 41

Web Service Implementation, Deploy and Test

课程名:以服务为中心的软件开发设计与实现. Web Service Implementation, Deploy and Test. Outline. Web service implementation and deploy REST JAX-WS. Representational State Transfer (REST). Two Camps SOAP, WS-* / XML-RPC REST (Representational State Transfer) What is REST?

arion
Download Presentation

Web Service Implementation, Deploy and Test

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 课程名:以服务为中心的软件开发设计与实现 Web Service Implementation, Deploy and Test

  2. Outline • Web service implementation and deploy • REST • JAX-WS

  3. Representational State Transfer (REST)

  4. Two Camps SOAP, WS-* / XML-RPC REST (Representational State Transfer) What is REST? Discussed in a PhD thesis by Roy Fielding When client traverses link, accesses new resource (i.e., transfers state) Uses existing standards, e.g., HTTP Two Camps on Web Services

  5. REST Characteristics • Client-Server: Clients pull representations • Stateless: each request from client to server must contain all needed information. • Uniform interface: all resources are accessed with a generic interface (HTTP-based) • Interconnected resource representations • Layered components - intermediaries, such as proxy servers, cache servers, to improve performance, security

  6. Security? Use SSL and HTTP Authentication HTTP methods/verbs: GET / POST / PUT / DELETE / HEAD Results should include URI for more info HTTP Headers, encoding, compression, caching, proxies Error handling? Use HTTP status/response codes & messages Resource location change? Use HTTP Redirect REST: HTTP-based!

  7. Web Sites GET http://en.wikipedia.org/wiki/REST GET http://www.bing.com/search?q=codecamp Web Services Flickr REST API http://www.flickr.com/services/rest?method=flickr.photos.search&api_key={api_key}&tags={tag} http://farm{farm-id}.static.flickr.com/{server-id}/{id}_{secret}_[mstb].jpg REST Example

  8. HTTP provides a simple set of operations. Amazingly, all Web exchanges are done using this simple HTTP API: GET = "give me some info" (Retrieve) POST = "here's some update info" (Update) PUT = "here's some new info" (Create) DELETE = "delete some info" (Delete) The HTTP API is CRUD (Create, Retrieve, Update, and Delete) Detailed REST methods

  9. Difference between GET/POST • GET: • For information retrieval • Data will be attached in URL • Example: login.action?name=hyddd&password=idontknow • Length Limit: IE (2083bytes), depends on OS/Browser • POST: • Anything • Data will be in the body of HTTP package

  10. URL 1 URL 2 HTTP GET request HTTP GET request Response (HTML/XML doc) Response (HTML/XML doc) HTTP response HTTP response URL to submitted PO HTTP response Process of RESTfulinvoling Parts List Part Data Web Server PO (HTML/XML) PO URL 3 HTTP POST

  11. XML JSON JSON Example <menu id="file" value="File"> <popup> <menuitem value="New" onclick="CreateNewDoc()" /> <menuitem value="Open" onclick="OpenDoc()" /> <menuitem value="Close" onclick="CloseDoc()" /> </popup> </menu> {"menu": { "id": "file", "value": "File", "popup": { "menuitem": [ {"value": "New", "onclick": "CreateNewDoc()"}, {"value": "Open", "onclick": "OpenDoc()"}, {"value": "Close", "onclick": "CloseDoc()"} ] } }}

  12. SOAP: WSDL (Web Services Description Language) REST: ? WADL (Web Application Description Language) Not supported Resistance due to fear it would impose an RPC style Write-up Documentation Popular Web Services provide client libraries for popular languages/platforms Describing REST web services

  13. Use HTTP codes (use the entity-body for more info) 200 OK 201 Created HTTP Location Header should have URI to new resource 400 Bad Request 404 Not Found 500 Internal Server Error 301 Moved Permanently 403 Forbidden 401 Unauthorized 409 Conflict Error Handling in REST

  14. WCF .NET 3.5 – added support for building REST Style services WCF .NET 3.5sp1 - UriTemplate flexibility, support ADO.NET Entity Framework entities in WCF contracts, improvements in the the dev tools ASP.NET MVC .NET 4.0: URL Routing in web forms WCF REST Starter Kit (beta) – make it easier Help page, Representation formats using Accepts HTTP Header, Declarative caching, X-HTTP-Method-Override Support in .NET

  15. Java: JAX-RS Jersey, RESTEasy, Enunciate, CXF, RESTlet Python: Django Flash/Flex: URLRequest class Browser plug-ins limited to GET and POST AIR – supports all methods Ruby – ActiveResource Mapping RESTful resources as models in a Rails application iPhone – ObjectiveResource, json-framework Support in other technologies

  16. Create a REST Web Service • Jersey • A RESTful web service framework based on JAX-RS standard • Supported by MyEclipse since ver. 7.0 • How to write a Simple HelloWorldRESTful Web Service in MyEclipse

  17. HelloWorldRESTful Web Service • Create a Web Service Project REST (JAX-RS)

  18. HelloWorldRESTful Web Service • Configure libraries Core JAXB Client JSON ATOM …

  19. HelloWorldRESTful Web Service • Create resource class HelloWorldResource

  20. HelloWorldRESTful Web Service • Write your HelloWorldResouce import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; @Path("/helloworld") public class HelloWorldResource { @GET @Produces("text/plain") public String sayHello() { return "Hello World"; } } javax.ws.rs.GET javax.ws.rs.Produces

  21. HelloWorldRESTful Web Service • View web.xml generated by MyEclipse <servlet> <display-name>JAX-RS REST Servlet</display-name> <servlet-name>JAX-RS REST Servlet</servlet-name> <servlet-class>com.sun.jersey.spi.container.servlet.ServletContaine</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>JAX-RS REST Servlet</servlet-name> <url-pattern>/services/*</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list>

  22. HelloWorldRESTful Web Service • Deploy to Tomcat HelloWorld MyEclipse Tomcat

  23. HelloWorldRESTful Web Service • Deploy to Tomcat Successful

  24. HelloWorldRESTful Web Service • Test • type in http://localhost:8080/HelloWorld/services/helloworld Successful

  25. Tools in MyEclipse

  26. Path Parameter Example @GET @Path("/{name}") @Produces("text/plain") public String sayHiWithName(@PathParam("name") String name) { return "Hi, " + name; }

  27. Annotations • @Path • URL Path • @GET / @POST • HTTP Method • @Consumes • MIME type the resource can accept from client (for POST) • @Produces • MIME type the resource can produce (send back to client)

  28. Parameters • @QueryParam • appended to the request URL with a leading "?" and then name/value pairs • http://www.google.com/search?q=apache+wink • @PathParam • @MatrixParam • @HeaderParam • @CookieParam • https://cwiki.apache.org/WINK/jax-rs-parameters.html

  29. XML vs. JavaObject • @XmlRootElement • publicclass Person { • private String id; • privateStringname; • private List<String> addresses; • @XmlElement(name="id") • public String getId() { • returnid; • } • @XmlElement(name="name") • public String getName() { • returnname; • } • @XmlElement(name="address") • public List<String> getAddresses() { • returnaddresses; • } • } <person> <address>Tsinghua University</address> <address>FIT Building</address> <address>1-308</address> <id>2010210760</id> <name>TANG Wenbin</name> </person>

  30. Invoke REST Service in Java //set URL URL url = new URL("http://localhost:8080/HelloWorld/services/helloworld/xml"); //make connection URLConnectionurlc = url.openConnection(); //use GET mode urlc.setDoInput(true); urlc.setAllowUserInteraction(false); //get result BufferedReaderbr = newBufferedReader(newInputStreamReader(urlc.getInputStream())); String l = null; while ((l=br.readLine())!=null) { System.out.println(l); } br.close();

  31. Test with REST WS Explorer

  32. Test with REST WS Explorer

  33. Java API for XML Web Services (JAX-WS)

  34. JAX-WS • JAX-WS is a Java programming language API for creating web services. • Latest version JAX-WS 2.0 • Part of Java EE. • New in Java SE 6. • API stack for web services. • Replaces JAX-RPC. • New API’s: JAX-WS, SAAJ, Web Service metadata • New packages: javax.xml.ws, javax.xml.soap,javax.jws

  35. Writing A Web Service with JAX-WS package loanservice; import javax.jws.WebService; import javax.jws.WebMethod; import javax.xml.ws.Endpoint; @WebService public class LoanApprover { @WebMethod public boolean approve(String name) { return name.equals("Mike"); }

  36. Writing A Web Service with JAX-WS(cont.) public static void main(String[] args){ LoanApprover la = new LoanApprover(); Endpoint endpoint = Endpoint.publish(“http://localhost:8080/loanservice”, la); } }

  37. Compile the Web Service Create a myservice directory. From the directory just above loanservice, run Java’s Annotation Processing Tool (APT): C:\>apt -d myserviceloanservice/LoanApprover.java This populates a directory named myservice. The directory holds the compiled package as well as a new directory (package) called jaxws. The new jaxws package holds classes associated with the parameters to and from each web service method. Use the -s switch to generate the source code.

  38. Publish the Service From a directory just above myservice: C:\>java -cp myserviceloanservice/LoanApprover To view the WSDL, visit the service with a browser at http://localhost:8080/loanapprover?wsdl

  39. Generate Stub Code Make a client directory. C:\>wsimport –p client –keep http://localhost:8080/loanapprover?wsdl This populates the client subdirectory with .class and .java files.

  40. Write the Client package client; class ApproverClient { public static void main(String args[]){ LoanApproverService service = new LoanApproverService(); LoanApproverapproverProxy = service.getLoanApproverPort(); boolean result = approverProxy.approve("Mike"); if(result) System.out.println("Approved"); else System.out.println("Not approved"); } }

  41. Compile & Run the Client C:\>javac –cp . client/ApproverClient.java C:\>java -cp . client/ApproverClient Approved

More Related