Spring MVC - Writing Java Objects to response body

[Last Updated: Apr 6, 2018]

Following example shows how to write Java objects directly to the output stream via StreamingResponseBody.


The Controller

We are going to use to write the response:

package com.logicbig.example;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;

public class MyController {

  public StreamingResponseBody handleRequest () {
      return outputStream -> {
          Map<String, BigInteger> map = new HashMap<>();
          map.put("one", BigInteger.ONE);
          map.put("ten", BigInteger.TEN);
          try(ObjectOutputStream oos = new ObjectOutputStream(outputStream)){

Boot main class

We are using Spring Boot in this example. Following is the main class:

public class StreamingJavaObjectMain {
  public static void main (String[] args) {, args);

Running web application

To try examples, run spring-boot maven plugin (configured in pom.xml of example project below):

mvn spring-boot:run

We can also run the above main class from our IDE.

The Client

As browser cannot handle serialized data written via ObjectOutputStream, we are going to use to make request and receive the Java object:

package com.logicbig.example;

import java.math.BigInteger;
import java.util.Map;

public class ClientMain {
  public static void main(String[] args) throws Exception {
      URL url = new URL("http://localhost:8080/");
      URLConnection connection = url.openConnection();
      try (ObjectInputStream inputStream = new ObjectInputStream(connection.getInputStream())) {
          Object o = inputStream.readObject();
          Map<String, BigInteger> map = (Map<String, BigInteger>) o;
          map.forEach((k, v) -> System.out.println(k + " = " + v));
Running the above main class from IDE:
one = 1
ten = 10

Example Project

Dependencies and Technologies Used:

  • Spring Boot 2.0.1.RELEASE
    Corresponding Spring Version 5.0.5.RELEASE
  • spring-boot-starter-web : Starter for building web, including RESTful, applications using Spring MVC. Uses Tomcat as the default embedded container.
  • JDK 1.8
  • Maven 3.3.9

Writing Java Objects to response stream Select All Download
  • spring-stream-java-objects
    • src
      • main
        • java
          • com
            • logicbig
              • example

    See Also