Spring Restful Webservice example with Maven and Tomcat

Connect with

Spring restful web services example in java using maven and tomcatSpring restful web services example in java maven and tomcat. In this rest ApI example I tried to explain how to develop Spring rest API.
Writing restful web services in java is very easy by using the Spring application framework. In the Rest API example, I’m going to demonstrate how to write a rest API example in Java Spring framework using Maven as a build tool and Tomcat 7 as a web server.

1. Maven Dependency for Spring Restful webservice



	4.0.0
	com.mysoftkey.sprintRest
	sprintRest
	1.0
	war
	sprintRest
	The project used for exposing restful web service for spring rest api for sprintRest app.

	
		4.1.0.RELEASE
		1.6.1
		2.5.3
	

	
		
			maven2-repository.java.net
			Java.net Repository for Maven
			http://download.java.net/maven/2/
		

	

	

		
		
			org.springframework
			spring-context
			${org.springframework.version}
			
				
				
					commons-logging
					commons-logging
				
			
		

		
			org.springframework
			spring-core
			${org.springframework.version}
			
				
				
					commons-logging
					commons-logging
				
			
		

		
			org.springframework
			spring-web
			${org.springframework.version}
		
		
			org.springframework
			spring-webmvc
			${org.springframework.version}
		
		
			org.springframework
			spring-test
			${org.springframework.version}
			test
		
		
			org.springframework
			spring-tx
			${org.springframework.version}
		
		
			javax.servlet
			javax.servlet-api
			3.1.0
		
		
			javax.servlet.jsp.jstl
			jstl-api
			1.2
		
		
			javax.servlet.jsp
			javax.servlet.jsp-api
			2.3.1
		

		
			org.codehaus.jackson
			jackson-mapper-asl
			1.9.13
		

		
			com.fasterxml.jackson.core
			jackson-databind
			${jackson.version}
		

		
			org.apache.httpcomponents
			httpclient
			4.3.6
		

		
			org.apache.commons
			commons-io
			1.3.2
		

		
		
			org.slf4j
			slf4j-api
			${org.slf4j.version}
		
		
			org.slf4j
			jcl-over-slf4j
			${org.slf4j.version}
			runtime
		
		
			org.slf4j
			slf4j-log4j12
			${org.slf4j.version}
			runtime
		
		
			log4j
			log4j
			1.2.16
			runtime
		

		
			commons-net
			commons-net
			3.3
		

	
	


2. User Controller class

package com.mysoftkey.springrest.controller;
 
import java.util.List;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UriComponentsBuilder;

import com.mysoftkey.springrest.model.User;
import com.mysoftkey.springrest.service.UserService;
 
@RestController
@RequestMapping(value = "/user")
public class UserController {
 
    @Autowired
    private UserService userService;  
     
    @RequestMapping(value = "/", method = RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity 	 	 	 	 	 	 	 	 	> getAllUsersHandler() {
        List users = userService.getAllUsers();
        if(users.isEmpty()){
            return new ResponseEntity 	 	 	 	 	 	 	 	 	>(HttpStatus.NO_CONTENT);
        }
        return new ResponseEntity 	 	 	 	 	 	 	 	 	>(users, HttpStatus.OK);
    }
 
    /**
     * This method is used to get User by userId in json format.
     * 
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity getUserByIdHandler(@PathVariable("id") long id) {
        User user = userService.getById(id);
        if (user == null) {
            System.out.println("User with id " + id + " not found");
            return new ResponseEntity(HttpStatus.NOT_FOUND);
        }
        return new ResponseEntity(user, HttpStatus.OK);
    }
 
    /**
     * This method is used to get add User object.
     * 
     * @param user
     * @param ucBuilder
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public ResponseEntity addeUserHandler(@RequestBody User user, UriComponentsBuilder ucBuilder) {
 
        if (userService.isUserExist(user)) {
            System.out.println("A User with name " + user.getName() + " already exist");
            return new ResponseEntity(HttpStatus.CONFLICT);
        }
 
        userService.addUser(user);
 
        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(ucBuilder.path("/user/{id}").buildAndExpand(user.getId()).toUri());
        return new ResponseEntity(headers, HttpStatus.CREATED);
    }
 
    /**
     * This method is used to update user with id.
     * 
     * @param id
     * @param user
     * @return
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public ResponseEntity updateUserHandler(@RequestBody User user, @PathVariable("id") long id) {
         
        User existingUser = userService.getById(id);
         
		if (existingUser == null) {
			System.out.println("User id " + id + " not found in our record");
			return new ResponseEntity(HttpStatus.NOT_FOUND);
		}
 
        existingUser.setName(user.getName());
        existingUser.setAge(user.getAge());
        existingUser.setSalary(user.getSalary());
         
        userService.updateUser(existingUser);
        return new ResponseEntity(existingUser, HttpStatus.OK);
    }
 
    /**
     * This method is used to delete user for provided user id.
     * 
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public ResponseEntity deleteUserHandler(@PathVariable("id") long id) {
 
    	// first fetch userId and , if exist then delete else set status not found 
        User user = userService.getById(id);
        if (user == null) {
            return new ResponseEntity(HttpStatus.NOT_FOUND);
        }
 
        userService.deleteUserById(id);
        return new ResponseEntity(HttpStatus.NO_CONTENT);
    }
}

3. Domain/Model/DTO/VO class

package com.mysoftkey.springrest.model;

/**
 * This is model class for User entity.
 * 
 * @author Ranjeet Jha
 *
 */
public class User {

	private long id = 0;
	
	private String name;
	
	private int age;
	
	private double salary;

	public User(){
	}
	
	public User(long id, String name, int age, double salary){
		this.id = id;
		this.name = name;
		this.age = age;
		this.salary = salary;
	}
	
	// add geter and setter method for these properties
}

4. User Service interface class

package com.mysoftkey.springrest.service;

import java.util.List;

import com.mysoftkey.springrest.model.User;

/**
 * This interface class is used to abstract the User operation.
 *  
 * @author Ranjeet Jha
 *
 */
public interface UserService {
	
	/**
	 * This method is used to get User by provided Id.
	 * 
	 * @param id
	 * @return
	 */
	public User getById(long id);
	
	/**
	 * This method is used to get User by provided userName.
	 * 
	 * @param name
	 * @return
	 */
	public User getByName(String name);
	
	/**
	 * This method is used to add User.
	 * 
	 * @param user
	 */
	public void addUser(User user);
	
	/**
	 * This method is used to update User
	 * 
	 * @param user
	 */
	public void updateUser(User user);
	
	/**
	 * This method is used to delete user by provided Id.
	 * 
	 * @param id
	 */
	public void deleteUserById(long id);

	/**
	 * This method is used to get all users. Assuming that number of user 
	 * is not much and pagination not required.
	 * 
	 * @return
	 */
	public List getAllUsers(); 
		
	/**
	 * This method is used whether provided user exist or not. 
         * if exist , it returns true else false.
	 * 
	 * @param user
	 * @return
	 */
	public boolean isUserExist(User user);
	
}

5. User Service Implimentation Class

In the user service class , tried to manipulate in in memory object.

package com.mysoftkey.springrest.service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.mysoftkey.springrest.model.User;

/**  
 * This service class is used to abstract the crud operation.
 * 
 * @author Ranjeet Jha
 *
 */
@Service("userService")
@Transactional
public class UserServiceImpl implements UserService {

	private static final AtomicLong counter = new AtomicLong();

	private static List userList;

	static {
		// populate dummy userList as application start.
		userList = populateDummyUsers();
	}

	public List getAllUsers() {
		return userList;
	}

	@Override
	public User getById(long id) {
		for (User user : userList) {
			if (user.getId() == id) {
				return user;
			}
		}
		return null;
	}

	@Override
	public User getByName(String name) {
		for (User user : userList) {
			if (user.getName().equalsIgnoreCase(name)) {
				return user;
			}
		}
		return null;
	}

	@Override
	public void addUser(User user) {
		user.setId(counter.incrementAndGet());
		userList.add(user);
	}

	@Override
	public void updateUser(User user) {
		int index = userList.indexOf(user);
		userList.set(index, user);
	}

	@Override
	public void deleteUserById(long id) {

		for (Iterator iterator = userList.iterator(); iterator.hasNext();) {
		 User user = iterator.next();
		 if (user.getId() == id) {
			iterator.remove();
		 }
		}
	}

	@Override
	public boolean isUserExist(User user) {
		return getByName(user.getName()) != null;
	}

	/**
	 * This method is used to populate dummy  data.
	 * 
	 * @return
	 */
	private static List populateDummyUsers() {
		List users = new ArrayList();
		users.add(new User(counter.incrementAndGet(), "Rokey", 25, 70000));
		users.add(new User(counter.incrementAndGet(), "Katty", 30, 30000));
		return users;
	}

}

6. Demo of Application

Here I tried to demonstrate different type of url, whether using rest client plugin or java client it’s your choice but I prefer to test all these service in ‘Advance Rest Client‘ of Google Crome browser.

  1. Get List of User
  2. Service endpoint URL: http://localhost:8080/springRest/user/
    output :

     [
    {
    id: 1,
    name: "Anushka",
    age: 25,
    salary: 70000
    },
    {
    id: 2,
    name: "Tanisha",
    age: 30,
    salary: 30000
    }
    ]
  3. Get User by userId:
  4. Service URL: http://localhost:8080/springRest/user/1
    HTTP method: GET
    output :

     {
    id: 1,
    name: "Rokey",
    age: 25,
    salary: 70000
    }
  5. add User
  6. Service endpoint URL: http://localhost:8080/springRest/user/add
    HTTP method: POST
    Content-Type: application/json

    input payload:

     {
    "id": 10,
    "name": "ranjeet",
    "age": 30,
    "salary": 70
    }
  7. update User by userId
  8. Service URL: http://localhost:8080/springRest/user/1
    HTTP method: PUT
    Content-Type: application/json

    input payload:

     {
    "id": 10,
    "name": "Ranjeet Jha",
    "age": 32,
    "salary": 70
    }
  9. Delete User by userId
  10. Service URL: http://localhost:8080/springRest/user/1
    HTTP method: DELETE
    Content-Type: application/json

7. Download

Click springRest-example-maven to download the source code of this example.

8. References

Spring Rest Guide official site
Spring Rest Web services Official site


Connect with

1 thought on “Spring Restful Webservice example with Maven and Tomcat”

  1. Pingback: minky

Leave a Comment

Your email address will not be published. Required fields are marked *