SlideShare una empresa de Scribd logo
1 de 7
Descargar para leer sin conexión
4/3/2013
1
Implementing RESTful Services
JAX-RS
CS213
03-Apr-2013
JAX-RS Features
• Annotation based
– No need for any configuration in web.xml
– New version of Servlet specification doesn’t
require a web.xml file at all.
• Flexible Deployment Option
– Servlet container
– JAX-RS aware container
• Easy Data Handling Mechanism
4/3/2013
2
Core Annotations
• URL Templates
– @Path
– Defines URI mappings and templates
– Applied on the resource class (most of other annotations are
for methods)
• MIME handling
– @Provides, @Consumes
– What MIME types does the resource produce and consume
• HTTP methods
– @GET, @POST, @PUT, @DELETE
– Identifies which HTTP method the Java method is interested in
Parameter
• @PathParam
– Allows you to extract URI
template segments
– /customers/1234
– /customers/{id}
• @QueryParam
– Access to specific
parameter URI query string
– /customers?city=Lahore
• @MatrixParam
– /customers;city=Lahore
• @FormParam
• @HeaderParam
– Access to a specific HTTP
Header
• @CoockieParam
– Access to a specific cookie
value
• @Context
– Access to contextual
information such as URI or
Request object
• @DefaultValue
4/3/2013
3
Parameter Handling
• HTTP request values are automatically
mapped to
– String and primitive types
– Class types that have a constructor that takes a
String parameter
– Class types that have a static valueOf(String val)
method to prepare an instance of that class
– List , Arrays or Set of above types when there are
multiple values
– Byte array or string for payload (POST or PUT)
Return Types
• Null (Status 204)
– Nothing is returned or a null value is retuned
• WebApplicationException
• An Entity/Object
– Marshaled/serialized to its string representation
• Response
• GenericEntity (embedded in response object)
4/3/2013
4
Poll Service Example
public class PollService {
String getPoll(int id) {
// return some JSON
}
// other methods
}
public class PollService {
String getPoll(int id) {
// return some JSON
}
// other methods
}
Example with JAX-RS Annotations
@Path("/polls")
public class PollService {
@Path("/{poll-id}")
@GET
@Provides("application/json")
String getPoll(@PathParam("poll-id") int id) {
...
}
}
@Path("/polls")
public class PollService {
@Path("/{poll-id}")
@GET
@Provides("application/json")
String getPoll(@PathParam("poll-id") int id) {
...
}
}
Define base URL of this resource
class. All request starting with this
context shall be routed to this class
This method will be
called for all GET type
requests of the form
/polls/12345
Automatically convert
and inject value of
URL segment into id
parameter.
Defines extension to
base URL and path
segment
4/3/2013
5
Example with POST
@Path("/polls")
public class PollService {
...
@POST
@Consumes("application/json")
Response createPoll(String data) {
...
}
}
@Path("/polls")
public class PollService {
...
@POST
@Consumes("application/json")
Response createPoll(String data) {
...
}
}
We will talk about it in
next slide.
Un-annotated parameters
assumed to be incoming
message body. There can
be only one!
What content types are
expected from client?
To be invoked on POST requests,
i.e. CREATE a resource, message
body will contain poll data.
Response Object
• Core Classes in JAX-RS
– Response and ResponseBuilder
• Objective
– Customize response code
– Specify certain response headers
– Specify redirect URLs
– Lot more..
Response createPoll(String data) {
...
ResponseBuilder rb = Response.status(201);
rb.type("application/json")
.header("Location", "/polls/"+id);
return rb.build();
}
Response createPoll(String data) {
...
ResponseBuilder rb = Response.status(201);
rb.type("application/json")
.header("Location", "/polls/"+id);
return rb.build();
}
4/3/2013
6
Default Response Codes
• GET and PUT
– 200 (OK)
• DELETE and POST
– 200 (OK) if content sent back with response
– 204 (NO CONTENT) if no content sent back or a
null is returned.
Example with Query Parameters
• Process requests of the form
– /polls?sort=title
@Path("/polls")
public class PollService {
...
@GET
@Produces({"application/json","application/xml"})
Response listPoll(
@DefaultValue("cdate") @QueryParam("sort") String order) {
...
}
}
@Path("/polls")
public class PollService {
...
@GET
@Produces({"application/json","application/xml"})
Response listPoll(
@DefaultValue("cdate") @QueryParam("sort") String order) {
...
}
}
4/3/2013
7
Frameworks
• JBoss RESTeasy
• Sun Jersey
• CXF
• Axis2
• Spring
That’s All
• JAX-RS Documentation
– http://jersey.java.net/nonav/documentation/snap
shot/index.html
• Java6 Tutorial
– http://docs.oracle.com/javaee/6/tutorial/doc/gijq
y.html

Más contenido relacionado

Destacado (6)

Client sidescripting javascript
Client sidescripting javascriptClient sidescripting javascript
Client sidescripting javascript
 
File handling in c++
File handling in c++File handling in c++
File handling in c++
 
Data file handling
Data file handlingData file handling
Data file handling
 
File handling in C++
File handling in C++File handling in C++
File handling in C++
 
file handling c++
file handling c++file handling c++
file handling c++
 
Study: The Future of VR, AR and Self-Driving Cars
Study: The Future of VR, AR and Self-Driving CarsStudy: The Future of VR, AR and Self-Driving Cars
Study: The Future of VR, AR and Self-Driving Cars
 

Similar a Rest services with Jax-rs

Using Java to implement RESTful Web Services: JAX-RS
Using Java to implement RESTful Web Services: JAX-RSUsing Java to implement RESTful Web Services: JAX-RS
Using Java to implement RESTful Web Services: JAX-RS
Katrien Verbert
 
Building Restful Web Services with Java
Building Restful Web Services with JavaBuilding Restful Web Services with Java
Building Restful Web Services with Java
Vassil Popovski
 
JAX-RS JavaOne Hyderabad, India 2011
JAX-RS JavaOne Hyderabad, India 2011JAX-RS JavaOne Hyderabad, India 2011
JAX-RS JavaOne Hyderabad, India 2011
Shreedhar Ganapathy
 

Similar a Rest services with Jax-rs (20)

CDI, Seam & RESTEasy: You haven't seen REST yet!
CDI, Seam & RESTEasy: You haven't seen REST yet!CDI, Seam & RESTEasy: You haven't seen REST yet!
CDI, Seam & RESTEasy: You haven't seen REST yet!
 
Using Java to implement RESTful Web Services: JAX-RS
Using Java to implement RESTful Web Services: JAX-RSUsing Java to implement RESTful Web Services: JAX-RS
Using Java to implement RESTful Web Services: JAX-RS
 
RESTful Web services using JAX-RS
RESTful Web services using JAX-RSRESTful Web services using JAX-RS
RESTful Web services using JAX-RS
 
Spring MVC Annotations
Spring MVC AnnotationsSpring MVC Annotations
Spring MVC Annotations
 
6 Months Industrial Training in Spring Framework
6 Months Industrial Training in Spring Framework6 Months Industrial Training in Spring Framework
6 Months Industrial Training in Spring Framework
 
Lab swe-2013intro jax-rs
Lab swe-2013intro jax-rsLab swe-2013intro jax-rs
Lab swe-2013intro jax-rs
 
Spark IT 2011 - Developing RESTful Web services with JAX-RS
Spark IT 2011 - Developing RESTful Web services with JAX-RSSpark IT 2011 - Developing RESTful Web services with JAX-RS
Spark IT 2011 - Developing RESTful Web services with JAX-RS
 
S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010
S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010
S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010
 
Jersey
JerseyJersey
Jersey
 
Building Restful Web Services with Java
Building Restful Web Services with JavaBuilding Restful Web Services with Java
Building Restful Web Services with Java
 
JAX-RS Creating RESTFul services
JAX-RS Creating RESTFul servicesJAX-RS Creating RESTFul services
JAX-RS Creating RESTFul services
 
Overview of RESTful web services
Overview of RESTful web servicesOverview of RESTful web services
Overview of RESTful web services
 
RestFull Webservices with JAX-RS
RestFull Webservices with JAX-RSRestFull Webservices with JAX-RS
RestFull Webservices with JAX-RS
 
RESTful Web Services with Jersey
RESTful Web Services with JerseyRESTful Web Services with Jersey
RESTful Web Services with Jersey
 
Advance java session 3
Advance java session 3Advance java session 3
Advance java session 3
 
JSUG - RESTful Web Services by Florian Motlik
JSUG - RESTful Web Services by Florian MotlikJSUG - RESTful Web Services by Florian Motlik
JSUG - RESTful Web Services by Florian Motlik
 
Java colombo-deep-dive-into-jax-rs
Java colombo-deep-dive-into-jax-rsJava colombo-deep-dive-into-jax-rs
Java colombo-deep-dive-into-jax-rs
 
JAX-RS JavaOne Hyderabad, India 2011
JAX-RS JavaOne Hyderabad, India 2011JAX-RS JavaOne Hyderabad, India 2011
JAX-RS JavaOne Hyderabad, India 2011
 
Resource Routing in ExpressionEngine
Resource Routing in ExpressionEngineResource Routing in ExpressionEngine
Resource Routing in ExpressionEngine
 
Course sites new user profile pages
Course sites new user profile pagesCourse sites new user profile pages
Course sites new user profile pages
 

Último

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Último (20)

Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 

Rest services with Jax-rs

  • 1. 4/3/2013 1 Implementing RESTful Services JAX-RS CS213 03-Apr-2013 JAX-RS Features • Annotation based – No need for any configuration in web.xml – New version of Servlet specification doesn’t require a web.xml file at all. • Flexible Deployment Option – Servlet container – JAX-RS aware container • Easy Data Handling Mechanism
  • 2. 4/3/2013 2 Core Annotations • URL Templates – @Path – Defines URI mappings and templates – Applied on the resource class (most of other annotations are for methods) • MIME handling – @Provides, @Consumes – What MIME types does the resource produce and consume • HTTP methods – @GET, @POST, @PUT, @DELETE – Identifies which HTTP method the Java method is interested in Parameter • @PathParam – Allows you to extract URI template segments – /customers/1234 – /customers/{id} • @QueryParam – Access to specific parameter URI query string – /customers?city=Lahore • @MatrixParam – /customers;city=Lahore • @FormParam • @HeaderParam – Access to a specific HTTP Header • @CoockieParam – Access to a specific cookie value • @Context – Access to contextual information such as URI or Request object • @DefaultValue
  • 3. 4/3/2013 3 Parameter Handling • HTTP request values are automatically mapped to – String and primitive types – Class types that have a constructor that takes a String parameter – Class types that have a static valueOf(String val) method to prepare an instance of that class – List , Arrays or Set of above types when there are multiple values – Byte array or string for payload (POST or PUT) Return Types • Null (Status 204) – Nothing is returned or a null value is retuned • WebApplicationException • An Entity/Object – Marshaled/serialized to its string representation • Response • GenericEntity (embedded in response object)
  • 4. 4/3/2013 4 Poll Service Example public class PollService { String getPoll(int id) { // return some JSON } // other methods } public class PollService { String getPoll(int id) { // return some JSON } // other methods } Example with JAX-RS Annotations @Path("/polls") public class PollService { @Path("/{poll-id}") @GET @Provides("application/json") String getPoll(@PathParam("poll-id") int id) { ... } } @Path("/polls") public class PollService { @Path("/{poll-id}") @GET @Provides("application/json") String getPoll(@PathParam("poll-id") int id) { ... } } Define base URL of this resource class. All request starting with this context shall be routed to this class This method will be called for all GET type requests of the form /polls/12345 Automatically convert and inject value of URL segment into id parameter. Defines extension to base URL and path segment
  • 5. 4/3/2013 5 Example with POST @Path("/polls") public class PollService { ... @POST @Consumes("application/json") Response createPoll(String data) { ... } } @Path("/polls") public class PollService { ... @POST @Consumes("application/json") Response createPoll(String data) { ... } } We will talk about it in next slide. Un-annotated parameters assumed to be incoming message body. There can be only one! What content types are expected from client? To be invoked on POST requests, i.e. CREATE a resource, message body will contain poll data. Response Object • Core Classes in JAX-RS – Response and ResponseBuilder • Objective – Customize response code – Specify certain response headers – Specify redirect URLs – Lot more.. Response createPoll(String data) { ... ResponseBuilder rb = Response.status(201); rb.type("application/json") .header("Location", "/polls/"+id); return rb.build(); } Response createPoll(String data) { ... ResponseBuilder rb = Response.status(201); rb.type("application/json") .header("Location", "/polls/"+id); return rb.build(); }
  • 6. 4/3/2013 6 Default Response Codes • GET and PUT – 200 (OK) • DELETE and POST – 200 (OK) if content sent back with response – 204 (NO CONTENT) if no content sent back or a null is returned. Example with Query Parameters • Process requests of the form – /polls?sort=title @Path("/polls") public class PollService { ... @GET @Produces({"application/json","application/xml"}) Response listPoll( @DefaultValue("cdate") @QueryParam("sort") String order) { ... } } @Path("/polls") public class PollService { ... @GET @Produces({"application/json","application/xml"}) Response listPoll( @DefaultValue("cdate") @QueryParam("sort") String order) { ... } }
  • 7. 4/3/2013 7 Frameworks • JBoss RESTeasy • Sun Jersey • CXF • Axis2 • Spring That’s All • JAX-RS Documentation – http://jersey.java.net/nonav/documentation/snap shot/index.html • Java6 Tutorial – http://docs.oracle.com/javaee/6/tutorial/doc/gijq y.html