In the last example we saw how to write raw bytes using StreamingResponseBody. 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.GetMapping;
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 {
@GetMapping("/test")
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);
}
};
}
}
Configuration Class
@EnableWebMvc
@Configuration
@ComponentScan
public class WebConfig implements WebMvcConfigurer {
@Override
public void configureAsyncSupport(AsyncSupportConfigurer configurer) {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5);
executor.setMaxPoolSize(10);
executor.setThreadNamePrefix("mvc-async-");
executor.initialize();
configurer.setTaskExecutor(executor);
}
}
Running the example
To try examples, run embedded Jetty (configured in pom.xml of example project below):
mvn jetty:run
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/test");
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));
}
}
}
$ mvn -q clean compile exec:java -Dexec.mainClass="com.logicbig.example.ClientMain" one = 1 ten = 10
Example ProjectDependencies and Technologies Used: - spring-webmvc 7.0.6 (Spring Web MVC)
Version Compatibility: 4.2.0.RELEASE - 7.0.6 Version compatibilities of spring-webmvc with this example: Versions in green have been tested.
- jakarta.servlet-api 6.1.0 (Jakarta Servlet API documentation)
- junit-jupiter-engine 6.0.3 (Module "junit-jupiter-engine" of JUnit)
- hamcrest 3.0 (Core API and libraries of hamcrest matcher framework)
- JDK 25
- Maven 3.9.11
|