Writing Java Web Services using JAX-RS
What is a web service?
Web services are consumer — Provider applications that communicate on the network through the HTTP protocol and exchange and exchange data as XML, JSON and other formats of data standards.
Advantages of web services?
1. Interoperability.
2. Loosely Coupled.
3. Protocol Standards.
Types of Web services?
1. SOAP — XML based where provider and consumer are both use HTTP Post for data/message exchange.
2. RESTFul — They use all the methods available in HTTP Protocol (like GET,POST,PUT,DELETE etc) and they support multiple data format like (JSON, XML, Text etc).
What is Apache CXF?
Apache CXF™ is an open source services framework. CXF helps you build and develop services using frontend programming APIs, like JAX-WS and JAX-RS.
What is REST?
REST stands for REpresentational State Transfer, It offers one single standard interface to perform CRUD operations (Create Read, Update and Delete).
Why REST?
1. Single interface.
2. Easy to access.
3. Support for multiple data formats (xml, csv, text, json etc.).
4. Stateless.
When to REST?
1. Need for multiple data format.
2. For light weight applications.
3. Where there is no formal contract.
Four Simple steps to design REST project:
Pre requisites :
1. Install Java 8 / JDK 8 (https://www.oracle.com/in/java/technologies/javase/javase-jdk8-downloads.html).
2. Spring Tool Suite IDE (Go to the link and download the latest STS and install: https://spring.io/tools).
3. Postman for execution of web services (Download: https://www.postman.com/downloads)
Class diagram:
We will be using JAX-RS api to create webservices for the above project.
For definition and annotation of JAX-RS please refer:
https://docs.oracle.com/cd/E19776-01/820-4867/ghbzr/index.html
1. Create Project and configuration:
a. Create Sprint Boot Project.
Open Eclipse -> File ->New -> Spring Starter Project.
Note: If you see below error then change the “http” request to “https” in the url.
Give the below details :
Hit next and Finish:
You will see this in your IDE :
Now, Open the pom file in editor mode and add the following maven dependency w.r.t cxf-spring-boot-starter-jaxrs
url : https://mvnrepository.com/artifact/org.apache.cxf/cxf-spring-boot-starter-jaxrs
Dependency :
<! — https://mvnrepository.com/artifact/org.apache.cxf/cxf-spring-boot-starter-jaxrs →<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-spring-boot-starter-jaxrs</artifactId>
<version>3.4.0</version>
</dependency>
Save the pom file -> right click -> Run As -> Maven Build -> Goals: clean install –> SUCCESS.
b. Create the Beans and end points:
Go to src/main/java -> right click on the package -> New -> Class
Add new package “model” and give a name to the model class as shown below:
c. Mark the annotations and configure:
Copy the following code to the Employee class:
NOTE: Mark Resource class with JAX-B annotation and the only annotation is @XMLRootElement, its used for serialization and de serialization into xml, json etc.
@XmlRootElement(name="Employee")
package com.kiran.restfulws.model;public class Employee {
private long id;
private String name;public long getId() {
return id;
}public void setId(long id) {
this.id = id;
}public String getName() {
return name;
}public void setName(String name) {
this.name = name;
}
}
Right click on one of the packages -> New -> Interface -> Name ->Finish
Right click on any package -> New -> Class (Impl) -> Select the interface created above -> Finish.
Go to EmployeeService class and add the following:
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import com.kiran.restfulws.model.Employee;@Path("/employeeservice")
public interface EmployeeService {@Path("/employees")
@GET
List<Employee> getEmployees();@Path("/employees/{id}")
@GET
Employee getEmployee(@PathParam(value = "id") long id);
}
Note: For Service (Interface) class give annotations
Go to EmployeeServiceImpl class and add the following:
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Service;
import com.kiran.restfulws.model.Employee;@Service
public class EmployeeServiceImpl implements EmployeeService {
Map<Long, Employee> employees = new HashMap<>();
long liveId1 = 1000l;
long liveId2 = 1001l;public EmployeeServiceImpl() {
init();
}void init() {
Employee employee1 = new Employee();
employee1.setId(liveId1);
employee1.setName("Adam");
employees.put(employee1.getId(), employee1);Employee employee2 = new Employee();
employee2.setId(liveId2);
employee2.setName("Samson");
employees.put(employee2.getId(), employee2);
}@Override
public List<Employee> getEmployees() {
Collection<Employee> output = employees.values();
List<Employee> result = new ArrayList<>(output);
return result;
}@Override
public Employee getEmployee(long id) {
return employees.get(id);
}
}
Note: @Service annotation is a spring annotation when given this bean will be discovered at run time. Do not forget to give this.
2. Configure the webservices end point (Final step before running the project):
Go to src/main/resources and open the application.properties file -> add the following properties :
cxf.jaxrs.component-scan=true
server.servlet.context-path=/restws
3. Test your application :
To launch the application -> Right click on the project -> Run As -> Spring Boot App.
Once run is successful, note down the port number of the tomcat application started.
Now launch postman -> Give the following:
- Get all the employees in the application built.
url : http://localhost:8080/restfulws/services/employeeservice/employees
2. Get single employee in the application built.
Url : http://localhost:8080/restfulws/services/employeeservice/employees/1001
Thanks!