Wednesday, July 29, 2015

How to create a Restful application using Spring




Rest architecture has become a de facto standard for constructing APIs and consuming Web services. In the example below, we are going to create a simple Rest application step by step using Spring 4.

Requirements:

- Eclipse
- Maven
- Jackson (not necessary, but makes things easier)
- Spring
-Any web server ( Maven Jetty Plugin in our case).

Maven Dependencies can be found here: https://github.com/zak905/rest-spring-example/blob/master/pom.xml

Let's start by first creating our "web" application.

In Eclipse, we need to go to: File -> New  -> Maven -> Maven Project. Click on Next, and Choose Web application Archetype as shown below :


Next, we can enter our Group Id and Artifact Id. Click on Finish, and the application is created.

I assume that you are already familiar with MVC concepts such as Controllers.

The structure of the application is as follows:



After creating the application, we need to create our PoJo that will serve as our Rest Resource. Our object looks like:

public class Person {
 private String firstname;
 private String lastName;
 private int age;
 private String departement;
 
 
 public Person(){
  
  
 }

 public String getFirstname() {
  return firstname;
 }

 public void setFirstname(String firstname) {
  this.firstname = firstname;
 }


 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

 public int getAge() {
  return age;
 }

 public void setAge(int age) {
  this.age = age;
 }


 public String getDepartement() {
  return departement;
 }

 public void setDepartement(String departement) {
  this.departement = departement;
 }
 
}

Next, we need to create the controller that will serve our resource. In a Rest application, GET is used for read operations ( access the data), while POST is used for write operations (e.g create a new person in the database).

@Controller
@RequestMapping("/person")
public class PersonController {
	@RequestMapping(method= RequestMethod.GET)
	public @ResponseBody Person getPersons(){
		Person person = new Person();
		person.setFirstname("some first name");
		person.setLastName("some lastname");
		person.setAge(26);
		person.setDepartement("Accounting");
		return person;
	}
}

That's it. All we need to do now is to configure our servlet in web.xml, and then we can test our application. First, we create our "mvc-dispatcher-servlet.xml" in WEB-INF:



Then, we add the servlet definition in web.xml:



















Finally, we can run our application using Jetty. In Eclipse, right click on the project -> Run As -> Run Configurations. In Goals field, type: jetty:run. Now you can open your browser and go to: localhost:8080/person

Congratulation, you have successfully created a Rest style application.

Source Code : https://github.com/zak905/rest-spring-example