Friday, May 19, 2023

How to return JSON, XML or Thymeleaf Views from Spring MVC Controller? Example Tutorial

Hello guys, if you are working in Spring based web application and you wan to return JSON, XML, or Thymeleaf View from your application but don't know how to do that then you have come to the right place. Earlier, I have shared how to create REST API in Spring, React + Spring project, and Spring Boot Interview Questions  and In this tutorial we are going to discuss, how to return to JSON, XML, or Thymeleaf view from the Spring MVC controller. To ensure that your payload from the MVC endpoint, ensure your project is using the Spring Boot starter web. You can use the following dependency to include spring boot starter web in your project. 

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>


Spring boot ensures that Jackson is auto-configured to serialize and deserialize Java objects to JSON when using this starter.

Then you have to annotate your controller with @RestController to instruct spring to bind the response of your method to the web response.


@RestController
@RequestMapping("/studentjson")
public class JsonPayloadController {

    @GetMapping(path = "/students", produces = MediaType.APPLICATION_JSON_VALUE)
    public List < Student > getStudents() {
        List < Student > students = List.of(
            new Student("IT17092548", 12, "Grade C"),
            new Student("IT17092590", 8, "Grade D")
        );
        return students;
    }
}



If you want your controller to return a different HTTP status, make sure your method returns the Spring response wrapper ResponseEntity.


@GetMapping(path = "/students", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity < List < Student >> getOrders() {
    List < Student > students = List.of(
        new Student("IT17092548", 12, "Grade C"),
        new Student("IT17092590", 8, "Grade D")
    );
    return ResponseEntity.status(HttpStatus.SUCCESS).body(students);

}




How to return a thymeleaf view from a controller

To start with the thymeleaf, you have to add the following spring dependency to your project.

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

Get the Thyemleaf dependency and the autoconfiguration mechanism of spring boot ensures all required beans with correct configuration are in place. Spring may be told the view name to render in a variety of methods, the simplest of which is to return the view name as a string.

@Controller
@RequestMapping("/student")
public class StudentController {

    @GetMapping
    public String getStudentsPage(Model model) {
        model.addAttribute("student", "Get all students");
        return "all students";
    }
}


The Thymeleaf view resolver searches for templates at classpath:/templates/ with the .html suffix.

<!DOCTYPE HTML>
<html lang="en" xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="utf-8">
    <title>Welcome</title>
</head>

<body>
    <div>
        <span th:text="${student}"></span>
    </div>
</body>

</html>



You can access the HTML page using http://localhost:8080/welcome and returns and including the message of students that has been set in the studentController.





How to return an XML from a controller? 

First, you need to add the Jackson dependency into your spring application pom.xml file.

<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>


If you are using the spring boot starter web, spring boot ensures to auto-configure everything to make use of the JacksonXmlModule. You need to annotate your POJO with @XmlRootElement.

@XmlRootElement
public class Student {

    private String id;

    // getters & setters

}

How to return to JSON, XML or Thymeleaf view from Spring MVC Controller?

Now you can return XML from your spring MVC controller methods.

@GetMapping(path = "/students", produces = MediaType.APPLICATION_XML_VALUE)
public List < Student > getStudents() {
    List < Student > students = List.of(
        new Student("IT17092548", 12, "Grade C"),
        new Student("IT17092590", 8, "Grade D")
    );
    return students;
}



That's all about how to return different kind of views from Spring MVC controller. So in this tutorial, we have discussed the how-to return the JSON, XML, or Thymeleaf view from the spring MVC controller with examples. So see you in the next tutorial with another interesting topic.

Other Spring MVC articles and Tutorials you may like
Thanks a lot for reading this article so far. If you like this Java and Spring MVC tutorial then please share them with your friends and colleagues. If you have any questions or feedback then please drop a note. 

No comments :

Post a Comment