SlideShare ist ein Scribd-Unternehmen logo
1 von 17
Downloaden Sie, um offline zu lesen
Hamid Ghorbani (Web Services) https://ir.linkedin.com/in/ghorbanihamid
Web Service
In simple words, services that can be accessed over network are called web services. Web Service is a
client server application, available over the Internet or private (intranet) networks, and can be remotely
invoked using HTTP. Web service is a language independent way of communication.
Types of Web Services:
There are mainly two types of web services.
1. SOAP: SOAP stands for Simple Object Access Protocol. SOAP is an XML based industry standard
protocol for designing and developing web services. Since it’s XML based, it’s platform and
language independent.
2. REST: REST is an architectural style for developing web services. In REST Architecture
everything is a resource. RESTful web services are light weight, highly scalable and maintainable
and are very commonly used to create APIs for web-based applications.
Java Web Services API:
There are two main API's defined by Java for developing web service applications since JavaEE 6.
1) JAX-WS: for SOAP web services. JAX-WS is XML based Java API to build web services server and
client application. There are two ways to write JAX-WS application code: by RPC style and Document
style.
2) JAX-RS: for RESTful web services. JAX-RS uses annotations to simplify the development and
deployment of web services. There are mainly 2 implementations currently in use for creating JAX-RS
application: Jersey and RESTeasy.
Hamid Ghorbani (Web Services) https://ir.linkedin.com/in/ghorbanihamid
SOAP Web Services:
SOAP is an acronym for Simple Object Access Protocol. It is a XML-based protocol for accessing web
services. It is platform independent and language independent. By using SOAP, you will be able to
interact with other programming language applications. In other words, it can be used with Java, .Net
or PHP language on any platform.
WSDL (Web Service Description Language): pronounced as wiz-dull.
WSDL is an xml document that describes the technical details of a web service such as method name,
method parameter and how to access it. In order to communicate between client and server, client must
know some information about the service:
 Address of web Service(Port / Endpoint – URL of the web service)
 Functions available, signature and return types of function.
 Communication protocol
 Input output formats
Service provider will create a standard XML file which will have all above information. So If this file is
given to client then client will be able to access web service. This XML file is called WSDL.
UDDI (Universal Description, Discovery, and Integration):
UDDI is a XML based framework for describing, discovering and integrating web services. This layer is
responsible for centralizing services into a common registry and providing easy publish/find
functionality. It is a directory of web service interfaces described by WSDL, containing information about
web services.
Advantages of Soap Web Services
 WS Security: SOAP defines its own security known as WS Security.
 Language and Platform independent: SOAP web services can be written in any programming
language and executed in any platform.
Disadvantages of Soap Web Services
 Slow: SOAP uses XML format that must be parsed to be read. It defines many standards that
must be followed while developing the SOAP applications. So it is slow and consumes more
bandwidth and resource.
 WSDL dependent: SOAP uses WSDL and doesn't have any other mechanism to discover the
service.
Hamid Ghorbani (Web Services) https://ir.linkedin.com/in/ghorbanihamid
RESTful Web Services:
Web services based on REST (Representational State Transfer) Architecture (not a protocol) are known
as RESTful web services. In REST Architecture everything is a resource. REST is web based architecture
and doesn’t specify any specific protocol to use, but in almost all cases it’s used over HTTP/HTTPS. We
can use XML, JSON, text or any other type of data for request and response. REST Client applications
can use HTTP GET/POST methods to invoke Restful web services. A RESTful web service usually defines
a URI and provides resource representation such as JSON and set of HTTP Methods. Jersey, Restlet,
Apache wink, Spring MVC, Restfulie, and RESTEasy (JBoss ) frameworks implement JAX-RS API,
which is standard specification to create RESTful web services.
Advantages of RESTful Web Services
Fast: RESTful Web Services are fast because there is no strict specification like SOAP. It consumes less
bandwidth and resource.
Permits different data format: RESTful web service permits different data format such as Plain
Text, HTML, XML and JSON.
Stateless: each request from client to server must contain all the information necessary to understand
the request, and cannot take advantage of any stored context on the server.
Cache: to improve network efficiency responses must be capable of being labeled as cacheable or non-
cacheable.
SOAP vs REST Web Services
No. SOAP REST
1 SOAP is a protocol. REST is an architectural style.
2 SOAP uses services interfaces to
expose the business logic.
REST uses URI to expose business logic.
3 SOAP defines standards to be strictly
followed.
REST does not define too much standards like
SOAP.
4 SOAP requires more bandwidth and
resource than REST.
REST requires less bandwidth and resource
than SOAP.
5 SOAP defines its own security. RESTful web services inherits security
measures from the underlying transport.
6 SOAP permits XML data format only. REST permits different data format such as
Plain text, HTML, XML, JSON etc.
Hamid Ghorbani (Web Services) https://ir.linkedin.com/in/ghorbanihamid
REST API Implementation
Java API for RESTful Web Services is JAX-RS. From version 1.1 on, JAX-RS is an official part of Java EE
6. A notable feature of being an official part of Java EE is that no configuration is necessary to start using
JAX-RS. JAX-RS uses annotations, to simplify the development and deployment of web service clients
and endpoints.
JAX-RS provides some annotations to aid in mapping a resource class as a web resource:
 @Path: Used to specify the relative path of class and methods. We can get the URI of a web service
by scanning the Path annotation value. If it exists on both the class and method, the relative path
to the resource method is a concatenation of the class and method.
 @GET, @PUT, @POST, @DELETE and @HEAD: Used to specify the HTTP request type of a
resource.
 @Produces: Specifies the response Internet media types .
 @Consumes: Specifies the accepted request Internet media types.
 @PathParam: Used to bind the method parameter to path value by parsing it. The parameter type
you inject into can be any primitive type, a String, or any Java object that has a constructor that
takes a String parameter, or a static value of method that takes a String as a parameter. For
example, let's say we wanted ISBN to be a real object.
 @QueryParam: binds the method parameter to the value of an URI query string parameter.
 @HeaderParam: Used to bind the method parameter to an HTTP header value.
 @CookieParam: Used to bind the method parameter to a cookie value.
 @FormParam: Used to bind the method parameter to a form value.
 @DefaultValue: Specifies a default value for the above bindings when the key is not found.
 @Context: Returns the entire context of the object.
There are some implementations of JAX-RS API.
1. Jersey: Jersey is the reference implementation provided by Sun. For using Jersey as our JAX-RS
implementation, all we need to configure its servlet in web.xml and add required dependencies.
Note that JAX-RS API is part of JDK not Jersey, so we have to add its dependency jars in our
application.
2. RESTEasy: RESTEasy is the JBoss project that provides JAX-RS implementation.
3. Spring MVC: from spring.
4. Apache CXF: Apache CXF is an open source Web service framework.
Hamid Ghorbani (Web Services) https://ir.linkedin.com/in/ghorbanihamid
Response Class:
Sometimes the web service you are writing can’t be implemented using the default request/response
behavior inherent in JAX-RS. For the cases in which you need to explicitly control the response sent
back to the client, your JAX-RS resource methods can return instances of javax.ws.rs.core.Response:
public abstract class Response {
public static ResponseBuilder status(Status status) {...}
public static ResponseBuilder status(int status) {...}
public static ResponseBuilder ok() {...}
public static ResponseBuilder ok(Object entity) {...}
public static ResponseBuilder serverError() {...}
public static ResponseBuilder created(URI location) {...}
public static ResponseBuilder noContent() {...}
public static ResponseBuilder notModified() {...}
public static ResponseBuilder notModified(EntityTag tag) {...}
public static ResponseBuilder notModified(String tag) {...}
public static ResponseBuilder seeOther(URI location) {...}
public static ResponseBuilder temporaryRedirect(URI location) {...}
public static ResponseBuilder notAcceptable(List<Variant> variants) {...}
public static ResponseBuilder fromResponse(Response response) {...}
}
The JAX-RS specification provides a Java enum called javax.ws.rs.core.Response.Status:
public enum Status {
OK(200, "OK"),
CREATED(201, "Created"),
ACCEPTED(202, "Accepted"),
NO_CONTENT(204, "No Content"),
MOVED_PERMANENTLY(301, "Moved Permanently"),
SEE_OTHER(303, "See Other"),
NOT_MODIFIED(304, "Not Modified"),
TEMPORARY_REDIRECT(307, "Temporary Redirect"),
BAD_REQUEST(400, "Bad Request"),
UNAUTHORIZED(401, "Unauthorized"),
FORBIDDEN(403, "Forbidden"),
NOT_FOUND(404, "Not Found"),
NOT_ACCEPTABLE(406, "Not Acceptable"),
CONFLICT(409, "Conflict"),
GONE(410, "Gone"),
PRECONDITION_FAILED(412, "Precondition Failed"),
UNSUPPORTED_MEDIA_TYPE(415, "Unsupported Media Type"),
INTERNAL_SERVER_ERROR(500, "Internal Server Error"),
SERVICE_UNAVAILABLE(503, "Service Unavailable");
}
Hamid Ghorbani (Web Services) https://ir.linkedin.com/in/ghorbanihamid
Response objects cannot be created directly; instead, they are created from ResponseBuilder instances
returned by one of the static helper methods of Response. The ResponseBuilder class is a factory that is
used to create one individual Response instance:
public static abstract class ResponseBuilder {
public abstract Response build();
public abstract ResponseBuilder clone();
public abstract ResponseBuilder status(int status);
public ResponseBuilder status(Status status) {...}
public abstract ResponseBuilder entity(Object entity);
public abstract ResponseBuilder type(MediaType type);
public abstract ResponseBuilder type(String type);
public abstract ResponseBuilder variant(Variant variant);
public abstract ResponseBuilder variants(List<Variant> variants);
public abstract ResponseBuilder language(String language);
public abstract ResponseBuilder language(Locale language);
public abstract ResponseBuilder location(URI location);
public abstract ResponseBuilder contentLocation(URI location);
public abstract ResponseBuilder tag(EntityTag tag);
public abstract ResponseBuilder tag(String tag);
public abstract ResponseBuilder lastModified(Date lastModified);
public abstract ResponseBuilder cacheControl(CacheControl cacheControl);
public abstract ResponseBuilder expires(Date expires);
public abstract ResponseBuilder header(String name, Object value);
public abstract ResponseBuilder cookie(NewCookie... cookies);
}
Example:
@Produces("text/plain")
public Response getBook() {
String book = ...;
ResponseBuilder resBuilder = Response.ok(book);
resBuilder.language("fa").header("Some-Header", "some value");
return builder.build();
}
Hamid Ghorbani (Web Services) https://ir.linkedin.com/in/ghorbanihamid
Building a REST Services with Jersey and JSON:
1) Create a standard Maven web project structure.
2) Add jersey-server and jersey-json Maven dependencies to pom.xml:
<dependency>
<groupId> com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>${jerseyServer.version}</version>
</dependency>
<dependency>
<groupId> com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
<version>${jerseyJson.version}</version>
</dependency>
3) Register Jersey as the servlet dispatcher for REST requests and put your Jersey service folder under
“init-param“with param name “com.sun.jersey.config.property.packages“. in your web.xml:
<servlet>
<servlet-name>jersey-serlvet</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>myJerseyServiceFolder</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey-serlvet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
4) Integrate JSON with Jersey: Declare “com.sun.jersey.api.json.POJOMappingFeature” as
Hamid Ghorbani (Web Services) https://ir.linkedin.com/in/ghorbanihamid
“init-param” in web.xml. It will make Jersey support JSON/object mapping:
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
Web.xml file after adding the above parameter:
<servlet>
<servlet-name>jersey-serlvet</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>myJerseyServiceFolder</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey-serlvet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
5) Create Model class for Customer Object:
public class Customers implements Serializable{
private int customerId;
private String customerName;
.
.
.
//. . .Getter and setter and toString() methods
}
Hamid Ghorbani (Web Services) https://ir.linkedin.com/in/ghorbanihamid
6) Create Rest Service Class, The @Path annotation placed on the CustomerService class designates the
class as a JAX-RS service. Java classes that you want to be recognized as JAX-RS services must have
this annotation. Also notice that the @Path annotation has the value of /customers. This value
represents the relative root URI of our customer service. If the absolute base URI of our server
is http://localhost:8080, methods exposed by our CustomerResource class would be available
under http://localhost:8080/customers:
@Path("/customers")
public class CustomersService {
CustomerDAO customerDAO;
@POST
@Path("/createCustomer")
@Consumes(MediaType.APPLICATION_JSON)
public Response createCustomer(Customer customer) {
customerDAO.create(customer);
System.out.println("Customer Info Saved: " + customer.toString());
return Response.created(URI.create("/customers/customerInfo/"
+ customer.getId())).build();
}
@GET
@Path("/customerInfo/{customerId}")
@Produces(MediaType.APPLICATION_JSON)
public Response getCustomer(@PathParam("customerId") int customerId) {
Customer customerInfo = customerDAO.get(customerId);
if (customerInfo == null) {
System.out.println("No Customer found for ID " + customerId);
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
return Response.status(Response.Status.OK).entity(customerInfo).build();
}
@PUT
@Path("/updateCustomer")
@Produces(MediaType.APPLICATION_JSON)
public void updateCustomer(@PathParam("customerId")int customerId, Customer customer) {
boolean result = customersDAO.updateCustomer(customerId, customer);
if (!result)
throw new WebApplicationException(Response.Status.NOT_FOUND);
return customersList;
}
}
Hamid Ghorbani (Web Services) https://ir.linkedin.com/in/ghorbanihamid
createCustomer() method:
An HTTP POST request sends an JSON object representing the customer we want to create.
The createCustomer() method receives the request, creates a Customer object, and adds it to
our database. To bind HTTP POST requests to the createCustomer() method, we annotate it with
the @POST annotation. The @Path annotation we put on the CustomerService class, combined with
this @POST annotation, binds all POST requests going to the relative URI /customers to the Java
method createCustomer().
The @Consumes annotation applied to createCustomer() specifies which media type the method is
expecting in the message body of the HTTP input request. If the client POSTs a media type other
than XML, an error code is sent back to the client.
The static Response.created() method creates a Response object that contains an HTTP status code of
201, “Created.” It also adds a Location header to the HTTP response with the value of something
like http://localhost:8080/customers/customerInfo/333, depending on the base URI of the server
and the generated ID of the Customer object (333 is an example).
getCustomer() method:
The getCustomer() method annotated with the @GET annotation to bind HTTP GET operations to
this Java method. getCustomer() also annotated with the @Produces annotation. This annotation
tells JAX-RS which HTTP Content-Type the GET response will be.
If the customer does not exist, method throws the javax.ws.rs.WebApplicationException. This
exception will set the HTTP response code to 404, “Not Found,” meaning that the customer info
does not exist.
updateCustomer() method:
We annotate the updateCustomer() method with @PUT to bind HTTP PUT requests to this method.
If customer doesn’t exist, we throw a WebApplicationException that will send a 404, “Not Found,”
response code back to the client. If the Customer object does exist, we update our
existing Customer object with new updated values.
Exception Handling:
Errors can be reported to a client either by creating and returning the appropriate Response object
or by throwing an exception. JAX-RS provides the javax.ws.rs.WebApplicationException. This can
be thrown by application code and automatically processed by JAX-RS without having to write an
explicit mapper.
Example : throw new WebApplicationException(Response.Status.NOT_FOUND);
Hamid Ghorbani (Web Services) https://ir.linkedin.com/in/ghorbanihamid
Client Application for jersey web service:
If you need to interact with a remote RESTful service, you can use the JAX-RS 2.0 Client API.
The Client interface is responsible for managing client HTTP connections.
public class TestRestService {
public static void main(String[] args) {
// create a customer
Customer customer = new Customer("1", "Hubert",. . .);
Client client = ClientBuilder.newClient(config);
WebTarget service = client.target("http://localhost:8080/customers");
Response response = service.path("createcustomer")
.request().post(Entity.json(customer));
// Return code should be 201 == created resource
if (response.getStatus() != (Response.Status.CREATED)
throw new RuntimeException("Failed to create");
System.out.println(response.getStatus());
// Get the customer
String customer = service.path("customerInfo/1")
.request().accept(MediaType.APPLICATION_JSON)
.get(String.class);
System.out.println(customer);
}
Hamid Ghorbani (Web Services) https://ir.linkedin.com/in/ghorbanihamid
Spring MVC Framework and REST:
The new approach in Spring 3, based on annotations and HttpMessageConverter, simplifies the process of
creating RESTful web services. It is much more lightweight and easy to implement. The following are the list of
spring annotations forimplementing RESTfull services:
 @Configuration: Annotating a class with the @Configuration indicates that the class can be used by
the Spring IoC container as a source of bean definitions.
 @EnableWebMvc: This annotation is used for enabling Spring MVC in an application and works
by importing the Spring MVC Configuration from WebMvcConfigurationSupport.
 @ComponentScan: Spring needs to know the packages to scan for annotated components. We can
use @ComponentScan annotation to specify the base packages to scan. Any class which is annotated
with @Component will be scanned.
 @RestController: @RestController annotation is the special version of @Controller and
@ResponseBody annotations rolled together for implementing the RESTful Web Services.
@RestController has been added as part of the Spring 4 release.
 @RequestMapping: @RequestMapping annotation is used for mapping web requests to a specific
handler classes and/or handler methods.
Note: Since Spring MVC 4.3, you can use new annotations @GetMapping, @PostMapping,
@PutMapping and @DeleteMapping instead of standard @RequestMapping. These annotations are
standard way of defining REST endpoints. They act as wrapper to @RequestMapping:
@GetMapping = @RequestMapping(method = RequestMethod.GET).
 @RequestParam: @RequestParam is annotated in the methods to bind the method parameters
to the request parameters. If the request is submitted by the browser, request parameters are passed
through the URL query parameters. That can be easily mapped to the methods by annotating the
method parameters with @RequestParam.
 @ResponseBody: @ResponseBody binds a method's return value to the web response body. It uses
HTTP Message converters to convert the return value to HTTP response body, based on the content-
type in the request HTTP header. When you use the @ResponseBody annotation on a method,
Spring converts the return value and writes it to the http response automatically.
Hamid Ghorbani (Web Services) https://ir.linkedin.com/in/ghorbanihamid
Building a REST Services with Spring:
1) Create a new spring MVC web project. Project's Spring dependencies are:
<!—Spring Dependencies -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springframework.version}</version>
</dependency>
2) Add Jackson Maven dependency to pom.xml. Jackson API is a Java library for processing JSON.
Using Jackson API we can convert Objects to JSON and vice versa:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jaksonCore.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jaksonCore.version}</version>
</dependency>
3) Set Servlet 3 Java Configuration:
Since version 3.1, Spring supports using Servlet 3 API, so you can omit web.xml and Create
AppInitializer class under config package:
public class AppInitializer extends
AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class[] getRootConfigClasses() {
return new Class[] { AppConfig.class };
}
@Override
protected Class[] getServletConfigClasses() {
return null;
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
Hamid Ghorbani (Web Services) https://ir.linkedin.com/in/ghorbanihamid
4) Set Spring configuration:
Starting from Spring 2.5 it became possible to configure the been dependency injection
using annotations. So instead of using XML to describe a bean wiring, we can now use annotations to
configure the bean wiring. Annotation injection is performed before XML injection. This means if a
bean wiring is configured both with annotations and XML, the XML will override the annotation
configuration.
Create AppConfig.java file under /src/config folder like below:
@Configuration
@EnableWebMvc
@ComponentScan
public class AppConfig {
}
5) Create Model class:
Customer Class as an example:
@Entity
public class Customer implements Serializable{
private int customerId;
private String customerName;
.
.
.
//..Getter and setter methods
}
7) Create Controller Class:
This class is annotated with @RestController annotation, So @ResponseBody annotation is not
necessary on top of each method.
The createCustomer() method parameter is annotated with @RequestBody, this annotation is used to
map the request body JSON data into the Customer object.
The @RequestMapping annotation placed on the CustomerRestController class has the value
of /customers. This value represents the relative root URI of our customer rest service. If the base
URI of our server is http://localhost:8080, methods exposed by our CustomerRestController class
would be available under http://localhost:8080/customers.
Example:
createCustomer() method : http://localhost:8080/customers/createCustomer.
getCustomer() method : http://localhost:8080/customers/getCustomer/1 .
// suppose 1 is Customer Id
Hamid Ghorbani (Web Services) https://ir.linkedin.com/in/ghorbanihamid
@RestController
@RequestMapping("/customers")
public class CustomersRestController {
@RequestMapping(value = "/createCustomer", method = RequestMethod.POST)
public ResponseEntity createCustomer(@RequestBody Customer customer) {
customerDAO.create(customer);
return new ResponseEntity(customer, HttpStatus.OK);
}
@RequestMapping("/getCustomer/{customerId}", method = RequestMethod.GET)
public ResponseEntity<Customer> getCustomer(@PathVariable("customerId") int customerId) {
Customer customerInfo = customerDAO.get(customerId);
if (customerInfo == null) {
return new ResponseEntity("No Customer found for ID " + customerId,
HttpStatus.NOT_FOUND);
}
return new ResponseEntity(customerInfo, HttpStatus.OK);
}
@RequestMapping(value = "/updateCustomer", method = RequestMethod.PUT)
public ResponseEntity<Customer> updateCustomer(@PathVariable("customerId") int customerId,
@RequestBody Customer customer) {
if (customer == null) {
System.out.println("Customer with id " + customerId + " not found");
return new ResponseEntity<Customer>(HttpStatus.NOT_FOUND);
}
customerDAO.updateCustomer(customer);
return new ResponseEntity(customer, HttpStatus.OK);
}
@RequestMapping(value = "/customersList",method = RequestMethod.GET,
produces = "application/json")
public ResponseEntity<List<Customer>> getCustomersList() {
List<Customer> customersList = customersDAO.getCustomersList();
return new ResponseEntity<List<Customer>>(customersList, HttpStatus.OK);
}
}
ResponseEntity: ResponseEntity extends HttpEntity and adds additional information of HTTP method
and uri to the request. ResponseEntity generates response with a given status code and its body.
Hamid Ghorbani (Web Services) https://ir.linkedin.com/in/ghorbanihamid
Client Application for Rest Web service:
If you need to call remote REST services from your application, you can use Apache's HttpClient popular library,
but the details to access REST services using this are too low level. Instead you can use Spring Framework’s
RestTemplate class. RestTemplate provides higher level methods that correspond to each of the six main HTTP
methods. HTTP Methods and corresponding RestTemplate methods:
 HTTP GET : getForObject, getForEntity
 HTTP PUT : put(String url, Object request, String…urlVariables)
 HTTP DELETE : delete
 HTTP POST : postForLocation(String url, Object request, String… urlVariables), postForObject(String url,
Object request, Class responseType, String… uriVariables)
 HTTP HEAD : headForHeaders(String url, String… urlVariables)
 HTTP OPTIONS : optionsForAllow(String url, String… urlVariables)
 HTTP PATCH and others : exchange execute
Example:
public class SpringRestTestClient {
public static final String REST_SERVICE_URI = "http://localhost:8080/SpringRestService";
public static void main(String args[]){
RestTemplate restTemplate = new RestTemplate();
// Get customer
Customer customer = restTemplate.getForObject(REST_SERVICE_URI+"/getCustomer/1",
Customer.class);
// Get All Customers
List<Customer> customersList = restTemplate.getForObject(REST_SERVICE_URI +
"/customersList/", List.class);
Customer customer = new Customer(0,"Hubert",. . .);
// create customer
URI uri = restTemplate.postForLocation(REST_SERVICE_URI + "/createCustomer/", Customer,
Customer.class);
// update customer
restTemplate.put(REST_SERVICE_URI+"/Customer/1", customer);
// delete customer
restTemplate.delete(REST_SERVICE_URI+"/Customer/1");
}
}
Hamid Ghorbani (Web Services) https://ir.linkedin.com/in/ghorbanihamid
Resources:
https://en.wikipedia.org/wiki/Java_API_for_RESTful_Web_Services
https://www.javatpoint.com/java-web-services-tutorial
h ps://www.journaldev.com/9191/java-web-services-tutorial
http://javabeat.net/spring-annotations/
http://www.baeldung.com/spring-enable-annotations
h p://docs.jboss.org/resteasy/docs/2.0.0.GA/Customerguide/html_single/index.html#_PathParam
http://www.vogella.com/tutorials/REST/article.html
https://dennis-xlc.gitbooks.io/restful-java-with-jax-rs-2-0-2rd-edition/en/index.html
https://jersey.github.io/documentation/latest/index.html
http://websystique.com/springmvc/spring-mvc-4-restful-web-services-crud-example-resttemplate/

Weitere ähnliche Inhalte

Was ist angesagt?

Spring Portlet MVC
Spring Portlet MVCSpring Portlet MVC
Spring Portlet MVCJohn Lewis
 
Boston 2011 OTN Developer Days - Java EE 6
Boston 2011 OTN Developer Days - Java EE 6Boston 2011 OTN Developer Days - Java EE 6
Boston 2011 OTN Developer Days - Java EE 6Arun Gupta
 
Spring Framework
Spring Framework  Spring Framework
Spring Framework tola99
 
Spring framework in depth
Spring framework in depthSpring framework in depth
Spring framework in depthVinay Kumar
 
Spring framework
Spring frameworkSpring framework
Spring frameworkvietduc17
 
Spring Framework
Spring FrameworkSpring Framework
Spring Frameworknomykk
 
Spring 3.x - Spring MVC - Advanced topics
Spring 3.x - Spring MVC - Advanced topicsSpring 3.x - Spring MVC - Advanced topics
Spring 3.x - Spring MVC - Advanced topicsGuy Nir
 
Spring MVC
Spring MVCSpring MVC
Spring MVCyuvalb
 
Java for Mainframers
Java for MainframersJava for Mainframers
Java for MainframersRich Helton
 
Ruby On Rails Seminar Basis Softexpo Feb2010
Ruby On Rails Seminar Basis Softexpo Feb2010Ruby On Rails Seminar Basis Softexpo Feb2010
Ruby On Rails Seminar Basis Softexpo Feb2010arif44
 

Was ist angesagt? (20)

Spring Portlet MVC
Spring Portlet MVCSpring Portlet MVC
Spring Portlet MVC
 
Struts N E W
Struts N E WStruts N E W
Struts N E W
 
Maven
MavenMaven
Maven
 
Boston 2011 OTN Developer Days - Java EE 6
Boston 2011 OTN Developer Days - Java EE 6Boston 2011 OTN Developer Days - Java EE 6
Boston 2011 OTN Developer Days - Java EE 6
 
Spring Framework Rohit
Spring Framework RohitSpring Framework Rohit
Spring Framework Rohit
 
Spring Framework
Spring Framework  Spring Framework
Spring Framework
 
Spring Web MVC
Spring Web MVCSpring Web MVC
Spring Web MVC
 
Spring MVC
Spring MVCSpring MVC
Spring MVC
 
Spring Framework
Spring FrameworkSpring Framework
Spring Framework
 
Spring framework in depth
Spring framework in depthSpring framework in depth
Spring framework in depth
 
Spring framework
Spring frameworkSpring framework
Spring framework
 
Spring Framework
Spring FrameworkSpring Framework
Spring Framework
 
Spring 3.x - Spring MVC - Advanced topics
Spring 3.x - Spring MVC - Advanced topicsSpring 3.x - Spring MVC - Advanced topics
Spring 3.x - Spring MVC - Advanced topics
 
Java spring ppt
Java spring pptJava spring ppt
Java spring ppt
 
Spring jdbc
Spring jdbcSpring jdbc
Spring jdbc
 
Spring MVC
Spring MVCSpring MVC
Spring MVC
 
Java for Mainframers
Java for MainframersJava for Mainframers
Java for Mainframers
 
Spring User Guide
Spring User GuideSpring User Guide
Spring User Guide
 
Ruby On Rails Seminar Basis Softexpo Feb2010
Ruby On Rails Seminar Basis Softexpo Feb2010Ruby On Rails Seminar Basis Softexpo Feb2010
Ruby On Rails Seminar Basis Softexpo Feb2010
 
Jsf2.0 -4
Jsf2.0 -4Jsf2.0 -4
Jsf2.0 -4
 

Ähnlich wie Rest web service

Restful web services by Sreeni Inturi
Restful web services by Sreeni InturiRestful web services by Sreeni Inturi
Restful web services by Sreeni InturiSreeni I
 
Day1 : web service basics
Day1 :  web service basics Day1 :  web service basics
Day1 : web service basics Testing World
 
Secc tutorials development and deployment of rest web services in java_v2.0
Secc tutorials development and deployment of rest web services in java_v2.0Secc tutorials development and deployment of rest web services in java_v2.0
Secc tutorials development and deployment of rest web services in java_v2.0Aravindharamanan S
 
Web services for developer
Web services for developerWeb services for developer
Web services for developerRafiq Ahmed
 
Phalcon 2 High Performance APIs - DevWeekPOA 2015
Phalcon 2 High Performance APIs - DevWeekPOA 2015Phalcon 2 High Performance APIs - DevWeekPOA 2015
Phalcon 2 High Performance APIs - DevWeekPOA 2015Jackson F. de A. Mafra
 
Creating Web Services with Zend Framework - Matthew Turland
Creating Web Services with Zend Framework - Matthew TurlandCreating Web Services with Zend Framework - Matthew Turland
Creating Web Services with Zend Framework - Matthew TurlandMatthew Turland
 
What are restful web services?
What are restful web services?What are restful web services?
What are restful web services?Aparna Sharma
 
Xml web services
Xml web servicesXml web services
Xml web servicesRaghu nath
 
REST Introduction.ppt
REST Introduction.pptREST Introduction.ppt
REST Introduction.pptKGSCSEPSGCT
 
Introduction to webservices
Introduction to webservicesIntroduction to webservices
Introduction to webservicesGagandeep Singh
 
IRJET- Rest API for E-Commerce Site
IRJET- Rest API for E-Commerce SiteIRJET- Rest API for E-Commerce Site
IRJET- Rest API for E-Commerce SiteIRJET Journal
 

Ähnlich wie Rest web service (20)

Restful web services by Sreeni Inturi
Restful web services by Sreeni InturiRestful web services by Sreeni Inturi
Restful web services by Sreeni Inturi
 
Day1 : web service basics
Day1 :  web service basics Day1 :  web service basics
Day1 : web service basics
 
Web Programming
Web ProgrammingWeb Programming
Web Programming
 
Salesforce Integration
Salesforce IntegrationSalesforce Integration
Salesforce Integration
 
Secc tutorials development and deployment of rest web services in java_v2.0
Secc tutorials development and deployment of rest web services in java_v2.0Secc tutorials development and deployment of rest web services in java_v2.0
Secc tutorials development and deployment of rest web services in java_v2.0
 
Web services for developer
Web services for developerWeb services for developer
Web services for developer
 
WIT UNIT-5.pdf
WIT UNIT-5.pdfWIT UNIT-5.pdf
WIT UNIT-5.pdf
 
Phalcon 2 High Performance APIs - DevWeekPOA 2015
Phalcon 2 High Performance APIs - DevWeekPOA 2015Phalcon 2 High Performance APIs - DevWeekPOA 2015
Phalcon 2 High Performance APIs - DevWeekPOA 2015
 
Apitesting.pptx
Apitesting.pptxApitesting.pptx
Apitesting.pptx
 
Creating Web Services with Zend Framework - Matthew Turland
Creating Web Services with Zend Framework - Matthew TurlandCreating Web Services with Zend Framework - Matthew Turland
Creating Web Services with Zend Framework - Matthew Turland
 
Rest api-interview
Rest api-interviewRest api-interview
Rest api-interview
 
What are restful web services?
What are restful web services?What are restful web services?
What are restful web services?
 
Xml web services
Xml web servicesXml web services
Xml web services
 
Unit 2
Unit 2Unit 2
Unit 2
 
REST Introduction.ppt
REST Introduction.pptREST Introduction.ppt
REST Introduction.ppt
 
Introduction to webservices
Introduction to webservicesIntroduction to webservices
Introduction to webservices
 
SCDJWS 6. REST JAX-P
SCDJWS 6. REST  JAX-PSCDJWS 6. REST  JAX-P
SCDJWS 6. REST JAX-P
 
IRJET- Rest API for E-Commerce Site
IRJET- Rest API for E-Commerce SiteIRJET- Rest API for E-Commerce Site
IRJET- Rest API for E-Commerce Site
 
REST & RESTful Web Services
REST & RESTful Web ServicesREST & RESTful Web Services
REST & RESTful Web Services
 
Web services
Web servicesWeb services
Web services
 

Mehr von Hamid Ghorbani

Mehr von Hamid Ghorbani (12)

Payment Tokenization
Payment TokenizationPayment Tokenization
Payment Tokenization
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 
Java Threads
Java ThreadsJava Threads
Java Threads
 
Java Reflection
Java ReflectionJava Reflection
Java Reflection
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Java collections
Java collectionsJava collections
Java collections
 
Java programming basics
Java programming basicsJava programming basics
Java programming basics
 
IBM Integeration Bus(IIB) Fundamentals
IBM Integeration Bus(IIB) FundamentalsIBM Integeration Bus(IIB) Fundamentals
IBM Integeration Bus(IIB) Fundamentals
 
ESB Overview
ESB OverviewESB Overview
ESB Overview
 
Spring security configuration
Spring security configurationSpring security configuration
Spring security configuration
 
SOA & ESB in banking systems(Persian language)
SOA & ESB in banking systems(Persian language)SOA & ESB in banking systems(Persian language)
SOA & ESB in banking systems(Persian language)
 

Kürzlich hochgeladen

Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringHironori Washizaki
 
Keeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldKeeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldRoberto Pérez Alcolea
 
Osi security architecture in network.pptx
Osi security architecture in network.pptxOsi security architecture in network.pptx
Osi security architecture in network.pptxVinzoCenzo
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsSafe Software
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecturerahul_net
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxRTS corp
 
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdfAndrey Devyatkin
 
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsJean Silva
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Rob Geurden
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLionel Briand
 
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfEnhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfRTS corp
 
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesAmazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesKrzysztofKkol1
 
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...OnePlan Solutions
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonLeveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonApplitools
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identityteam-WIBU
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?Alexandre Beguel
 

Kürzlich hochgeladen (20)

Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their Engineering
 
Keeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldKeeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository world
 
Osi security architecture in network.pptx
Osi security architecture in network.pptxOsi security architecture in network.pptx
Osi security architecture in network.pptx
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data Streams
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecture
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
 
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
 
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero results
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and Repair
 
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfEnhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
 
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesAmazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
 
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonLeveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identity
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?
 

Rest web service

  • 1. Hamid Ghorbani (Web Services) https://ir.linkedin.com/in/ghorbanihamid Web Service In simple words, services that can be accessed over network are called web services. Web Service is a client server application, available over the Internet or private (intranet) networks, and can be remotely invoked using HTTP. Web service is a language independent way of communication. Types of Web Services: There are mainly two types of web services. 1. SOAP: SOAP stands for Simple Object Access Protocol. SOAP is an XML based industry standard protocol for designing and developing web services. Since it’s XML based, it’s platform and language independent. 2. REST: REST is an architectural style for developing web services. In REST Architecture everything is a resource. RESTful web services are light weight, highly scalable and maintainable and are very commonly used to create APIs for web-based applications. Java Web Services API: There are two main API's defined by Java for developing web service applications since JavaEE 6. 1) JAX-WS: for SOAP web services. JAX-WS is XML based Java API to build web services server and client application. There are two ways to write JAX-WS application code: by RPC style and Document style. 2) JAX-RS: for RESTful web services. JAX-RS uses annotations to simplify the development and deployment of web services. There are mainly 2 implementations currently in use for creating JAX-RS application: Jersey and RESTeasy.
  • 2. Hamid Ghorbani (Web Services) https://ir.linkedin.com/in/ghorbanihamid SOAP Web Services: SOAP is an acronym for Simple Object Access Protocol. It is a XML-based protocol for accessing web services. It is platform independent and language independent. By using SOAP, you will be able to interact with other programming language applications. In other words, it can be used with Java, .Net or PHP language on any platform. WSDL (Web Service Description Language): pronounced as wiz-dull. WSDL is an xml document that describes the technical details of a web service such as method name, method parameter and how to access it. In order to communicate between client and server, client must know some information about the service:  Address of web Service(Port / Endpoint – URL of the web service)  Functions available, signature and return types of function.  Communication protocol  Input output formats Service provider will create a standard XML file which will have all above information. So If this file is given to client then client will be able to access web service. This XML file is called WSDL. UDDI (Universal Description, Discovery, and Integration): UDDI is a XML based framework for describing, discovering and integrating web services. This layer is responsible for centralizing services into a common registry and providing easy publish/find functionality. It is a directory of web service interfaces described by WSDL, containing information about web services. Advantages of Soap Web Services  WS Security: SOAP defines its own security known as WS Security.  Language and Platform independent: SOAP web services can be written in any programming language and executed in any platform. Disadvantages of Soap Web Services  Slow: SOAP uses XML format that must be parsed to be read. It defines many standards that must be followed while developing the SOAP applications. So it is slow and consumes more bandwidth and resource.  WSDL dependent: SOAP uses WSDL and doesn't have any other mechanism to discover the service.
  • 3. Hamid Ghorbani (Web Services) https://ir.linkedin.com/in/ghorbanihamid RESTful Web Services: Web services based on REST (Representational State Transfer) Architecture (not a protocol) are known as RESTful web services. In REST Architecture everything is a resource. REST is web based architecture and doesn’t specify any specific protocol to use, but in almost all cases it’s used over HTTP/HTTPS. We can use XML, JSON, text or any other type of data for request and response. REST Client applications can use HTTP GET/POST methods to invoke Restful web services. A RESTful web service usually defines a URI and provides resource representation such as JSON and set of HTTP Methods. Jersey, Restlet, Apache wink, Spring MVC, Restfulie, and RESTEasy (JBoss ) frameworks implement JAX-RS API, which is standard specification to create RESTful web services. Advantages of RESTful Web Services Fast: RESTful Web Services are fast because there is no strict specification like SOAP. It consumes less bandwidth and resource. Permits different data format: RESTful web service permits different data format such as Plain Text, HTML, XML and JSON. Stateless: each request from client to server must contain all the information necessary to understand the request, and cannot take advantage of any stored context on the server. Cache: to improve network efficiency responses must be capable of being labeled as cacheable or non- cacheable. SOAP vs REST Web Services No. SOAP REST 1 SOAP is a protocol. REST is an architectural style. 2 SOAP uses services interfaces to expose the business logic. REST uses URI to expose business logic. 3 SOAP defines standards to be strictly followed. REST does not define too much standards like SOAP. 4 SOAP requires more bandwidth and resource than REST. REST requires less bandwidth and resource than SOAP. 5 SOAP defines its own security. RESTful web services inherits security measures from the underlying transport. 6 SOAP permits XML data format only. REST permits different data format such as Plain text, HTML, XML, JSON etc.
  • 4. Hamid Ghorbani (Web Services) https://ir.linkedin.com/in/ghorbanihamid REST API Implementation Java API for RESTful Web Services is JAX-RS. From version 1.1 on, JAX-RS is an official part of Java EE 6. A notable feature of being an official part of Java EE is that no configuration is necessary to start using JAX-RS. JAX-RS uses annotations, to simplify the development and deployment of web service clients and endpoints. JAX-RS provides some annotations to aid in mapping a resource class as a web resource:  @Path: Used to specify the relative path of class and methods. We can get the URI of a web service by scanning the Path annotation value. If it exists on both the class and method, the relative path to the resource method is a concatenation of the class and method.  @GET, @PUT, @POST, @DELETE and @HEAD: Used to specify the HTTP request type of a resource.  @Produces: Specifies the response Internet media types .  @Consumes: Specifies the accepted request Internet media types.  @PathParam: Used to bind the method parameter to path value by parsing it. The parameter type you inject into can be any primitive type, a String, or any Java object that has a constructor that takes a String parameter, or a static value of method that takes a String as a parameter. For example, let's say we wanted ISBN to be a real object.  @QueryParam: binds the method parameter to the value of an URI query string parameter.  @HeaderParam: Used to bind the method parameter to an HTTP header value.  @CookieParam: Used to bind the method parameter to a cookie value.  @FormParam: Used to bind the method parameter to a form value.  @DefaultValue: Specifies a default value for the above bindings when the key is not found.  @Context: Returns the entire context of the object. There are some implementations of JAX-RS API. 1. Jersey: Jersey is the reference implementation provided by Sun. For using Jersey as our JAX-RS implementation, all we need to configure its servlet in web.xml and add required dependencies. Note that JAX-RS API is part of JDK not Jersey, so we have to add its dependency jars in our application. 2. RESTEasy: RESTEasy is the JBoss project that provides JAX-RS implementation. 3. Spring MVC: from spring. 4. Apache CXF: Apache CXF is an open source Web service framework.
  • 5. Hamid Ghorbani (Web Services) https://ir.linkedin.com/in/ghorbanihamid Response Class: Sometimes the web service you are writing can’t be implemented using the default request/response behavior inherent in JAX-RS. For the cases in which you need to explicitly control the response sent back to the client, your JAX-RS resource methods can return instances of javax.ws.rs.core.Response: public abstract class Response { public static ResponseBuilder status(Status status) {...} public static ResponseBuilder status(int status) {...} public static ResponseBuilder ok() {...} public static ResponseBuilder ok(Object entity) {...} public static ResponseBuilder serverError() {...} public static ResponseBuilder created(URI location) {...} public static ResponseBuilder noContent() {...} public static ResponseBuilder notModified() {...} public static ResponseBuilder notModified(EntityTag tag) {...} public static ResponseBuilder notModified(String tag) {...} public static ResponseBuilder seeOther(URI location) {...} public static ResponseBuilder temporaryRedirect(URI location) {...} public static ResponseBuilder notAcceptable(List<Variant> variants) {...} public static ResponseBuilder fromResponse(Response response) {...} } The JAX-RS specification provides a Java enum called javax.ws.rs.core.Response.Status: public enum Status { OK(200, "OK"), CREATED(201, "Created"), ACCEPTED(202, "Accepted"), NO_CONTENT(204, "No Content"), MOVED_PERMANENTLY(301, "Moved Permanently"), SEE_OTHER(303, "See Other"), NOT_MODIFIED(304, "Not Modified"), TEMPORARY_REDIRECT(307, "Temporary Redirect"), BAD_REQUEST(400, "Bad Request"), UNAUTHORIZED(401, "Unauthorized"), FORBIDDEN(403, "Forbidden"), NOT_FOUND(404, "Not Found"), NOT_ACCEPTABLE(406, "Not Acceptable"), CONFLICT(409, "Conflict"), GONE(410, "Gone"), PRECONDITION_FAILED(412, "Precondition Failed"), UNSUPPORTED_MEDIA_TYPE(415, "Unsupported Media Type"), INTERNAL_SERVER_ERROR(500, "Internal Server Error"), SERVICE_UNAVAILABLE(503, "Service Unavailable"); }
  • 6. Hamid Ghorbani (Web Services) https://ir.linkedin.com/in/ghorbanihamid Response objects cannot be created directly; instead, they are created from ResponseBuilder instances returned by one of the static helper methods of Response. The ResponseBuilder class is a factory that is used to create one individual Response instance: public static abstract class ResponseBuilder { public abstract Response build(); public abstract ResponseBuilder clone(); public abstract ResponseBuilder status(int status); public ResponseBuilder status(Status status) {...} public abstract ResponseBuilder entity(Object entity); public abstract ResponseBuilder type(MediaType type); public abstract ResponseBuilder type(String type); public abstract ResponseBuilder variant(Variant variant); public abstract ResponseBuilder variants(List<Variant> variants); public abstract ResponseBuilder language(String language); public abstract ResponseBuilder language(Locale language); public abstract ResponseBuilder location(URI location); public abstract ResponseBuilder contentLocation(URI location); public abstract ResponseBuilder tag(EntityTag tag); public abstract ResponseBuilder tag(String tag); public abstract ResponseBuilder lastModified(Date lastModified); public abstract ResponseBuilder cacheControl(CacheControl cacheControl); public abstract ResponseBuilder expires(Date expires); public abstract ResponseBuilder header(String name, Object value); public abstract ResponseBuilder cookie(NewCookie... cookies); } Example: @Produces("text/plain") public Response getBook() { String book = ...; ResponseBuilder resBuilder = Response.ok(book); resBuilder.language("fa").header("Some-Header", "some value"); return builder.build(); }
  • 7. Hamid Ghorbani (Web Services) https://ir.linkedin.com/in/ghorbanihamid Building a REST Services with Jersey and JSON: 1) Create a standard Maven web project structure. 2) Add jersey-server and jersey-json Maven dependencies to pom.xml: <dependency> <groupId> com.sun.jersey</groupId> <artifactId>jersey-server</artifactId> <version>${jerseyServer.version}</version> </dependency> <dependency> <groupId> com.sun.jersey</groupId> <artifactId>jersey-json</artifactId> <version>${jerseyJson.version}</version> </dependency> 3) Register Jersey as the servlet dispatcher for REST requests and put your Jersey service folder under “init-param“with param name “com.sun.jersey.config.property.packages“. in your web.xml: <servlet> <servlet-name>jersey-serlvet</servlet-name> <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class> <init-param> <param-name>com.sun.jersey.config.property.packages</param-name> <param-value>myJerseyServiceFolder</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>jersey-serlvet</servlet-name> <url-pattern>/rest/*</url-pattern> </servlet-mapping> 4) Integrate JSON with Jersey: Declare “com.sun.jersey.api.json.POJOMappingFeature” as
  • 8. Hamid Ghorbani (Web Services) https://ir.linkedin.com/in/ghorbanihamid “init-param” in web.xml. It will make Jersey support JSON/object mapping: <init-param> <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name> <param-value>true</param-value> </init-param> Web.xml file after adding the above parameter: <servlet> <servlet-name>jersey-serlvet</servlet-name> <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class> <init-param> <param-name>com.sun.jersey.config.property.packages</param-name> <param-value>myJerseyServiceFolder</param-value> </init-param> <init-param> <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name> <param-value>true</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>jersey-serlvet</servlet-name> <url-pattern>/rest/*</url-pattern> </servlet-mapping> 5) Create Model class for Customer Object: public class Customers implements Serializable{ private int customerId; private String customerName; . . . //. . .Getter and setter and toString() methods }
  • 9. Hamid Ghorbani (Web Services) https://ir.linkedin.com/in/ghorbanihamid 6) Create Rest Service Class, The @Path annotation placed on the CustomerService class designates the class as a JAX-RS service. Java classes that you want to be recognized as JAX-RS services must have this annotation. Also notice that the @Path annotation has the value of /customers. This value represents the relative root URI of our customer service. If the absolute base URI of our server is http://localhost:8080, methods exposed by our CustomerResource class would be available under http://localhost:8080/customers: @Path("/customers") public class CustomersService { CustomerDAO customerDAO; @POST @Path("/createCustomer") @Consumes(MediaType.APPLICATION_JSON) public Response createCustomer(Customer customer) { customerDAO.create(customer); System.out.println("Customer Info Saved: " + customer.toString()); return Response.created(URI.create("/customers/customerInfo/" + customer.getId())).build(); } @GET @Path("/customerInfo/{customerId}") @Produces(MediaType.APPLICATION_JSON) public Response getCustomer(@PathParam("customerId") int customerId) { Customer customerInfo = customerDAO.get(customerId); if (customerInfo == null) { System.out.println("No Customer found for ID " + customerId); throw new WebApplicationException(Response.Status.NOT_FOUND); } return Response.status(Response.Status.OK).entity(customerInfo).build(); } @PUT @Path("/updateCustomer") @Produces(MediaType.APPLICATION_JSON) public void updateCustomer(@PathParam("customerId")int customerId, Customer customer) { boolean result = customersDAO.updateCustomer(customerId, customer); if (!result) throw new WebApplicationException(Response.Status.NOT_FOUND); return customersList; } }
  • 10. Hamid Ghorbani (Web Services) https://ir.linkedin.com/in/ghorbanihamid createCustomer() method: An HTTP POST request sends an JSON object representing the customer we want to create. The createCustomer() method receives the request, creates a Customer object, and adds it to our database. To bind HTTP POST requests to the createCustomer() method, we annotate it with the @POST annotation. The @Path annotation we put on the CustomerService class, combined with this @POST annotation, binds all POST requests going to the relative URI /customers to the Java method createCustomer(). The @Consumes annotation applied to createCustomer() specifies which media type the method is expecting in the message body of the HTTP input request. If the client POSTs a media type other than XML, an error code is sent back to the client. The static Response.created() method creates a Response object that contains an HTTP status code of 201, “Created.” It also adds a Location header to the HTTP response with the value of something like http://localhost:8080/customers/customerInfo/333, depending on the base URI of the server and the generated ID of the Customer object (333 is an example). getCustomer() method: The getCustomer() method annotated with the @GET annotation to bind HTTP GET operations to this Java method. getCustomer() also annotated with the @Produces annotation. This annotation tells JAX-RS which HTTP Content-Type the GET response will be. If the customer does not exist, method throws the javax.ws.rs.WebApplicationException. This exception will set the HTTP response code to 404, “Not Found,” meaning that the customer info does not exist. updateCustomer() method: We annotate the updateCustomer() method with @PUT to bind HTTP PUT requests to this method. If customer doesn’t exist, we throw a WebApplicationException that will send a 404, “Not Found,” response code back to the client. If the Customer object does exist, we update our existing Customer object with new updated values. Exception Handling: Errors can be reported to a client either by creating and returning the appropriate Response object or by throwing an exception. JAX-RS provides the javax.ws.rs.WebApplicationException. This can be thrown by application code and automatically processed by JAX-RS without having to write an explicit mapper. Example : throw new WebApplicationException(Response.Status.NOT_FOUND);
  • 11. Hamid Ghorbani (Web Services) https://ir.linkedin.com/in/ghorbanihamid Client Application for jersey web service: If you need to interact with a remote RESTful service, you can use the JAX-RS 2.0 Client API. The Client interface is responsible for managing client HTTP connections. public class TestRestService { public static void main(String[] args) { // create a customer Customer customer = new Customer("1", "Hubert",. . .); Client client = ClientBuilder.newClient(config); WebTarget service = client.target("http://localhost:8080/customers"); Response response = service.path("createcustomer") .request().post(Entity.json(customer)); // Return code should be 201 == created resource if (response.getStatus() != (Response.Status.CREATED) throw new RuntimeException("Failed to create"); System.out.println(response.getStatus()); // Get the customer String customer = service.path("customerInfo/1") .request().accept(MediaType.APPLICATION_JSON) .get(String.class); System.out.println(customer); }
  • 12. Hamid Ghorbani (Web Services) https://ir.linkedin.com/in/ghorbanihamid Spring MVC Framework and REST: The new approach in Spring 3, based on annotations and HttpMessageConverter, simplifies the process of creating RESTful web services. It is much more lightweight and easy to implement. The following are the list of spring annotations forimplementing RESTfull services:  @Configuration: Annotating a class with the @Configuration indicates that the class can be used by the Spring IoC container as a source of bean definitions.  @EnableWebMvc: This annotation is used for enabling Spring MVC in an application and works by importing the Spring MVC Configuration from WebMvcConfigurationSupport.  @ComponentScan: Spring needs to know the packages to scan for annotated components. We can use @ComponentScan annotation to specify the base packages to scan. Any class which is annotated with @Component will be scanned.  @RestController: @RestController annotation is the special version of @Controller and @ResponseBody annotations rolled together for implementing the RESTful Web Services. @RestController has been added as part of the Spring 4 release.  @RequestMapping: @RequestMapping annotation is used for mapping web requests to a specific handler classes and/or handler methods. Note: Since Spring MVC 4.3, you can use new annotations @GetMapping, @PostMapping, @PutMapping and @DeleteMapping instead of standard @RequestMapping. These annotations are standard way of defining REST endpoints. They act as wrapper to @RequestMapping: @GetMapping = @RequestMapping(method = RequestMethod.GET).  @RequestParam: @RequestParam is annotated in the methods to bind the method parameters to the request parameters. If the request is submitted by the browser, request parameters are passed through the URL query parameters. That can be easily mapped to the methods by annotating the method parameters with @RequestParam.  @ResponseBody: @ResponseBody binds a method's return value to the web response body. It uses HTTP Message converters to convert the return value to HTTP response body, based on the content- type in the request HTTP header. When you use the @ResponseBody annotation on a method, Spring converts the return value and writes it to the http response automatically.
  • 13. Hamid Ghorbani (Web Services) https://ir.linkedin.com/in/ghorbanihamid Building a REST Services with Spring: 1) Create a new spring MVC web project. Project's Spring dependencies are: <!—Spring Dependencies --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${springframework.version}</version> </dependency> 2) Add Jackson Maven dependency to pom.xml. Jackson API is a Java library for processing JSON. Using Jackson API we can convert Objects to JSON and vice versa: <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>${jaksonCore.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jaksonCore.version}</version> </dependency> 3) Set Servlet 3 Java Configuration: Since version 3.1, Spring supports using Servlet 3 API, so you can omit web.xml and Create AppInitializer class under config package: public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class[] getRootConfigClasses() { return new Class[] { AppConfig.class }; } @Override protected Class[] getServletConfigClasses() { return null; } @Override protected String[] getServletMappings() { return new String[] { "/" }; } }
  • 14. Hamid Ghorbani (Web Services) https://ir.linkedin.com/in/ghorbanihamid 4) Set Spring configuration: Starting from Spring 2.5 it became possible to configure the been dependency injection using annotations. So instead of using XML to describe a bean wiring, we can now use annotations to configure the bean wiring. Annotation injection is performed before XML injection. This means if a bean wiring is configured both with annotations and XML, the XML will override the annotation configuration. Create AppConfig.java file under /src/config folder like below: @Configuration @EnableWebMvc @ComponentScan public class AppConfig { } 5) Create Model class: Customer Class as an example: @Entity public class Customer implements Serializable{ private int customerId; private String customerName; . . . //..Getter and setter methods } 7) Create Controller Class: This class is annotated with @RestController annotation, So @ResponseBody annotation is not necessary on top of each method. The createCustomer() method parameter is annotated with @RequestBody, this annotation is used to map the request body JSON data into the Customer object. The @RequestMapping annotation placed on the CustomerRestController class has the value of /customers. This value represents the relative root URI of our customer rest service. If the base URI of our server is http://localhost:8080, methods exposed by our CustomerRestController class would be available under http://localhost:8080/customers. Example: createCustomer() method : http://localhost:8080/customers/createCustomer. getCustomer() method : http://localhost:8080/customers/getCustomer/1 . // suppose 1 is Customer Id
  • 15. Hamid Ghorbani (Web Services) https://ir.linkedin.com/in/ghorbanihamid @RestController @RequestMapping("/customers") public class CustomersRestController { @RequestMapping(value = "/createCustomer", method = RequestMethod.POST) public ResponseEntity createCustomer(@RequestBody Customer customer) { customerDAO.create(customer); return new ResponseEntity(customer, HttpStatus.OK); } @RequestMapping("/getCustomer/{customerId}", method = RequestMethod.GET) public ResponseEntity<Customer> getCustomer(@PathVariable("customerId") int customerId) { Customer customerInfo = customerDAO.get(customerId); if (customerInfo == null) { return new ResponseEntity("No Customer found for ID " + customerId, HttpStatus.NOT_FOUND); } return new ResponseEntity(customerInfo, HttpStatus.OK); } @RequestMapping(value = "/updateCustomer", method = RequestMethod.PUT) public ResponseEntity<Customer> updateCustomer(@PathVariable("customerId") int customerId, @RequestBody Customer customer) { if (customer == null) { System.out.println("Customer with id " + customerId + " not found"); return new ResponseEntity<Customer>(HttpStatus.NOT_FOUND); } customerDAO.updateCustomer(customer); return new ResponseEntity(customer, HttpStatus.OK); } @RequestMapping(value = "/customersList",method = RequestMethod.GET, produces = "application/json") public ResponseEntity<List<Customer>> getCustomersList() { List<Customer> customersList = customersDAO.getCustomersList(); return new ResponseEntity<List<Customer>>(customersList, HttpStatus.OK); } } ResponseEntity: ResponseEntity extends HttpEntity and adds additional information of HTTP method and uri to the request. ResponseEntity generates response with a given status code and its body.
  • 16. Hamid Ghorbani (Web Services) https://ir.linkedin.com/in/ghorbanihamid Client Application for Rest Web service: If you need to call remote REST services from your application, you can use Apache's HttpClient popular library, but the details to access REST services using this are too low level. Instead you can use Spring Framework’s RestTemplate class. RestTemplate provides higher level methods that correspond to each of the six main HTTP methods. HTTP Methods and corresponding RestTemplate methods:  HTTP GET : getForObject, getForEntity  HTTP PUT : put(String url, Object request, String…urlVariables)  HTTP DELETE : delete  HTTP POST : postForLocation(String url, Object request, String… urlVariables), postForObject(String url, Object request, Class responseType, String… uriVariables)  HTTP HEAD : headForHeaders(String url, String… urlVariables)  HTTP OPTIONS : optionsForAllow(String url, String… urlVariables)  HTTP PATCH and others : exchange execute Example: public class SpringRestTestClient { public static final String REST_SERVICE_URI = "http://localhost:8080/SpringRestService"; public static void main(String args[]){ RestTemplate restTemplate = new RestTemplate(); // Get customer Customer customer = restTemplate.getForObject(REST_SERVICE_URI+"/getCustomer/1", Customer.class); // Get All Customers List<Customer> customersList = restTemplate.getForObject(REST_SERVICE_URI + "/customersList/", List.class); Customer customer = new Customer(0,"Hubert",. . .); // create customer URI uri = restTemplate.postForLocation(REST_SERVICE_URI + "/createCustomer/", Customer, Customer.class); // update customer restTemplate.put(REST_SERVICE_URI+"/Customer/1", customer); // delete customer restTemplate.delete(REST_SERVICE_URI+"/Customer/1"); } }
  • 17. Hamid Ghorbani (Web Services) https://ir.linkedin.com/in/ghorbanihamid Resources: https://en.wikipedia.org/wiki/Java_API_for_RESTful_Web_Services https://www.javatpoint.com/java-web-services-tutorial h ps://www.journaldev.com/9191/java-web-services-tutorial http://javabeat.net/spring-annotations/ http://www.baeldung.com/spring-enable-annotations h p://docs.jboss.org/resteasy/docs/2.0.0.GA/Customerguide/html_single/index.html#_PathParam http://www.vogella.com/tutorials/REST/article.html https://dennis-xlc.gitbooks.io/restful-java-with-jax-rs-2-0-2rd-edition/en/index.html https://jersey.github.io/documentation/latest/index.html http://websystique.com/springmvc/spring-mvc-4-restful-web-services-crud-example-resttemplate/