用JAX-RS和Jersey完成RESTful Web Services

  • View
    9.447

  • Download
    9

Embed Size (px)

DESCRIPTION

1. RESTful Services 2. JAX-RS (JSR-311) Implementation3. JAX-RS Service 4. JAX-RS Client 5. Security 6. Java EE 7 JAX-RS 2.0 (JSR-339) Session NetBeans 7.0 GlassFish 3.1 JerseyJAX-RS 1.1 Server Client JAX-RS 2.0

Transcript

  • 1. .RESTful Services Using JAX-RS and Jersey/Monster Su.

2. .RESTful Services Using. JAX-RS and Jersey monster.supreme@gmail.comhttp://monstersupreme.blogspot.com July 29, 2011 3. . Profile Java XML/Web ServicesDesign PatternsEJB/JPA Java EE Struts/Spring Framework/Hibernate Open Source Framework JBoss ASGlassFish Application Server Apache Hadoop Google App EngineMicrosoft Azure Cloud Platform iOS AndroidWindows Phone 7 Smart Handheld 4. . Outline... 1Introduction ...2Implementation... 3Server-Side API ...4Development Tool... 5Client-Side API ...6Application... 7Concern ...8Future... 9Summary 5. .. . Introduction1... 2 Implementation .. . Server-Side API3... 4 Development Tool... 5 Client-Side API .. . Application6... 7 Concern .. . Future8... 9 Summary 6. . SOAP Amazon Lite BookBookService - save()/delete()/get()/update()http://amazonlite.com/bookService?wsdl DVDDVDService - persist()/remove()/load()/merge()http://amazonlite.com/dvdService?wsdl InvoiceInvoiceService - insert()/cancel()/locate()/replace()http://amazonlite.com/invoiceService?wsdl 7. Service Calling Made Easy - SOAP. http://geekandpoke.typepad.com 8. . SOAP ... 1SOAP ()... 2SOAP Overhead (XML )... 3SOAP ()... 4SOAP ()... 5SOAP ( WS-*)... 6... 7... 8... 9... 10 9. . Take a REST Amazon Lite BookHTTP Method - POST/DELETE/GET/PUThttp://amazonlite.com/books DVDHTTP Method - POST/DELETE/GET/PUThttp://amazonlite.com/dvds InvoiceHTTP Method - POST/DELETE/GET/PUThttp://amazonlite.com/invoices 10. Service Calling Made Easy - REST. http://geekandpoke.typepad.com 11. . Information Web Resource Resource URI CRUD Uniform HTTP Method Protocol HTTP Stateless Scalability 12. . RESTful Services REpresentational State Transfer 2000 Roy Fielding Resource Action URL Web ResourceResource XMLJSONHTMLPDFRaw Data WSDL Interface HTTP Method GETPOSTPUT DELETE Client Server Resource 13. . URL/URI ResourceREST URL Resource http://localhost:8080/helloWorld URL Resource http://localhost:8080/findBookByIsbn?isbn=0596158041RESTfulURL Resource https://graph.facebook.com/monster.supreme URL https://graph.facebook.com/monster.supreme/picture?type=large URL Resource http://api.twitter.com/1/friends/ids.xml?screen_name=MonsterSupreme 14. . HTTP 15. . HTTP Method vs. CRUD ResourceGET ResourcePOST URI Resource URI ResourcePUT URI ResourceDELETE Resource HEAD Body GET Resource OPTIONS Method 16. . WSDL Web Application Description Language WADLW3C Member SubmissionSun Marc Hadley (JAX-RS Lead) http://www.w3.org/Submission/wadl/ HTTP-Based Web Application Machine Process-able DescriptionSOAPWSDLRESTWADL 17. . WADL 1 2 3 5 6 7 8 9 10 12 131415161718 19 20 21 18. REST vs. SOAPRESTful Web Services vs.BigWeb Services. http://www2008.org/papers/pdf/p805-pautassoA.pdfREST vs. SOAP RPC REST REST SOAP REST Architecture StyleREST Service Web Mobile () Web Resource REST QoS SOAP 19. .. . Introduction1... 2 Implementation .. . Server-Side API3... 4 Development Tool... 5 Client-Side API .. . Application6... 7 Concern .. . Future8... 9 Summary 20. Java RESTful Services . J2SE/J2EE 1.4 REST Server Java Servlet API JSPClient java.net URL HttpURLConnection Java API for XML Processing (JAXP) XML Java I/O InputStream OutputStream HTTP Request/Response 21. Java RESTful Services . Java SE/EE 5 REST Server Client JAX-WS 2.0 Service Dispatch Provider Java API for XML Processing (JAXP) XML Java Architecture for XML Binding 2.0(JAXB 2.0) XML Java SOAP REST 22. Java RESTful Services . Java EE 6 REST JSR 311https://jsr311.dev.java.net/ Java API for RESTful Web Services JAX-RS2007 2 2008 10 Java EE 6 javax.ws.rs.* Annotation Java SE 5Jersey JAX-RS 23. Java RESTful Services . Java EE 5 vs. Java EE 6 Java EE 5 (JSR 244)JAX-WS 2.0 (JSR 224)JAXB 2.0 (JSR 222) Java EE 6 (JSR 316)JAX-WS 2.2 (JSR 224 )JAXB 2.2 (JSR 222 )JAX-RS 1.1 (JSR 311) 24. . JAX-RS Noelios Technologies RestletJBoss RESTEasyApache CXFSun/Oracle JerseyApache WinkeXo everRESTTrialox ag Triaxrs 25. JAX-RS Restlet. http://www.restlet.org/ 26. JBoss RESTEasy. http://www.jboss.org/resteasy 27. SOAP REST CXF. http://cxf.apache.org/ 28. JAX-RS Jersey. http://jersey.java.net/ 29. Wink. http://incubator.apache.org/wink/ 30. eXo Platform everREST. http://trialox.org/archives/323 31. OSGi Container Triaxrs. http://code.google.com/p/everrest/ 32. .. . Introduction1... 2 Implementation .. . Server-Side API3... 4 Development Tool... 5 Client-Side API .. . Application6... 7 Concern .. . Future8... 9 Summary 33. . Annotation URI PathParameter @Path @PathParam HTTP Method @QueryParam @POST @HeaderParam @DELETE @FormParam @GET@CookieParam @PUT@MatrixParam @HEAD @DefaultValue @OPTIONS Media Handling Injection @Consumes @Context@Produces 34. . Resource Resource ClassLifecycle Per-Request GCJersey Per-Session @Singleton 1import javax.ws.rs.GET; 2import javax.ws.rs.Produces; 3import javax.ws.rs.Path; 4 5@Path("/helloworld") 6public class HelloWorldResource 7{ 8@GET 9@Produces("text/plain") 10 public String getClichedMessage() 11 { 12 return "Hello World"; 13 } 14 } 35. Resource Class . http://www.devx.com/ 36. . URI Path Template @Path / @Path("users/{username: [a-zA-Z][a-zA-Z_0-9]*}")URI Path Template URI @Path("{bookId}/")public Book getBook(@PathParam("bookId") int bookId) {...}URI Path Template @Path("/books/")public List getBooks(@DefaultValue("5") @QueryParam("max") int max) {...} 37. . Designator HTTP MethodRequest Method Designator @GET@POST@PUT@DELETE@HEAD @OPTIONS Method JAX-RS @HEAD @OPTIONS 1@Stateless 2@Path("series") 3public class SeriesFacadeREST extends AbstractFacade 4{ 5@DELETE 6@Path("{id}") 7public void remove(@PathParam("id") 8Integer id) 9{ 10 super.remove(super.find(id)); 11 } 12 } 38. . Resource @Produces @Consumes MIME Request Header Client Accept: text/plain;q=0.9, text/html 1 @Stateless 2 @Path("series") 3 public class SeriesFacadeREST extends AbstractFacade 4 { 5 @POST 6 @Consumes({"application/xml", "application/json"}) 7 public void create(Series entity) 8 { 9 super.create(entity);10 }11 } 39. . JAXB/Bean Validation JSON 1@Entity 2@Table(name="Series") 3@XmlRootElement 4@NamedQueries({ 5@NamedQuery(name="Series.findAll", query="SELECT s FROM Series s"), 6@NamedQuery(name="Series.findBySeriesId", 7query="SELECT s FROM Series s WHERE s.seriesId = :seriesId")}) 8public class Series implements Serializable 9{ 10 @Id 11 @GeneratedValue(strategy=GenerationType.IDENTITY) 12 @Basic(optional=false) 13 @NotNull 14 @Column(name="seriesId") 15 private Integer seriesId; 16 17 @Basic(optional=false) 18 @NotNull 19 @Size(min=1, max=50) 20 @Column(name="seriesName") 21 private String seriesName; 22 } 40. . JPA Entity Resource 1@Entity 2@Table(name="Series") 3@XmlRootElement 4public class Series implements Serializable 5{ 6@OneToMany(cascade=CascadeType.ALL, mappedBy="series") 7private Collection movieCollection; 8 9@XmlTransient 10 public Collection getMovieCollection() 11 { 12 return movieCollection; 13 } 14 15 public void setMovieCollection(Collection movieCollection) 16 { 17 this.movieCollection = movieCollection; 18 } 19 } 41. . Jersey Front Controller 1 2 3 4ServletAdaptor 5 6com.sun.jersey.spi.container.servlet.ServletContainer 7 81 9 10 11 12 ServletAdaptor 13 /resources/* 14 15 42. .. . Introduction1... 2 Implementation .. . Server-Side API3... 4 Development Tool... 5 Client-Side API .. . Application6... 7 Concern .. . Future8... 9 Summary 43. . CLI ToolcURLWget GUI ToolRESTClientsoapUI Browser ExtensionFirefoxPosterRESTClientChromeSimple REST ClientREST Console Web ClientRESTGate IDE PluginNetBeanssoapUIEclipseHTTP4eJBossToolssoapUI 44. Command-Line Tool. cURLhttp://curl.haxx.se/ 45. Java Application. RESTClienthttp://code.google.com/p/rest-client/ 46. Java Application. soapUIhttp://www.soapui.org/ 47. Firefox Addon. RESTClienthttps://addons.mozilla.org/en-US/firefox/addon/restclient/ 48. Chrome Extension. Simple REST Clienthttps://chrome.google.com/webstore/ 49. Chrome Extension. REST Consolehttp://www.codeinchaos.com/ 50. Web Client. RESTGatehttp://www.thomas-bayer.com/restgate/ 51. Eclipse Plugin. HTTP4ehttp://www.ywebb.com/ 52. Eclipse Plugin. JBossToolshttp://www.jboss.org/tools 53. .. . Introduction1... 2 Implementation .. . Server-Side API3... 4 Development Tool... 5 Client-Side API .. . Application6... 7 Concern .. . Future8... 9 Summary 54. . Client-Side API JAX-RS 1.1 Server-Side Only API Client Programming Language HTTP RESTful Client JAX-RS Client API JAX-RS 2.0 Client API 55. URL + HttpURLConnection. Java SE 1URL url =2new URL("http://localhost/demo/resources/movies/" + movieId);3HttpURLConnection conn = (HttpURLConnection) url.openConnection();4conn.setRequestMethod("GET");5conn.setRequestProperty("Accept", "application/xml");67JAXBContext ctx = JAXBContext.newInstance(Movie.class);8Unmarshaller unmarshaller = ctx.createUnmarshaller();9StreamSource source = new StreamSource(conn.getInputStream());10 JAXBElement element =11 unmarshaller.unmarshal(source, Movie.class);12 Movie movie = element.getValue();1314 conn.disconnect(); 56. Apache HttpClient . http://hc.apache.org/1DefaultHttpClient client = new DefaultHttpClient();2HttpGet get =3new HttpGet("http://localhost/demo/resources/movies/" + movieId);4get.addHeader("Accept", "application/xml");5HttpResponse response = client.execute(get);67if (response.getStatusLine().getStatusCode() == 200)8{9JAXBContext ctx = JAXBContext.newInstance(Movie.class);10 Unmarshaller unmarshaller = ctx.createUnmarshaller();11 StreamSource source =12 new StreamSource(response.getEntity().getContent());13 JAXBElement element =14 unmarshaller.unmarshal(source, Movie.class);15 Movie movie = element.getValue();16 }1718 client.getConnectionManager