Download return name

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

URL shortening wikipedia , lookup

URL redirection wikipedia , lookup

Transcript
课程名:以服务为中心的软件开发设计与实现
Web Service Implementation,
Deploy and Test
1
Outline
• Web service implementation and deploy
– REST
– JAX-WS
2
Representational State
Transfer (REST)
3
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
4
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
5
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
6
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/{serverid}/{id}_{secret}_[mstb].jpg
7
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)
8
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
9
Process of RESTful involing
Response
(HTML/XML doc)
HTTP GET request
Response
(HTML/XML doc)
HTTP POST
PO
(HTML/XML)
URL to submitted PO
10
URL 1
Parts
List
HTTP response
URL 2
HTTP response
URL 3
HTTP response
Web Server
HTTP GET request
Part
Data
PO
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>
JSON
11
XML
{"menu": { "id": "file", "value": "File",
"popup": {
"menuitem": [
{"value": "New", "onclick": "CreateNewDoc()"},
{"value": "Open", "onclick": "OpenDoc()"},
{"value": "Close", "onclick": "CloseDoc()"}
]
}
}}
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
12
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
–
–
–
–
–
–
–
13
400 Bad Request
404 Not Found
500 Internal Server Error
301 Moved Permanently
403 Forbidden
401 Unauthorized
409 Conflict
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-MethodOverride
14
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
15
Create a REST Web Service
• Jersey
– A RESTful web service framework based on JAXRS standard
– Supported by MyEclipse since ver. 7.0
• How to write a Simple HelloWorld RESTful Web
Service in MyEclipse
16
HelloWorld RESTful Web Service
• Create a Web Service Project
REST (JAXRS)
17
HelloWorld RESTful Web Service
• Configure libraries
Core
JAXB
Client
JSON
ATOM
…
18
HelloWorld RESTful Web Service
• Create resource class
HelloWorldResource
19
HelloWorld RESTful Web Service
• Write your HelloWorldResouce
javax.ws.rs.GET
javax.ws.rs.Produces
20
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";
}
}
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</servletclass>
<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>
21
HelloWorld RESTful Web Service
• Deploy to Tomcat
HelloWorld
22
MyEclipse
Tomcat
HelloWorld RESTful Web Service
• Deploy to Tomcat
Successful
23
HelloWorld RESTful Web Service
• Test
– type in http://localhost:8080/HelloWorld/services/helloworld
Successful
24
Tools in MyEclipse
25
Path Parameter Example
@GET
@Path("/{name}")
@Produces("text/plain")
public String sayHiWithName(@PathParam("name") String name) {
return "Hi, " + name;
}
26
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)
27
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
28
XML vs. JavaObject
@XmlRootElement
public 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;
}
<person>
<address>Tsinghua University</address>
<address>FIT Building</address>
<address>1-308</address>
<id>2010210760</id>
<name>TANG Wenbin</name>
</person>
@XmlElement(name="address")
public List<String> getAddresses() {
return addresses;
}
}
29
Invoke REST Service in Java
//set URL
URL url = new
URL("http://localhost:8080/HelloWorld/services/helloworld/xml");
//make connection
URLConnection urlc = url.openConnection();
//use GET mode
urlc.setDoInput(true);
urlc.setAllowUserInteraction(false);
//get result
BufferedReader br =
new BufferedReader(new InputStreamReader(urlc.getInputStream()));
String l = null;
while ((l=br.readLine())!=null) {
System.out.println(l);
} br.close();
30
Test with REST WS Explorer
31
Test with REST WS Explorer
32
Java API for XML Web Services
(JAX-WS)
33
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
34
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");
}
35
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);
}
}
36
Compile the Web Service
Create a myservice directory.
From the directory just above loanservice, run Java’s
Annotation 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.
37
Publish the Service
From 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
38
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.
39
Write the Client
package 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");
}
}
40
Compile & Run the Client
C:\>javac –cp . client/ApproverClient.java
C:\>java -cp . client/ApproverClient
Approved
41