Spring Boot Rest XML CRUD example – Web service with XML Request and Response
Technologies used :
- Spring Boot 2.5.4
- Java 11
- Spring Data JPA
- H2DB
- Jackson Dataformat XML 2.10.1
- Maven 3
Project Structure:
– WebConfig implements WebMvcConfigurer. This is where we set the default content type.
– Book data model class corresponds to entity and table books.
– BookRepository is an interface that extends JpaRepository for CRUD methods and custom finder methods. It will be autowired in BookController.
– BookController is a RestController which has request mapping methods for RESTful requests such as: getBookById, createBook, updateBook, deleteBook...
– Configuration for Spring Datasource, JPA & Hibernate in application.properties.
– pom.xml contains dependencies for Spring Boot, Jackson Dataformat XML, JPA & H2DB.
2)Maven/Dependency Management [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.5.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.knf</groupId>
<artifactId>springbootrestxml</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springbootrestxml</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</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>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</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>
Rest Controller
package com.knf.springbootrestxml.controller;
import com.knf.springbootrestxml.model.Book;
import com.knf.springbootrestxml.repository.BookRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@CrossOrigin(origins = "http://localhost:8080")
@RestController
@RequestMapping("/api")
public class BookController {
@Autowired
BookRepository bookRepository;
@GetMapping("/books")
public ResponseEntity<List<Book>> getAllBooks(@RequestParam(required = false)
String title) {
try {
List<Book> books = new ArrayList<Book>();
if (title == null)
bookRepository.findAll().forEach(books::add);
else {
bookRepository.findByTitleContaining(title).forEach(books::add);
}
if (books.isEmpty()) {
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
return new ResponseEntity<>(books, HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@GetMapping("/books/{id}")
public ResponseEntity<Book> getBookById(@PathVariable("id") long id) {
Optional<Book> bookData = bookRepository.findById(id);
if (bookData.isPresent()) {
return new ResponseEntity<>(bookData.get(), HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
@PostMapping("/books")
public ResponseEntity<Book> createBook(@RequestBody Book _book) {
try {
Book book = bookRepository.save(new Book(_book.getTitle(),
_book.getDescription(), false));
return new ResponseEntity<>(book, HttpStatus.CREATED);
} catch (Exception e) {
return new ResponseEntity<>(null, HttpStatus.EXPECTATION_FAILED);
}
}
@PutMapping("/books/{id}")
public ResponseEntity<Book> updateBook(@PathVariable("id") long id,
@RequestBody Book book) {
Optional<Book> bookData = bookRepository.findById(id);
if (bookData.isPresent()) {
Book _book = bookData.get();
_book.setTitle(book.getTitle());
_book.setDescription(book.getDescription());
_book.setPublished(book.isPublished());
return new ResponseEntity<>(bookRepository.save(_book), HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
@DeleteMapping("/books/{id}")
public ResponseEntity<HttpStatus> deleteBook(@PathVariable("id") long id) {
try {
bookRepository.deleteById(id);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
} catch (Exception e) {
return new ResponseEntity<>(HttpStatus.EXPECTATION_FAILED);
}
}
}
Modal class(Book.java)
package com.knf.springbootrestxml.model;
import javax.persistence.*;
@Entity
@Table(name = "books")
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column(name = "title")
private String title;
@Column(name = "description")
private String description;
@Column(name = "isPublished")
private boolean published;
public Book() {
}
public Book(String title, String description, boolean published) {
this.title = title;
this.description = description;
this.published = published;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public boolean isPublished() {
return published;
}
public void setPublished(boolean published) {
this.published = published;
}
@Override
public String toString() {
return "Book{" +
"id=" + id +
", title='" + title + '\'' +
", description='" + description + '\'' +
", published=" + published +
'}';
}
}
Repository Layer(BookRepository)
package com.knf.springbootrestxml.repository;
import java.util.List;
import com.knf.springbootrestxml.model.Book;
import org.springframework.data.jpa.repository.JpaRepository;
public interface BookRepository extends JpaRepository<Book, Long> {
List<Book> findByTitleContaining(String title);
}
WebConfig
package com.knf.springbootrestxml.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 WebConfig implements WebMvcConfigurer {
@Override
public void configureContentNegotiation(final
ContentNegotiationConfigurer configurer) {
configurer.defaultContentType(MediaType.APPLICATION_XML);
}
}
Driver Class(SpringbootrestxmlApplication)
package com.knf.springbootrestxml;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringbootrestxmlApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootrestxmlApplication.class, args);
}
}
Run
$ mvn spring-boot:run