Close

Spring MVC - Writing Java Objects to response body

[Updated: Apr 6, 2018, Created: Apr 6, 2018]

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

Example

The Controller

We are going to use java.io.ObjectOutputStream 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.io.ObjectOutputStream;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;

@Controller
public class MyController {

  @RequestMapping("/")
  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)){
              oos.writeObject(map);
          }
      };
  }
}

Boot main class

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

@SpringBootApplication
public class StreamingJavaObjectMain {
  public static void main (String[] args) {
      SpringApplication.run(StreamingJavaObjectMain.class, 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 java.net.URLConnection to make request and receive the Java object:

package com.logicbig.example;

import java.io.ObjectInputStream;
import java.math.BigInteger;
import java.net.URL;
import java.net.URLConnection;
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
                • MyController.java

    See Also