Spring RESTful Web Service with JSON Example

  • Facebook
  • Google
  • LinkedIn
  • Twitter

REST(Representational State Transfer) is an architectural style with which Web Services can be designed that serves resources based on the request from client. A Web Service is a unit of managed code, that can be invoked using HTTP requests. REST has gained in popularity over its contender SOAP (Simple Object Access Protocol) because REST is lighter in terms of bandwidth usage. RESTful services are much easier to implement and scale than SOAP. Once you develop the core functionality of application, deployed it on the server and is exposed, then everyone can be accessed using URI's through HTTP requests from a variety of client applications. No need of repeating the same functionality in multiple machine, you write it once and access it anywhere means if anything change in functionality it will be reflected to client.

Advantage

  • RESTful Web Services are fast because there is no strict specification like SOAP. It consumes less bandwidth and resource.
  • RESTful web services can be written in any programming language and executed in any platform.
  • RESTful web services can use SOAP web services as the implementation.
  • RESTful web service permits different data format such as Text, HTML, XML and JSON.

I have used the following:

  • Java JDK 1.6
  • Eclipse 4.5
  • Tomcat 8
  • Spring 3.1.1
  • JSON

Open Eclipse and click on File --> New --> Dynamic Web Project

Create pom.xml under springrest project

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.javatutsworld</groupId>
	<artifactId>springrest</artifactId>
	<name>SpringRestExample</name>
	<packaging>war</packaging>
	<version>1.0.0-BUILD-SNAPSHOT</version>
	<properties>
		<java-version>1.6</java-version>
		<org.springframework-version>3.1.1.RELEASE</org.springframework-version>
		<org.aspectj-version>1.6.10</org.aspectj-version>
		<org.slf4j-version>1.6.6</org.slf4j-version>
	</properties>
	<dependencies>
		<!-- Spring -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${org.springframework-version}</version>
			<exclusions>
				<!-- Exclude Commons Logging in favor of SLF4j -->
				<exclusion>
					<groupId>commons-logging</groupId>
					<artifactId>commons-logging</artifactId>
				 </exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
				
		<!-- AspectJ -->
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjrt</artifactId>
			<version>${org.aspectj-version}</version>
		</dependency>	

		<!-- Jackson  -->
		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-mapper-asl</artifactId>
			<version>1.9.13</version>
		</dependency>
		
		<!-- Logging -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${org.slf4j-version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>jcl-over-slf4j</artifactId>
			<version>${org.slf4j-version}</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>${org.slf4j-version}</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.15</version>
			<exclusions>
				<exclusion>
					<groupId>javax.mail</groupId>
					<artifactId>mail</artifactId>
				</exclusion>
				<exclusion>
					<groupId>javax.jms</groupId>
					<artifactId>jms</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.sun.jdmk</groupId>
					<artifactId>jmxtools</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.sun.jmx</groupId>
					<artifactId>jmxri</artifactId>
				</exclusion>
			</exclusions>
			<scope>runtime</scope>
		</dependency>

		<!-- @Inject -->
		<dependency>
			<groupId>javax.inject</groupId>
			<artifactId>javax.inject</artifactId>
			<version>1</version>
		</dependency>
				
		<!-- Servlet -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>jsp-api</artifactId>
			<version>2.1</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
	
		<!-- Test -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.7</version>
			<scope>test</scope>
		</dependency>        
	</dependencies>
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-eclipse-plugin</artifactId>
                <version>2.9</version>
                <configuration>
                    <additionalProjectnatures>
                        <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
                    </additionalProjectnatures>
                    <additionalBuildcommands>
                        <buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
                    </additionalBuildcommands>
                    <downloadSources>true</downloadSources>
                    <downloadJavadocs>true</downloadJavadocs>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.5.1</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                    <compilerArgument>-Xlint:all</compilerArgument>
                    <showWarnings>true</showWarnings>
                    <showDeprecation>true</showDeprecation>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.2.1</version>
                <configuration>
                    <mainClass>org.test.int1.Main</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

dispatcher-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:beans="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

	<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
	
	<!-- Enables the Spring MVC @Controller programming model -->
	<annotation-driven />

	<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
	<resources mapping="/resources/**" location="/resources/" />

	<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
	<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<beans:property name="prefix" value="/WEB-INF/views/" />
		<beans:property name="suffix" value=".jsp" />
	</beans:bean>
	
	<context:component-scan base-package="com.javatutsworld.springrest" />
	
</beans:beans>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/root-context.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

Model Class (Student.java)

package com.javatutsworld.model;

public class Student {
	private String studentId;
	private String studentName;
	private String studentAddress;
	private String country;

	public String getStudentName() {
		return studentName;
	}

	public void setStudentName(String studentName) {
		this.studentName = studentName;
	}

	public String getStudentAddress() {
		return studentAddress;
	}

	public void setStudentAddress(String studentAddress) {
		this.studentAddress = studentAddress;
	}

	
	public Student() {
	}
	
	public Student(String studentId, String studentName, String studentAddress, String country) {
		setStudentId(studentId);
		setStudentName(studentName);
		setStudentAddress(studentAddress);
		setCountry(country);
	}
	
	public String getStudentId() {
		return studentId;
	}
	
	public void setStudentId(String studentId) {
		this.studentId = studentId;
	}
	
		public String getCountry() {
		return country;
	}
	
	public void setCountry(String country) {
		this.country = country;
	}
	
	public String toString() {
		return "[" + getStudentId()
				+ ", " + getStudentName()
				+ ", " + getStudentAddress()
				+ ", " + getCountry()
				+ "]";
	}
}

Controller Class (RestController.java)

package com.javatutsworld.springrest;

import java.text.DateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.javatutsworld.model.Student;;

/**
 * Handles requests for the application home page.
 */
@Controller
public class RestController {
	
	private static final Logger logger = LoggerFactory.getLogger(RestController.class);
	private Map<String, Student> students = new HashMap<String, Student>();
	
	public RestController() {
		// pre-initialize the list of students available ...
		
		students.put("001", new Student("001", "Mohd Saaim", "D-15 Okhla Vihar", "INDIA"));
		students.put("002", new Student("002", "Mohd Aariz", "D-15 Okhla Vihar", "INDIA"));
	}
	
	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String home(Locale locale, Model model) {
		logger.info("Welcome home! The client locale is {}.", locale);
		
		Date date = new Date();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
		
		String formattedDate = dateFormat.format(date);
		
		model.addAttribute("serverTime", formattedDate );
		
		return "status";
	}
	
	@RequestMapping(value="/students", method=RequestMethod.GET)
	@ResponseBody
	public Map<String, Student> getAllStudents() {
		logger.info("Inside getAllStudents() method...");
		
		return students;
	}
	
	@RequestMapping(value="/student/{studentId}", method=RequestMethod.GET)
	@ResponseBody
	public Student getStudentByStudentId(@PathVariable("studentId") String studentId) {
		Student myStudent = students.get(studentId); 
		
		if (myStudent != null) {
			logger.info("Inside getStudentByStudentId, returned: " + myStudent.toString());
		} else {
			logger.info("Inside getStudentByStudentId, studentId: " + studentId + ", NOT FOUND!");
		}
		return myStudent; 
	}

	@RequestMapping(value="/student/delete/{studentId}", method=RequestMethod.GET)
	@ResponseBody
	public Student deleteStudentByStudentId(@PathVariable("studentId") String studentId) {
		Student myStudent = students.remove(studentId); 
		
		if (myStudent != null) {
			logger.info("Inside deleteStudentByStudentId, deleted: " + myStudent.toString());
		} else {
			logger.info("Inside deleteStudentByStudentId, ticker: " + studentId + ", NOT FOUND!");
		}
		return myStudent;
	}

	@RequestMapping(value="/student/create", method=RequestMethod.GET)
	public ModelAndView addStudent() {
		
		return new ModelAndView("addStudent", "command", new Student());
	}
	
	@RequestMapping(value="/student/addStudent", method=RequestMethod.POST)
	@ResponseBody
	public Student addStudent(@ModelAttribute("student") Student student) {
		
		if (student != null) {
			logger.info("Inside addStudent, adding: " + student.toString());
		} else {
			logger.info("Inside addStudent...");
		}
		students.put(student.getStudentId(), student);
		return student;
		
	}
	
}

Add Student View (addStudent.jsp)

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="f" %>
<%@ page session="false" %>
<html>
	<head>
		<title>${message}</title>
	</head>
	<body>
	    <h1>${message}</h1>
		<f:form method="POST" action="addStudent">
		<table>
			<tbody>
				<tr>
				  <td>Student Id:</td>
				  <td><f:input path="studentId" size="10" maxlength="10"></f:input></td>
				</tr>
				<tr>
				  <td>Student Name:</td>
				  <td><f:input path="studentName" size="30"></f:input></td>
				</tr>
				<tr>
				  <td>Student Address:</td>
				  <td><f:input path="studentAddress" size="6"></f:input></td>
				</tr>
				<tr>
				  <td>Country:</td>
				  <td><f:input path="country" size="20"></f:input></td>
				</tr>
				<tr>
        			<td colspan="2"><input type="submit" value="Add Student"></td>
    			</tr>
			</tbody>
		</table>
		</f:form>	
	</body>
</html>

Build and deploye on the server

Below is url to get a List of All Students

http://localhost:8080/springrest/students

Spring Rest

Below is url to get Student By studentId

http://localhost:8080/springrest/student/005

Spring Rest

Below is url to add an Student Using Form

http://localhost:8080/springrest/student/create

Spring Rest

      Advertisements