Spring MVC ResponseBody return List

If you want to return @ResponseBody body as java List using Spring MVC framework please follow below steps:

Very important point to return data as List:

  • Include annotation driven tag in dispatcher-servlet.xml (Spring context configuration) as shown below:
<mvc:annotation-driven />
  • If your controller method is annotate with @ResponseBody then Spring transforms returned data type into JSON format
  • @ResponseBody automatically encodes object in appropriate formats based on accept header of request and presence of JSON or XML libraries in classpath.
  • To encode data in appropriate format you will have to include JSON parser in your class path which will convert return data in appropriate format. For example I am using Jackson parser below is maven dependency that needs to be included in you pom.xml file and if you are using simple eclipse project then include jackson-mapper-aslxxx.jar in your class path.

Below are needed:

  • Eclipse 3.0 or above (Download from here)
  • JDK 1.6 or above (Download from here )
  • Tomcat 6 or above (Please follow link to install and configure tomcat in eclipse: Configure and Run Tomcat server in eclipse )
  • Maven 3.0.4
  • Jackson JSON dependencies in pom.xml

After all set up and configuration you will below Java List response in your browser:

Spring MVC ResponseBody return List

  • Create maven project name SpringReturnList in eclipse (Please use this link if you are not familiar how to create maven project in eclipse: Create maven Project Eclipse)
  • Below shows project structure:

Spring MVC ResponseBody return List

  • Please add below dependency in pom.xml file:
<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>SpringReturnList</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>SpringAutocomplete Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <properties>
        <spring.version>4.0.3.RELEASE</spring.version>
    </properties>
    <dependencies>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.9.13</version>
        </dependency>


    </dependencies>
    <build>
        <finalName>SpringReturnList</finalName>
    </build>
</project>

  • Please copy below XML into your web.xml file
<?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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
    <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>*.web</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>helloWorld.web</welcome-file>
    </welcome-file-list>

</web-app>
  • Now create file name: dispatcher-servlet.xml inside WEB-INF folder and copy and paste below content
<?xml  version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    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: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>
    
</beans>
  • Create jsp folder inside WEB-INF folder
  • Create jsp file name: helloWorld.jsp and copy paste below code:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<title>Spring list response</title>
</head>
<body>
<form:form method="get" action="returnListInResponse.web">
    <h1>Spring: ${message}</h1>
    Enter Request: <input type="text" name="name" value="">
    <input type="Submit" value="Get List In reponse">
    
</form:form>    
</body>
</html>
  • Create package name com.javahonk.controller inside src/main/java folder
  • Create class name: SpringMVCController.java inside com.javahonk.controller pakcage and copy paste below content in it:
package com.javahonk.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
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 {
    @RequestMapping(value = "/helloWorld.web", method = 
        RequestMethod.GET)
    public String printWelcome(ModelMap model, HttpServletRequest 
        request, HttpServletResponse response) {

    model.addAttribute("message", "Return List in response");
    return "helloWorld";

    }

    @RequestMapping(value = "/returnListInResponse.web", 
        method = RequestMethod.GET)
    public @ResponseBody
    List<String> returnListInResponse(@RequestParam("name") 
    String name) {
    
    List<String> list = new ArrayList<String>();
    if (name.equalsIgnoreCase("Java Honk")) {
        for (int i = 0; i < 10; i++) {
        list.add("Java");
        list.add("Honk");
        list.add("Test");
        }

    }else {
        for (int i = 0; i < 10; i++) {
        list.add("Name is not Java Honk");      
        }
    }
    
    return list;
    }
}

 

  • Now lets run this set up in tomcat server. If you haven’t done tomcat set up in eclipse yet please use this link: Configure and Run Tomcat server in eclipse. Now right click project –>Run As –> Run on server you will see below screen with input field to send request and get java list format response.

Spring MVC ResponseBody return List

  • Enter “Java Honk” in input field and click Get List In response button:

Spring MVC ResponseBody return List

  • Finally you will see below response from server in your browser:

Spring MVC ResponseBody return List

 

download Download Project: SpringRetrunList

That’s it Spring MVC ResponseBody return List

Leave a Reply

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