Search code examples
javajsonlistpostget

GET not showing the objects Posted which is implemented in java dynamic web project


I am implementing(in eclipse) a simple way to put and get using my java api.

The code is as follows:

@Path("/jason")
public class JavajsonRestApi {

    List<Book> bookList = new ArrayList<>();

    @GET
    @Path("/json")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes({MediaType.APPLICATION_JSON})
    public List<Book> getJson() {
        return bookList;
    }

    @POST
    @Path("/json")
    @Produces(MediaType.APPLICATION_JSON)
    public List<Book> postJson(Book book) {
        bookList.add(book);
        return bookList;
    }

}

The bookList is a global variable declared outside the methods. Using post post I am pushing objects to the specified endpoint. Using get I am getting list of objects from the same end-point.

But the GET show empty list despite adding to the list, moreover bookList is global variable here. The GET should show list of books posted.

Why is the weird behavior?

Any help is appreciated.


Solution

  • One of the solutions to this problem I got working was from: https://javabrains.io/courses/javaee_jaxrs/lessons/Implementing-POST-Method/

    The code implementation changes to:

    @Path("/jason")
    public class JavajsonRestApi {
    
    private Booklist  bookList = new Booklist();
    
        @POST
        @Path("/json")
        @Consumes(MediaType.APPLICATION_JSON)
        public Book postJson(Book book) {
          bookList.addBook(book);
          return book;
        }
    
        @GET
        @Path("/json")
        @Produces(MediaType.APPLICATION_JSON)
        public List<Book> getJson() {
            return bookList.getAllBooks();
        }
    }
    

    The Booklist implementation is:

    public class Booklist {
    
    private Map<Long, Book> books = Databaseclasss.getBooks();
    
    public Booklist() {
        books.put(1L, new Book("I","you",1));
        books.put(2L, new Book("me","me",2));
    }
    
    public List<Book> getAllBooks(){
        return new ArrayList<Book>(books.values());
    }
    
    public Book getBook(Long id) {
        return books.get(id);
    }
    
    public Book addBook(Book book) {
        book.setid(books.size()+1);
        books.put(book.getId().longValue(), book);
        return book;
    }
    
    public Book removeBook(Long id) {
        return books.remove(id);
    }
    }
    

    The Databaseclass implementation is as follows:

    public class Databaseclasss {
    
    private static Map<Long, Book> books= new HashMap<>();
    
    public static Map<Long, Book> getBooks(){
        return books;
    }
    }
    

    I hope this is helpful to others as well.

    Thank you Laurens and Stafs for valuable responses.