SlideShare a Scribd company logo
Scott
Leberknight
RESTful
Web Services with
Jersey
"Jersey RESTful Web Services framework is
[an] open source, production quality framework
for developing RESTful Web Services in Java..."
Jersey...
...produces & consumes
RESTful web services
(in Java, mostly pain-free)
...is the JAX-RS reference
implementation
(and extends JAX-RS with
additional features)
JAX-RS?
Java API for RESTful Services
It's about the
Resources,
stupid...
"A JAX-RS resource is an annotated
POJO that provides so-called resource
methods that are able to handle HTTP
requests for URI paths that the resource
is bound to."
@Path("/simple")	
public class SimpleResource {	
!
@GET	
@Produces("text/plain")	
public String get() {	
return "it's quite simple, you see?";	
}	
}
resource class
Root Resources
POJO (plain-old Java object)
Annotated with @Path and/or
method designator (e.g. @GET)
@Path
Specifies the URI at which a
resource is located
URI template capability
(via @PathParam)
URI path template
@Path("/users/{userid}")	
@GET	
@Produces("application/json")	
public User user(@PathParam("userid") String id) {	
return _userRepository.getUser(id);	
}
Method designators
Represent the HTTP method that
resource methods respond to
@GET	
@Produces("text/plain")	
public String get() {	
return "this is it!";	
}
HTTP method designator
@Produces
Specifies the MIME type of
representations that a resource
produces
Media Types
MediaType class contains constants
for common MIME types...
Media Types
MediaType.TEXT_PLAIN	
!
MediaType.APPLICATION_JSON	
!
MediaType.APPLICATION_XML	
!
MediaType.MULTIPART_FORM_DATA	
!
// and more...
@Consumes
Specifies the MIME type of
representations that a resource
can consume
@Consumes
@Path("/users")	
@POST	
@Consumes(MediaType.APPLICATION_JSON)	
public Response create(User user) {	
Long id = _userRepository.create(user);	
URI uri = URIBuilder.fromURI("/users")	
.path(id).build();	
return Response.created(uri).build();	
}
Sub-Resources & Paths
methods annotated with @Path in
root resource classes, or...
methods returning an (annotated)
resource class
@Path("/myapp")	
public class UserResource { // root resource	
@Path("users")	
@GET	
@Produces(MediaType.TEXT_HTML)	
public String getUsersAsHtml() { ... } 	
!
@Path("users.xml")	
@GET	
@Produces(MediaType.APPLICATION_XML)	
public String getUsersAsXml() { ... }	
!
@Path("users.json")	
@GET	
@Produces(MediaType.APPLICATION_JSON)	
public String getUsersAsXml() { ... }	
}
Sub-resource methods
Sub-resource URIs
/myapp/users
/myapp/users.xml
/myapp/users.json
Injection
Use annotations to specify data to
be injected...
Query & form parameters
Headers, cookies, etc.
Security context
...and more
@*Param
QueryParam
HeaderParam
MatrixParam
FormParam
CookieParam
BeanParam
@QueryParam
@Path("query-params")	
@GET	
public String colors (@QueryParam("red") int red,	
@QueryParam("green") int green,	
@QueryParam("blue") int blue) {	
return String.format("RGB(%d,%d,%d)", red, green, blue);	
}
@HeaderParam
@Path("header-params")	
@GET	
public String headers(@HeaderParam("Accept") String accept,	
@HeaderParam("X-Foo") String foo) {	
	
return String.format("Accept: %s, X-Foo: %s",	
accept, foo);	
}
@MatrixParam
@Path("matrix-params")	
@GET	
public String matrixParams(@MatrixParam("red") int red,	
@MatrixParam("green") int green,	
@MatrixParam("blue") int blue) {	
return String.format("RGB(%d,%d,%d)", red, green, blue);	
}
What's a "matrix param"?
http://www.w3.org/DesignIssues/MatrixURIs.html
Also, see Tim-Berners Lee on matrix param
design issues circa 1996...
acme.com/rest/samples/color;red=25;green=78;blue=192
Parameters separate by semi-colons, e.g.
Not widely used, supported (or known)
What if a parameter isn't
supplied???
@DefaultValue
@Path("defaults")	
@GET	
public String defaults(	
@DefaultValue("Orange") @QueryParam("color") String color,
@DefaultValue(MediaType.APPLICATION_JSON)	
@HeaderParam("Accept") String accept) {	
!
return String.format("color: %s, Accept: %s", color, accept);	
}
@FormParam
@Path("form-params")	
@POST	
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)	
public Response formParams(@FormParam("first") String firstName,	
@FormParam("last") String lastName) {	
!
String entity = String.format("%s %s", firstName, lastName);	
return Response.ok(entity).build();	
}
@BeanParam
@Path("bean-params")	
@POST	
public Response beanParams(@BeanParam User user) {	
!
String entity = String.format("User: %s %s",	
user.getFirstName(), user.getLastName());	
return Response.ok(entity).build();	
}
@BeanParam class
public class User {	
!
@QueryParam("first")	
@DefaultValue("John")	
private String _firstName;	
!
@QueryParam("last")	
@DefaultValue("Doe")	
private String _lastName;	
!
public String getFirstName() {	
return _firstName;	
}	
!
public String getLastName() {	
return _lastName;	
}	
}
@Context
Use to obtain information
related to request/response
UriInfo
@Path("context-uri-info/{thing}")	
@GET	
public String uriInfo(@Context UriInfo info) {	
URI baseUri = info.getBaseUri();	
MultivaluedMap<String, String> queryParams = info.getQueryParameters();	
MultivaluedMap<String, String> pathParams = info.getPathParameters();	
!
return String.format("base URI: %s, query params: %s, path params: %s",	
baseUri, queryParams.entrySet(), pathParams.entrySet());	
}
HttpHeaders
@Path("http-headers")	
@GET	
public String httpHeaders(@Context HttpHeaders headers) {	
List<MediaType> acceptableMediaTypes = 	
headers.getAcceptableMediaTypes();	
String xFoo = headers.getHeaderString("X-Foo");	
!
return String.format("acceptableMediaTypes: %s, X-Foo: %s",	
acceptableMediaTypes, xFoo);	
}
Raw form parameters
@Path("raw-form")	
@POST	
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)	
public Response rawForm(MultivaluedMap<String, String> formParams) {	
!
String entity = formParams.entrySet().toString();	
return Response.ok(entity).build();	
}
(Note: don't actually need @Context in above)
Resource Life Cycle
Scopes
Per-Request (default)
new instance created on each request
Per-lookup
new instance created on each lookup
(perhaps within same request)
Singleton
only one instance for entire app
JAX-RS Application
Model
Defines components of a JAX-RS
application, i.e. resources
Application class
Independent of deployment environment
JAX-RS apps provide concrete
implementation class
Simple Application
public class SampleApplication extends Application {	
!
@Override	
public Set<Class<?>> getClasses() {	
Set<Class<?>> classes = new HashSet<>();	
!
classes.add(SampleResource.class);	
classes.add(SimpleResource.class);	
classes.add(UserResource.class);	
!
return classes;	
}	
}
Jersey's implementation of Application
Jersey ResourceConfig
Extend or create programmatically
Provides additional features like
resource classpath scanning
Jersey ResourceConfig
public class SampleJerseyApp extends ResourceConfig {	
!
public SampleJerseyApp() {	
// scan classpath for resources	
packages("com.acme.rest", "com.foo.services");	
!
// register filters	
register(CsrfProtectionFilter.class);	
register(UriConnegFilter.class);	
register(HttpMethodOverrideFilter.class);	
!
// other configuration, etc.	
}	
}
Deployment Options
JavaSE
(e.g. Grizzly, Jetty, Simple, etc.)
Servlet container
(e.g. Tomcat, Jetty)
JavaEE
(e.g. JBoss, etc.)
OSGi
Using Grizzly
HTTP Server
(JavaSE deployment)
public class Server {	
public static final String BASE_URI = "http://localhost:8080/rest/";	
!
public static HttpServer startServer() {	
ResourceConfig config = new ResourceConfig()	
.packages("com.acme.rest")	
.register(CsrfProtectionFilter.class)	
.register(UriConnegFilter.class)	
.register(HttpMethodOverrideFilter.class);	
!
// create a new Grizzly HTTP server rooted at BASE_URI	
return GrizzlyHttpServerFactory	
.createHttpServer(URI.create(BASE_URI), config);	
}	
!
public static void main(String[] args) throws Exception {	
final HttpServer server = startServer();	
System.out.printf("Jersey app started with WADL available at "	
+ "%sapplication.wadlnHit enter to stop it...n", BASE_URI);	
System.in.read();	
server.shutdownNow();	
}	
}
Grizzly Server
Client API
Jersey provides a client API to consume
RESTful services
Written in fluent-style
(method chaining)
Supports URI templates, forms, etc.
Client client = ClientBuilder.newClient();	
WebTarget target = client.target("http://localhost:8080/rest")	
.path("sample/query-params");	
String response = target.queryParam("red", 0)	
.queryParam("green", 113)	
.queryParam("blue", 195)	
.request()	
.get(String.class);
Client API example
Representations
...supports common media types like
JSON, XML, etc.
...implementations provide ways to
convert to/from various media
representations
JAX-RS...
...supplies support out-of-box for XML,
JSON, etc.
...uses MOXy as the default provider for
JSON and XML conversion
Jersey...
@Path("/")	
public class UserResource {	
!
@Path("/users.json") @GET @Produces(MediaType.APPLICATION_JSON)	
public Collection<User> users() {	
return _userRepository.getAllUsers();	
}	
!
@Path("/users/{userid}.json") @GET	
@Produces(MediaType.APPLICATION_JSON)	
public User user(@PathParam("userid") Integer id) {	
return _userRepository.getUser(id);	
}	
!
@Path("/users.json") @POST @Consumes(MediaType.APPLICATION_JSON)	
public Response create(User user) throws Exception {	
Long id = _userRepository.save(user);	
URI uri = UriBuilder.fromUri("users").path(id).build();	
return Response.created(uri).build();	
}	
!
// more resource methods...	
}
Automatic JSON support
Building Responses
@POST	
@Consumes("application/xml")	
public Response post(String content) {	
  URI createdUri = buildUriFor(content);	
  String createdContent = create(content);	
  	
return Response.created(createdUri)	
.entity(Entity.text(createdContent)).build();	
}
& more to explore...
Security
JerseyTest
Asynchronous
API
Filters &
Interceptors
Bean Validation
MVC templates
...and more (see Jersey user guide)
References
https://jersey.java.net
Jersey web site
https://jersey.java.net/documentation/latest/index.html
Jersey user guide (latest)
https://grizzly.java.net/
Project Grizzly web site
https://jersey.java.net/apidocs/latest/jersey/index.html
Jersey API docs
https://jax-rs-spec.java.net
JAX-RS web site
My Info
twitter: sleberknight
www.sleberknight.com/blog
scott dot leberknight at gmail dot com

More Related Content

PDF
Jersey and JAX-RS
PPT
Developing RESTful WebServices using Jersey
PDF
So various polymorphism in Scala
ODP
RestFull Webservices with JAX-RS
PDF
RESTful Web services using JAX-RS
ODP
RESTing with JAX-RS
PDF
Json to hive_schema_generator
PDF
JAX-RS 2.0: RESTful Web Services
Jersey and JAX-RS
Developing RESTful WebServices using Jersey
So various polymorphism in Scala
RestFull Webservices with JAX-RS
RESTful Web services using JAX-RS
RESTing with JAX-RS
Json to hive_schema_generator
JAX-RS 2.0: RESTful Web Services

What's hot (20)

PPT
Introduction to JAX-RS
PDF
Java Web Programming [2/9] : Servlet Basic
PDF
JAX-RS 2.0: New and Noteworthy in RESTful Web services API at JAX London
PPTX
JSON in der Oracle Datenbank
PDF
Introduction to JAX-RS @ SIlicon Valley Code Camp 2010
PDF
Java Web Programming [5/9] : EL, JSTL and Custom Tags
PDF
A JCR View of the World - adaptTo() 2012 Berlin
PPTX
Resthub lyonjug
PDF
Javaone 2010
PPTX
Rest with Java EE 6 , Security , Backbone.js
PDF
CDI, Seam & RESTEasy: You haven't seen REST yet!
PPTX
Restful webservices
PDF
03 form-data
PPT
Jstl Guide
PDF
CQ5 QueryBuilder - .adaptTo(Berlin) 2011
PPT
JSP Standart Tag Lİbrary - JSTL
PPT
Xml parsers
PPTX
jstl ( jsp standard tag library )
PDF
Apache Beam de A à Z
PDF
Introduction to JAX-RS
Java Web Programming [2/9] : Servlet Basic
JAX-RS 2.0: New and Noteworthy in RESTful Web services API at JAX London
JSON in der Oracle Datenbank
Introduction to JAX-RS @ SIlicon Valley Code Camp 2010
Java Web Programming [5/9] : EL, JSTL and Custom Tags
A JCR View of the World - adaptTo() 2012 Berlin
Resthub lyonjug
Javaone 2010
Rest with Java EE 6 , Security , Backbone.js
CDI, Seam & RESTEasy: You haven't seen REST yet!
Restful webservices
03 form-data
Jstl Guide
CQ5 QueryBuilder - .adaptTo(Berlin) 2011
JSP Standart Tag Lİbrary - JSTL
Xml parsers
jstl ( jsp standard tag library )
Apache Beam de A à Z
Ad

Viewers also liked (20)

PDF
AWS Lambda
PDF
Introduction to REST and Jersey
PDF
jps & jvmtop
PDF
Dropwizard
PDF
Apache ZooKeeper
PPTX
Zk meetup talk
PPT
Chapter 18 - Distributed Coordination
PPTX
Jersey framework
PPTX
Survey of restful web services frameworks
ODP
RESTful Web Services
PDF
Polyglot persistence for Java developers: time to move out of the relational ...
ODP
Criando um Web Service Restful com Jersey, Eclipse, JBoss, Tomcat, WebSphere
PPTX
01. http basics v27
PDF
CoffeeScript
PDF
Polyglot Persistence
PDF
Cloudera Impala, updated for v1.0
PDF
De Web Services RESTful a Aplicações Mashup
PDF
wtf is in Java/JDK/wtf7?
AWS Lambda
Introduction to REST and Jersey
jps & jvmtop
Dropwizard
Apache ZooKeeper
Zk meetup talk
Chapter 18 - Distributed Coordination
Jersey framework
Survey of restful web services frameworks
RESTful Web Services
Polyglot persistence for Java developers: time to move out of the relational ...
Criando um Web Service Restful com Jersey, Eclipse, JBoss, Tomcat, WebSphere
01. http basics v27
CoffeeScript
Polyglot Persistence
Cloudera Impala, updated for v1.0
De Web Services RESTful a Aplicações Mashup
wtf is in Java/JDK/wtf7?
Ad

Similar to RESTful Web Services with Jersey (20)

PDF
Eclipse Day India 2015 - Rest with Java (jax rs) and jersey
PDF
Rest with java (jax rs) and jersey and swagger
PDF
Jersey
PPTX
What is new in Java 8
PPT
Using Java to implement RESTful Web Services: JAX-RS
PPTX
Building Restful Web Services with Java
PDF
Java7 New Features and Code Examples
PPTX
Integration patterns in AEM 6
PDF
Functional Thinking - Programming with Lambdas in Java 8
PDF
WhatsNewNIO2.pdf
PDF
Unsafe JAX-RS: Breaking REST API
PDF
REST made simple with Java
ODP
Jax-rs-js Tutorial
PPTX
Overview of RESTful web services
PDF
Spark IT 2011 - Developing RESTful Web services with JAX-RS
PDF
Scala - en bedre Java?
PDF
Cascading Through Hadoop for the Boulder JUG
PDF
Scala - en bedre og mere effektiv Java?
PDF
JAX-RS Creating RESTFul services
PPT
JSR 172: XML Parsing in MIDP
Eclipse Day India 2015 - Rest with Java (jax rs) and jersey
Rest with java (jax rs) and jersey and swagger
Jersey
What is new in Java 8
Using Java to implement RESTful Web Services: JAX-RS
Building Restful Web Services with Java
Java7 New Features and Code Examples
Integration patterns in AEM 6
Functional Thinking - Programming with Lambdas in Java 8
WhatsNewNIO2.pdf
Unsafe JAX-RS: Breaking REST API
REST made simple with Java
Jax-rs-js Tutorial
Overview of RESTful web services
Spark IT 2011 - Developing RESTful Web services with JAX-RS
Scala - en bedre Java?
Cascading Through Hadoop for the Boulder JUG
Scala - en bedre og mere effektiv Java?
JAX-RS Creating RESTFul services
JSR 172: XML Parsing in MIDP

More from Scott Leberknight (12)

PDF
JShell & ki
PDF
JUnit Pioneer
PDF
JDKs 10 to 14 (and beyond)
PDF
Unit Testing
PDF
PDF
PDF
Java 8 Lambda Expressions
PDF
Google Guava
PDF
Cloudera Impala
PDF
HBase Lightning Talk
JShell & ki
JUnit Pioneer
JDKs 10 to 14 (and beyond)
Unit Testing
Java 8 Lambda Expressions
Google Guava
Cloudera Impala
HBase Lightning Talk

Recently uploaded (20)

PDF
Electronic commerce courselecture one. Pdf
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Spectral efficient network and resource selection model in 5G networks
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PPTX
Big Data Technologies - Introduction.pptx
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PPTX
A Presentation on Artificial Intelligence
PDF
Empathic Computing: Creating Shared Understanding
PDF
NewMind AI Monthly Chronicles - July 2025
PPTX
MYSQL Presentation for SQL database connectivity
PDF
KodekX | Application Modernization Development
PDF
Encapsulation theory and applications.pdf
Electronic commerce courselecture one. Pdf
The Rise and Fall of 3GPP – Time for a Sabbatical?
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Advanced methodologies resolving dimensionality complications for autism neur...
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
Diabetes mellitus diagnosis method based random forest with bat algorithm
“AI and Expert System Decision Support & Business Intelligence Systems”
Per capita expenditure prediction using model stacking based on satellite ima...
Spectral efficient network and resource selection model in 5G networks
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Digital-Transformation-Roadmap-for-Companies.pptx
Big Data Technologies - Introduction.pptx
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
A Presentation on Artificial Intelligence
Empathic Computing: Creating Shared Understanding
NewMind AI Monthly Chronicles - July 2025
MYSQL Presentation for SQL database connectivity
KodekX | Application Modernization Development
Encapsulation theory and applications.pdf

RESTful Web Services with Jersey