Spring Boot Rest XML Request and Response Example

In this topic, we will learn to create a Spring Boot Restful web service example in that a RestController accepts XML as a request and returns XML as a response instead of JSON. We will create a CRUD Rest API example project in Spring Boot using Maven, Spring Web, Spring Data JPA, and H2 database.

spring_boot_rest_request_response_xml

The above diagram shows a flow of the CRUD restful web service Spring Boot example project. Let’s create this example step-by-step

1. Creating a Spring Boot Starter Project

We are creating a Spring Boot Application from the web tool Spring Initializr or you can create from IDE(STS, vs code etc.) which you are using. 
Add the following dependencies: 
  • Spring Web
  • Spring Data JPA
  • Lombok
  • H2 Database

2. Keep the IDE ready

We are importing this created application into our Eclipse IDE or you can import it into another IDE you are using. You can refer to this article to create and set up the Spring Boot Project in Eclipse IDE.

Project Structure of Spring Boot REST with Request Response XML

project_structure_xml_request_response_spring_boot 

3. Adding the jackson-dataformat-xml library

We are adding this jackson-dataformat-xml dependency in the pom.xml file.

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

→ This library is used to render XML responses.

4. Maven Dependency

Here is the complete pom.xml file for the Spring Boot Application.
pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.3</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.springjava</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-xml</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

5. Defining the configuration

We are configuring the H2 database configuration in the application.properties file.
application.properties

# H2 Database Configuration
spring.datasource.url=jdbc:h2:mem:test
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=update
spring.h2.console.enabled=true

6. Creating a JPA Entity

We are creating a JPA entity class Student with these properties(id, studentName, email, and mobileNo).
Student.java

package com.springjava.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import lombok.Data;

@Data
@Entity
public class Student{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String studentName;
private String email;
private String mobileNo;
}

→ This @Data annotation is used for a constructor, setter method, getter method etc.
→ This @Entity annotation is used to create a table through Java code in the database.

7. Creating a JPA Repository

We are creating a JPA Repository to interact with the JPA Entity class and use the query method for the persistence operation in the table student.
StudentRepository.java

package com.springjava.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.springjava.entity.Student;
public interface StudentRepository extends JpaRepository<Student, Integer> {
}

8. Creating a Service Interface

We are creating a Service interface with some method declaration( save(), findAll(), and findById()).
StudentService.java

package com.springjava.service;
import java.util.List;
import com.springjava.entity.Student;
public interface StudentService {
void save(Student student);
List<Student> findAll();
Student findById(Integer id);
void delete(Student student);
}

9. Creating a Service class

We are creating a Service class StudentServiceImpl and this class is implementing the StudentService interface. This class is annotated with @Service annotation to act as a service for the application
StudentServiceImpl.java

package com.springjava.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.springjava.entity.Student;
import com.springjava.repository.StudentRepository;
@Service
public class StudentServiceImpl implements StudentService {
    @Autowired
    StudentRepository stuRepo;
    @Override
    public void save(Student student) {
        stuRepo.save(student);    
    }
    @Override
    public List<Student> findAll() {
        return stuRepo.findAll();
    }
    @Override
    public Student findById(Integer id) {
        return stuRepo.findById(id).get();
    }
    @Override
    public void delete(Student student) {
        stuRepo.delete(student);
        
    }
}

10. Creating an XML configuration class

We are creating an XML configuration class WebConfg that implements the WebMvcConfigurer interface.
WebConfg.java

package com.springjava.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfg implements WebMvcConfigurer {

@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.defaultContentType(MediaType.APPLICATION_XML);
    }
}

→ This @Configuration annotation uses the class as a source of bean definitions for the application context.
→ This WebMvcConfigurer interface defines callback methods to customise the Java-based configuration for Spring MVC.
→ If we do not create this class, we must mark each method with produces=MediaType.APPLICATION_XML_VALUE of the Controller.

11. Creating a RestConroller class

We are creating a RestController class StudentController in which all methods are created for API endpoints
StudentController.Java

package com.springjava.controller;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.springjava.entity.Student;
import com.springjava.service.StudentService;

@RestController
@RequestMapping("/api")
public class StudentController {
    @Autowired
    StudentService stuService;
    
    @PostMapping("/student/save")
    public ResponseEntity<?> saveStudent(@RequestBody Student student) {
        Map<String, Object> respStu = new LinkedHashMap<String, Object>();
        stuService.save(student);
        respStu.put("status", 1);
        respStu.put("message", "Record is Saved Successfully!");
        return new ResponseEntity<>(respStu, HttpStatus.CREATED);
    }
    
    @GetMapping("/student/list")
    public ResponseEntity<?> getStudents() {
        Map<String, Object> respStu = new LinkedHashMap<String, Object>();
        List<Student> studList = stuService.findAll();
        if (!studList.isEmpty()) {
            respStu.put("status", 1);
            respStu.put("data", studList);
            return new ResponseEntity<>(respStu, HttpStatus.OK);
        } else {
            respStu.clear();
            respStu.put("status", 0);
            respStu.put("message", "Data is not found");
            return new ResponseEntity<>(respStu, HttpStatus.NOT_FOUND);
        }
    }
    @GetMapping("/student/{id}")
    public ResponseEntity<?> getUserById(@PathVariable Integer id) {
        Map<String, Object> respStu = new LinkedHashMap<String, Object>();
        try {
            Student stu = stuService.findById(id);
            respStu.put("status", 1);
            respStu.put("data", stu);
            return new ResponseEntity<>(respStu, HttpStatus.OK);
        } catch (Exception ex) {
            respStu.clear();
            respStu.put("status", 0);
            respStu.put("message", "Data is not found");
            return new ResponseEntity<>(respStu, HttpStatus.NOT_FOUND);
        }
    }
    
    @PutMapping("student/update/{id}")
    public ResponseEntity<?> updateUserById(@PathVariable Integer id, @RequestBody Student student) {
        Map<String, Object> respStu = new LinkedHashMap<String, Object>();
        try {
            Student stu = stuService.findById(id);
            stu.setStudentName(student.getStudentName());
            stu.setEmail(student.getEmail());
            stu.setMobileNo(student.getMobileNo());
            stuService.save(stu);
            respStu.put("status", 1);
            respStu.put("data", stuService.findById(id));
            return new ResponseEntity<>(respStu, HttpStatus.OK);
        } catch (Exception ex) {
            respStu.clear();
            respStu.put("status", 0);
            respStu.put("message", "Data is not found");
            return new ResponseEntity<>(respStu, HttpStatus.NOT_FOUND);
        }
    }
    @DeleteMapping("/student/delete/{id}")
    public ResponseEntity<?> deleteUser(@PathVariable Integer id) {
        Map<String, Object> respStu = new LinkedHashMap<String, Object>();
        try {
            Student stu = stuService.findById(id);
            stuService.delete(stu);
            respStu.put("status", 1);
            respStu.put("message", "Record is deleted successfully!");
            return new ResponseEntity<>(respStu, HttpStatus.OK);
        } catch (Exception ex) {
            respStu.clear();
            respStu.put("status", 0);
            respStu.put("message", "Data is not found");
            return new ResponseEntity<>(respStu, HttpStatus.NOT_FOUND);
        }
    }
}

12. Run the Spring Boot Application and Check

Right Click on the DemoApplication.java then click on Run As, and select Java Application
Check H2 Database
Check the H2 database console and browse this URL “http://localhost:8080/h2-console”.

h2_database_console

See the below table here:

h2_database_table

Testing API on the Postman
Saving the student data
POST: http://localhost:8080/api/student/save

api_testing_on_postman

Check the table:

h2_database_table

Retrieving the student data
GET: http://localhost:8080/api/student/list

api_testing_on_postman

Retrieving the student data by Id
GET: http://localhost:8080/api/student/1

api_testing_on_postman

Updating the student by Id
PUT: http://localhost:8080/api/student/update/1

api_testing_on_postman

Deleting the student data by Id
DELETE: http://localhost:8080/api/student/delete/1

api_testing_on_postman

Check the table:

h2_database_table

Conclusion

In this topic, we learnt about how to implement CRUD rest API with XML data request and response in the Spring Boot Application.

Leave a Comment