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 on Web Services• 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
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
REST: HTTP-based!• 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
7
REST Example• 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
8
Detailed REST methods• 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)
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
10W
eb S
erve
r
HTTP POST URL 3PO(HTML/XML)
HTTP GET request URL 1
HTTP responseURL to submitted PO
PartsList
PartData
PO
HTTP responseResponse(HTML/XML doc)
HTTP responseResponse(HTML/XML doc)
HTTP GET request URL 2
Process of RESTful involing
11
JSON Example
XML
JSON
{"menu": { "id": "file", "value": "File", "popup": { "menuitem": [ {"value": "New", "onclick": "CreateNewDoc()"}, {"value": "Open", "onclick": "OpenDoc()"}, {"value": "Close", "onclick": "CloseDoc()"} ] }}}
<menu id="file" value="File"> <popup> <menuitem value="New" onclick="CreateNewDoc()" /> <menuitem value="Open" onclick="OpenDoc()" /> <menuitem value="Close" onclick="CloseDoc()" /> </popup></menu>
12
Describing REST web services• 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
13
Error Handling in REST
• 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
14
Support in .NET
• 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
15
Support in other technologies• 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
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 HelloWorld RESTful Web
Service in MyEclipse
17
HelloWorld RESTful Web Service• Create a Web Service Project
REST (JAX-RS)
18
HelloWorld RESTful Web Service• Configure libraries
CoreJAXBClientJSONATOM
…
19
HelloWorld RESTful Web Service• Create resource class
HelloWorldResource
20
HelloWorld RESTful 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.GETjavax.ws.rs.Produces
21
HelloWorld RESTful 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
HelloWorld RESTful Web Service• Deploy to Tomcat
HelloWorld MyEclipse Tomcat
23
HelloWorld RESTful Web Service• Deploy to Tomcat
Successful
24
HelloWorld RESTful 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@XmlRootElementpublic class Person {
private String id;private Stringname;private List<String> addresses;
@XmlElement(name="id")public String getId() {
return id;}
@XmlElement(name="name")public String getName() {
return name;}
@XmlElement(name="address")public List<String> getAddresses() {
return addresses;}}
<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 URLURL url = new URL("http://localhost:8080/HelloWorld/services/helloworld/xml");
//make connectionURLConnection urlc = url.openConnection();
//use GET modeurlc.setDoInput(true);urlc.setAllowUserInteraction(false);
//get resultBufferedReader br = new BufferedReader(new InputStreamReader(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-WSpackage 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 ServiceCreate a myservice directory.
From the directory just above loanservice, run Java’sAnnotation Processing Tool (APT):
C:\>apt -d myservice loanservice/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 ServiceFrom a directory just above myservice:
C:\>java -cp myservice loanservice/LoanApprover
To view the WSDL, visit the service with a browser at http://localhost:8080/loanapprover?wsdl
39
Generate Stub CodeMake a client directory.
C:\>wsimport –p client –keep http://localhost:8080/loanapprover?wsdl
This populates the client subdirectory with .classand .java files.
40
Write the Clientpackage client;
class ApproverClient {
public static void main(String args[]){ LoanApproverService service = new LoanApproverService(); LoanApprover approverProxy = service.getLoanApproverPort(); boolean result = approverProxy.approve("Mike"); if(result) System.out.println("Approved"); else System.out.println("Not approved");
}}
41
Compile & Run the ClientC:\>javac –cp . client/ApproverClient.java
C:\>java -cp . client/ApproverClientApproved