Spring 4 MVC JSON Hello World Annotation Example

November 14, 2015 | Last tested: November 2015 | 2875 views | Comments

Return JSON responses on Spring Web MVC 4 Framework with Jackson JSON.

 

Built and tested with the following:

  • Eclipse Juno IDE
  • Apache Tomcat 7.0.47
  • JDK 1.7.0
  • Maven 3.0.4
  • Spring Web-MVC Framework 4.2.2
    • Configuration: XML
    • Url Mapping: Annotation
  • Jackson JSON 2.6.3

 

Task: Create a Spring WebMVC 4 application that will have a page that will return a message in JSON format.


Summary

  • Step 1. Set up a Spring WebMVC Framework 4 Application.
  • Step 2. Add dependency.
  • Step 3. Create the Class for the JSON message response.
  • Step 4. Create the JSON controller.
  • Step 5. Add a link from the Home Page.

Highlights

Add Dependency (pom.xml).

<!-- Jackson JSON -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.6.3</version>
</dependency>

Read more about Jackson JSON Processor

 

Create the JSON object.

package com.consistentcoder.json;

import java.util.List;

public class Response {
    private List<String> response;
    
    public Response(List<String> message) {
        this.response = message;
    }

    public List<String> getResponse() {
        return response;
    }

    public void setResponse(List<String> response) {
        this.response = response;
    }
}

 

Set the Producible media type element to application/json.

produces = "application/json"

For example.

@RequestMapping(value="/json", method=RequestMethod.GET, produces = "application/json")

Read more about Annotation Type RequestMapping - Element produces

 

Add the annotation @ResponseBody to the Controller.

@ResponseBody

For example.

@RequestMapping(value="/json", method=RequestMethod.GET, produces = "application/json")
@ResponseBody
public Response jsonPage() {

        /**
         * Set the response message and
         * append to the JSON object.
         */

    return new Response(result);
}

Read more about Annotation Type ResponseBody

 

Inside the Controller Method, add the response message to the JSON object.

List<String> result = new ArrayList<String>();
result.add("Hello World!");

For example.

@RequestMapping(value="/json", method=RequestMethod.GET, produces = "application/json")
@ResponseBody
public Response jsonPage() {

        List<String> result = new ArrayList<String>();
        result.add("Hello World!");

    return new Response(result);
}

Let's begin!


Step 1. Set up a Spring WebMVC Framework 4 Application.

Read about How to Create A Spring 4 MVC application tutorial Spring 4 MVC Hello World Annotation Example.

It is better to first read and understand the given sample above, but there are also some options to quickly set up the project. To clone, download, or import it's source code, go directly to this link.

Before proceeding with the next steps, it is important to have the Spring WebMVC application running correctly.

Spring 4 MVC Hello World Annotation Example Final Project Structure

A working Spring 4 MVC Hello World Annotation Example screenshot.

Continue below if your application is running correctly like what was shown on the above image.

 

Step 2. Add dependency.

Open pom.xml and add Jackson JSON as dependency.

<!-- Jackson JSON -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.6.3</version>
</dependency>

 

Step 3. Create the Class for the JSON message response.

Create a new package com.consistentcoder.json, and inside that new package, create a new class Response.

package com.consistentcoder.json;

import java.util.List;

public class Response {
    private List<String> response;
    
    public Response(List<String> message) {
        this.response = message;
    }

    public List<String> getResponse() {
        return response;
    }

    public void setResponse(List<String> response) {
        this.response = response;
    }
}

 

Step 4. Create the JSON controller.

Open Main.java Class and add a new method.

@RequestMapping(value="/json", method=RequestMethod.GET, produces = "application/json")
    @ResponseBody
    public Response jsonPage() {

            List<String> result = new ArrayList<String>();
            result.add("Hello World!");

        return new Response(result);
    }

 

Full Main.java code

package com.consistentcoder.controllers;

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

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.ResponseBody;

import com.consistentcoder.json.Response;

@Controller
public class Main {
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String index(ModelMap model) {
    
        model.addAttribute("message", "Spring 4 MVC JSON Hello World Example Built with Maven");
        return "hello";
    }
    
    @RequestMapping(value="/json", method=RequestMethod.GET, produces = "application/json")
    @ResponseBody
    public Response jsonPage() {

            List<String> result = new ArrayList<String>();
            result.add("Hello World!");

        return new Response(result);
    }
}

 

Step 5. Add a link from the Home Page.

By now, /json link is already up and will display the JSON response, to make it accessible from the home page for viewing purposes, just add a link to it. Open hello.jsp and add the link to the JSON page.

<p><a href="json">Click here to view a Sample JSON response.</a></p>

 

Full hello.jsp 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">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Spring 4 MVC JSON Hello World Annotation Example</title>
</head>
<body>
    <h1>${ message }</h1>
    <p><a href="json">Click here to view a Sample JSON response.</a></p>
</body>
</html>

 

That's all!

Spring 4 MVC JSON Hello World Annotation Example has been developed.

 

Final Project Structure

 

What's Next? Test the application.

Start your server and run the application. The Home Page will be displayed.

 

Click the "Click here to view a Sample JSON response" link.

 

 
 

Source Code