Java JAX-RS RESTful service with XML/JSON response using Application Subclass without web.xml

This tutorial tells about how to develop restful web service that returns XML or JSON as response using  java JAX-RS API.   In this example, let us create a  web service (GetEmployeeDetailsService)  using jersey-bundle 1.19 without Maven support in Eclipse. This simple Restful service does not require  any deployment descriptor (web.xml) for specifying base URI that maps to servlet.  This service has two resource methods as given below.

1. getEmployee – accetps employee code and return employee details as JSON or XML response.
http://localhost:8080/JavaRestService/resource/getEmployee/1001/

2. getEmployees – returns all employee list as JSON or XML response.

http://localhost:8080/JavaRestService/resource/getEmployees

You can also have a look at my earlier tutorial of  Java jax-rs Hello World service example with help of Maven and web.xml

Technologies Used:

Eclipse

JDK 1.8

jersey-bundle-1.19.jar (Includes code of all jersey jars that implements JAX-RS related features)

Apache Tomcat v7.0

Annotations used :

@ApplicationPath – to define base URI for the webservice for availing various method resources, etc..

@GET – to process HTTP GET requests

@Path – An URI path to map the HTTP requests with a java class and/or any java methods. This URI path is relative to base URI. For example, “/getEmployees”. You can also embed variables in the URIs like “/getEmployee/{empcode}” where empcode is a path variable. For example, “/getEmployee/1001/” where 1001 is the value of empcode that is passed to the resource method as a variable.

@PathParam – Extracts some value from the request URI and maps to the path parameter. The parameter name specified in the @PathParam(“parameter Name”) matches with the URI path embedded variable name specified in the @Path(“/getEmployee/{variable}”).

	    @Path("/getEmployee/{empcode}")
	    public EmpDetails getEmployee(@PathParam("empcode") String empcode) {
	    ....
	    ....
	     }

http://localhost:8080/JavaRestService/resource/getEmployee/1001/

In the above url, the value 1001 is mapped to empcode

@Produces – To specify content type ( MIME media types) of response that can be produced by a resource method. For example, “text/plain”, ‘application/json’, etc…

Example : @Produces(“application/json”)

Now let us create java restful (JAX-RS) web service (GetEmployeeDetailsService) that returns JSON/XML as response in Eclipse without maven

Steps:

1. Creating a Dynamic Web Project (JavaRestService) in Eclipse

             File->New->Dynamic Web Project

             Give Project Name as  JavaRestService     and  press Next , Next and Finish

                                    (web.xml is not required)

dynamic web project dynamic web project1 dynamic web project2

2. Define base URI for the WebService using @ApplicationPath annotation for mapping to the resources. As we are not using web.xml, the following sub class that extends Application is used to specify the Base URI using the annotation @ApplicationPath. Override getClasses() method of Application class in the sub class to return the list of resources.

EmpBaseApplication.java

package net.javaonline.restful.ws.application.controller;

import java.util.HashSet;
import java.util.Set;

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

//Does not require web.xml
//to define the base URI pattern
@ApplicationPath(value="/resource" )
public class EmpBaseApplication extends Application
{
	public EmpBaseApplication( ) {}

	@Override
	public Set<Class<?>> getClasses( )
	{
		final Set<Class<?>> rSet = new HashSet<Class<?>>( );
		rSet.add( GetEmployeeDetailsService.class );
		return rSet;
	}
} 

3. Write code for GetEmployeeService for retriving Employee details based on employee code or to display all employees

GetEmployeeDetailsService.java


package net.javaonline.restful.ws.application.controller;

import java.util.List;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import net.javaonline.restful.ws.application.dao.GetEmployeeDetailsDAO;
import net.javaonline.restful.ws.application.model.EmpDetails;

@Path("")

public class GetEmployeeDetailsService {

	    @GET
	    @Path("/getEmployee/{empcode}")
	    //@Produces("application/xml") //to return  XML as response
	    @Produces("application/json")  //to return JSON
	    public EmpDetails getEmployee(@PathParam("empcode") String empcode) {

	    	System.out.println("Inside service controller");
	        	GetEmployeeDetailsDAO empDao=new GetEmployeeDetailsDAO();
 	    	   //return Response.ok( empDao.getEmpDetails(empcode) ).build();
	        	return empDao.getEmpDetails(empcode);
	     }

	    @GET
	    @Path("/getEmployees")
	   // @Produces(MediaType.APPLICATION_XML)    //to produce XML response
	    @Produces(MediaType.APPLICATION_JSON)
	    public Response getEmployees() {

	    	System.out.println("Inside service controller1");
        	GetEmployeeDetailsDAO empDao=new GetEmployeeDetailsDAO();
        	GenericEntity<List<EmpDetails>> ge=new GenericEntity<List<EmpDetails>>(empDao.getEmployees()){};
      	    return Response.ok( ge ).build();

	     }

	}  

4. Write Model code (POJO) for EmpDetails

EmpDetails.java

package net.javaonline.restful.ws.application.model;

import java.io.Serializable;

import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="employee")
@XmlAccessorType(XmlAccessType.FIELD)

public class EmpDetails implements Serializable {

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;
	String empcode="";
	String empName="";
	double salary=0;
	String address="";

	public EmpDetails (){}	//Empty Constructor is required.  

	public EmpDetails(String empcode,String name, String address, double salary)
		{
			this.empcode=empcode;

			this.empName=name;

			this.address=address;

			this.salary=salary;

		}

	public String getEmpcode() {
		return empcode;
	}

	public void setEmpcode(String empcode) {
		this.empcode = empcode;
	}

	public String getEmpName() {
		return empName;
	}

	public void setEmpName(String empName) {
		this.empName = empName;
	}

	public double getSalary() {
		return salary;
	}

	public void setSalary(double salary) {
		this.salary = salary;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

}  

The above java class contains JAXB annotations.

1. @XmlRootElement(name=”employee”) – to map the above Java class to employee XML element.
2. @XmlAccessorType(XmlAccessType.FIELD) – All fields of the above java class are bound to XML

5. Create DAO class to return Employee Details or list of all employees


package net.javaonline.restful.ws.application.dao;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.javaonline.restful.ws.application.model.EmpDetails;

public class GetEmployeeDetailsDAO {

	Map<String, EmpDetails> employees = new HashMap<String, EmpDetails>();

	public GetEmployeeDetailsDAO()
	{

		//Emp details to be retrieved from the database. 

		employees.put("1001", new EmpDetails("1001", "ABC", "101, ABC St", 40000));
		employees.put("1002", new EmpDetails("1002", "XYZ", "102, XYZ St", 50000));
		employees.put("1003", new EmpDetails("1003", "QAZ", "103, QAZ St", 30000));
		employees.put("1004", new EmpDetails("1004", "WSX", "104, WSX St", 70000));
	}

	public EmpDetails getEmpDetails(String empcode)
	{

		return employees.get(empcode);  //returns employee datails based on employee code

	}

	public List<EmpDetails> getEmployees()
	{

		//Convert Map to ArrayList

		return new ArrayList<EmpDetails>(employees.values()); //returns list of employees. 

	}

} 

Call the webservice to get Employee details of any given employee code

http://localhost:8080/JavaRestService/resource/getEmployee/1002/

where 1002 is the employee code

JSON output:

jax-rs JSON1

To get output as XML, use the annotation @Produces(“application/xml”) in GetEmployeeDetailsService class instead of @Produces(“application/json”)

XML Output:

To get all employeejax-rs XML1s list, call the below url

http://localhost:8080/JavaRestService/resource/getEmployees

JSON Output:

XML Output:jax-rs JSON2jax-rs XML2

Reference : Packaging and Deploying RESTful Web Services

You may also like

Leave a Reply