410 likes | 596 Views
课程名:以服务为中心的软件开发设计与实现. 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?
E N D
课程名:以服务为中心的软件开发设计与实现 Web Service Implementation, Deploy and Test
Outline • Web service implementation and deploy • REST • JAX-WS
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
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
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!
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
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
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
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
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()"} ] } }}
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
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
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
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
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
HelloWorldRESTful Web Service • Create a Web Service Project REST (JAX-RS)
HelloWorldRESTful Web Service • Configure libraries Core JAXB Client JSON ATOM …
HelloWorldRESTful Web Service • Create resource class HelloWorldResource
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
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>
HelloWorldRESTful Web Service • Deploy to Tomcat HelloWorld MyEclipse Tomcat
HelloWorldRESTful Web Service • Deploy to Tomcat Successful
HelloWorldRESTful Web Service • Test • type in http://localhost:8080/HelloWorld/services/helloworld Successful
Path Parameter Example @GET @Path("/{name}") @Produces("text/plain") public String sayHiWithName(@PathParam("name") String name) { return "Hi, " + name; }
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)
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
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>
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();
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
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"); }
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); } }
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.
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
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.
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"); } }
Compile & Run the Client C:\>javac –cp . client/ApproverClient.java C:\>java -cp . client/ApproverClient Approved