3 Ways to return different content types from Spring MVC Controller? @RequestMapping and ResponseEntity Example Tutorial

Hello guys, if you want to provide different types from a Controller in Spring MVC and wondering how to do that then you have come to the right place. In the past, I have shared the free Spring MVC courses, books, and interview questions and in this article, I am going to show you three ways to send different content types from Spring Controller. There are various content types for a controller and we are going to discuss them in this tutorial. So we are going to discuss how to interpret the data present in the request and response. JSON is one of the media formats that may be consumed/produced using this request-response architecture.

So there will be a detailed description of different ways to set the content type in Spring MVC.

1. Using @RequestMapping in Spring

This is used to map web requests to a spring controller and it has various attributes including the HTTP method, request parameters, headers, and media types.

We can categorize the media types into two types named producible and consumable. If you need a different media type, we can also define it in here names custom media type. But we are not going to discuss this here. The main purpose of this media type is to restrict the primary mapping and allow only certain values.



After we specify the media type, the controller will accept from a client. As shown in the following example, we can provide a list of media types too.


RequestMapping(
value = "/students", 
method = RequestMethod.POST, 
consumes = "application/json")
public void addStudent(@RequestBody ContentType type, Model studentModel) {
  // your code
}

On an occasion, if it is unable to consume by resources, the system will generate a 406 Not acceptable
error.

@RequestMapping(value = "/students",
    method = RequestMethod.GET,
    produces = "application/json"
)
@ResponseBody
public String getStudents() {
    return "{\"getstudents\": \"getting all students\"}";
}

So let's use this API method to call the request. 

Call -  http://localhost:8080/students

{
  "getstudents" : "hello responsebody"
}

When a method's return type is String and there is no JSON Mapper in the classpath. The StringHttpMessageConverter class handles the return value in this example, setting the content type to "text/plain."



2. Using ResponseEntity

In the Spring MVC framework, ResponseEntity is a generic type that represents the entire HTTP response. So there is a capability to control all the status codes, header, and bodies.

@RequestMapping(
    value = "/getallstudents",
    method = RequestMethod.GET,
    produces = "application/json"
)
public ResponseEntity < String > getAllStudents() {
    final HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setContentType(MediaType.APPLICATION_JSON);
    return new ResponseEntity < String > ("{\"students\": \"Get all students\"}",
                httpHeaders, HttpStatus.OK);
}


we can see the following response.
{
"students": "Get all students"
}






3. Map<String, Object> return Type

In this method, we can use the Map return type instead of having String. This map return type will need and return JSON object.

@RequestMapping(
    value = "/students",
    method = RequestMethod.GET,
    produces = "application/json"
)
@ResponseBody
public Map < String, Object > getAlllStudents() {
    HashMap < String, Object > map = new HashMap < String, Object > ();
    map.put("students", "Get all students");
    return map;
}

so in the above code, we can use the following url to call the request and get the exact response.

http://localhost:8080/students

The response will be as follows:

{
"students" : "Get all students"
}

You can see that all three methods work fine and allow you to send different types of objects like String, ResponseEntity, and Map of String and Object. Accordinly Spring MVC handlers can set content-type to text/plain, text/json, or text/xml

3 Ways to Provide different content types for a Controller in Spring MVC? Example Tutorial



That's all about how to provide different content types from a Controller in Spring MVC. In this article, we discussed how to set content type in for a controller. First, we used the response entity and then the Map interface in order to match each other. So see you with the next tutorial.

Other Java and Spring Tutorial you may like
  • How to use @PropertySource annotation in Spring? (example)
  • How Spring MVC works internally? (answer)
  • 15 Spring Data JPA Interview Questions Answers (Spring data jpa question)
  • How to upload a file in the Spring MVC application? (example)
  • 15 Spring Cloud Interview Questions with Answers (Spring cloud questions)
  • Spring Data JPA @Query Example (query example)
  • Spring Data JPA Repository (JpaReposistory example)
  • 10 Advanced Spring Boot Courses for Java developers (courses)
  • Difference between @RequestParam and @PathVariable in Spring (answer)
  • Top 7  Courses to learn Microservices in Java (courses)
  • @SpringBootApplication vs @EnableAutoConfiguration? (answer)
  • 10 Spring MVC annotations Java developer should learn (annotations)
  • 5 Courses to Learn Spring Security for Java programmers (courses)
  • 5 Courses to learn Spring Cloud for Microservices (courses)
  • Difference between @Autowired and @Inject in Spring? (answer)
  • Top 5 Frameworks Java Developer Should Know (frameworks)
  • Difference between @Component@Service, and @Controller in Spring (answer)
  • Top 5 Spring Boot Annotations Java Developers should know (read)
  • 20+ Spring MVC Interview Questions for Programmers (answer)
  • 15 Spring Boot Interview Questions for Java Developers (questions)
  • Top 5 Courses to Learn and Master Spring Cloud (courses)
  • Top 5 Spring Cloud annotations Java programmer should learn (cloud)

Thanks for reading this article so far. If you find this Spring MVC tutorial and ResponseEntity and RequestMapping Example then please share it with your friends and colleagues. If you have any questions or feedback then please drop a note.

P. S. - If you are a Java beginner and want to learn the Core Spring Framework from scratch, and looking for some best online resources then you can also check out these best Spring MVC courses for Java developers.  This list contains the best Udemy and Pluralsight courses to learn Spring MVC from scratch.     

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.