Spring MVC RESTFul Service POST Data Complete example

Spring MVC RESTFul Service POST Data Complete example

In this tutorial you will see how to develop Spring MVC RESTFul service and post data through HTML page and also test it through Postman – REST client for chrome efficient way to test RESTFul Service. Here we will post data with two value name and another string value with multiple line and process it. Please follow steps below:

  • Create maven project name: SpringMVCRESTFulService
  • Final project structure:

Spring MVC RESTFul Service POST Data Complete example

  • pom.xml:
<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.javahonk</groupId>
  <artifactId>SpringMVCRESTFulService</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>SpringMVCRESTFulService Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <properties>
		<junit.version>3.8.1</junit.version>
		<SpringVersion>4.0.6.RELEASE</SpringVersion>
		<spring-jdbc.version>4.0.6.RELEASE</spring-jdbc.version>
		<json.version>20140107</json.version>
		<jackson.version>1.9.10</jackson.version>
		<log4j.version>1.2.16</log4j.version>
		<jtds.version>1.2</jtds.version>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>${junit.version}</version>
			<scope>test</scope>
		</dependency>
		<!-- Spring dependencies -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${SpringVersion}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${SpringVersion}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${SpringVersion}</version>
		</dependency>
		<!-- Spring and Transactions -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>${spring-jdbc.version}</version>
		</dependency>

		<!-- Jackson JSON Mapper -->
		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-mapper-asl</artifactId>
			<version>${jackson.version}</version>
		</dependency>
		<dependency>
			<groupId>org.json</groupId>
			<artifactId>json</artifactId>
			<version>${json.version}</version>
		</dependency>		
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>${log4j.version}</version>
		</dependency>

	</dependencies>
  <build>
    <finalName>SpringMVCRESTFulService</finalName>
    <plugins>
		<plugin>
			<artifactId>maven-compiler-plugin</artifactId>
			<configuration>
				<source>1.6</source>
				<target>1.6</target>
			</configuration>
			<version>3.1</version>
		</plugin>
	</plugins>
  </build>
</project>
  • 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">
  <display-name>Archetype Created Web Application</display-name>
  <servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>
  • dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="
        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
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">

	<context:component-scan base-package="com.javahonk.controller" />
	<mvc:resources mapping="/static/**" location="/static/" />
    <mvc:annotation-driven/>
	
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix">
			<value>/WEB-INF/jsp/</value>
		</property>
		<property name="suffix">
			<value>.jsp</value>
		</property>
	</bean>  
	
	<!-- bind messages.properties -->
	<bean class="org.springframework.context.support.ResourceBundleMessageSource" id="messageSource">
		<property name="basename" value="messages" />
	</bean> 	

</beans>
  • index.jsp:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Spring MVC RESTFul Service POST Data Complete example</title>
</head>
<body>
<h2>Process data on server from @RequestBody </h2>
	<form action="springMVCRESTFulService" method="post">
		<h2>Post data example</h2>
		<p>
			<b>Name:</b> <input type="text" name="name">
		</p>
		<p>
			<b>String data:</b>
		</p>
		<textarea rows="15" cols="75" name="stringValue"></textarea>
		<p><input type="submit"></p> 
	</form>
<h2>Process data on server from @RequestParam </h2>	
	<form action="springMVCRESTFulService2" method="post">
		<h2>Post data example</h2>
		<p>
			<b>Name:</b> <input type="text" name="name">
		</p>
		<p>
			<b>String data:</b>
		</p>
		<textarea rows="15" cols="75" name="stringValue"></textarea>
		<p><input type="submit"></p> 
	</form>
</body>
</html>

SpringMVCController.java: In this class I will show you how to process form request data using below two method parameter:

  • @RequestBody: We will process form data using @RequestBody. Here all request comes as one object which is whole form request and data will be seperated by name value pair as (name=Java Honk&stringValue=Post data test. Also you will see if request send as multiple line in string how to fetch each line from it.
  • @RequestParam:  We will process form data using @RequestBody. Here request will come as separate form field parameter and will be process separately.

Java Class:

package com.javahonk.controller;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;


@Controller
public class SpringMVCController {
	
	private static final Logger logger = Logger.getLogger(SpringMVCController.class);
	
	@RequestMapping(value = "/firstPage")
	public String firstPage(ModelMap model) {
		
		logger.info("Log4j info is working");
        logger.warn("Log4j warn is working");       
        logger.debug("Log4j debug is working");
        logger.error("Log4j error is working");
        System.out.println("System out is working");
		model.addAttribute("message", "Spring MVC RESTFul Service");
		
		return "index";		
	}
	
	@RequestMapping(value = "/springMVCRESTFulService", method=RequestMethod.POST)
	public @ResponseBody String springMVCRESTFulService(@RequestBody String requestBody) {
		
		//If request contains multiple line and form submitted split data using 
		//New Line Code "%0D%0A"
		String value[] = requestBody.split("&");
		String name[] = value[0].split("=");
		
		System.out.println("Name: "+name[1].replace('+', ' '));
		
		String textAreaValue[] = value[1].split("=");		
		
		//New Line Code "%0D%0A"
		String val3[] = textAreaValue[1].replace('+', ' ').split("%0D%0A");
		if (val3.length != 0  && val3.length == 1) {
			val3 = textAreaValue[1].replace('+', ' ').split("\n");
		}
		StringBuffer finalValue = new StringBuffer();
		for (String string : val3) {
			System.out.println(string);
			finalValue.append(string+" ");
			
		}
		return "You entered value --> Name = "+name[1].replace('+', ' ')+" Text Area value =  "+finalValue.toString();
	}
	
	@RequestMapping(value = "/springMVCRESTFulService2", method=RequestMethod.POST)
	public @ResponseBody String angularServicePostCall2(@RequestParam String name, @RequestParam String stringValue) {
		
		//Split data if its multiple line
		String value[] = stringValue.split("\r\n");
		StringBuffer finalValue = new StringBuffer();
		for (String string : value) {
			System.out.println("Value entered in text area: "+string);
			finalValue.append(string+" ");
		}
		
		return "You entered value --> Name = "+name+" Text Area value =  "+finalValue.toString();		
	}
	

}
  • We will use tomcat server to run this code. Once you download and configure project test data as below:

Spring MVC RESTFul Service POST Data Complete example

  • As you see above we have two form on JSP page to test data using two different way.  Click submit button separately you will see below output:

Spring MVC RESTFul Service POST Data Complete example

Spring MVC RESTFul Service POST Data Complete example

  • Now test this service using Postman – REST client for chrome. You could add this extension in your chrome browser and open your Postman rest client and enter data as below:

Spring MVC RESTFul Service POST Data Complete example

download Download Project: SpringMVCRESTFulService

Leave a Reply

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