简体   繁体   中英

REST API ArrayList @DELETE

public class BookList {

    public static List<Book> Listing= new ArrayList<Book>();

    Book book = new Book();

    public List<Book> getBooks(){
        Book book1=new Book("1", "Name 1","Author 1", "Text");
        Book book2=new Book("2", "Name 2","Author 2", "Text");
        Book book3=new Book("3",  "Name 3","Author 3", "Text");
        Book book4=new Book("4", "Name 4","Author 4", "Text");


        Listing.add(book1);
        Listing.add(book2);
        Listing.add(book3);
        Listing.add(book4);

        return Listing;

    }

And I have a Main Java Class where @DELETE function is located.

@DELETE
    @Path("/{bookID}")
    @Produces(MediaType.APPLICATION_XML)
    public Response deleteBook(@PathParam("bookiD") int id){
        String output = (bookList.getBook(id));
        return Response.status(200).entity("Hehehe").build(); 
    }

What I want to get is to when I run this @DELETE in Postman is to provide me back with the list of books that are left in the list and exluclude the one that book which ID I put into link: For example localhost:49000/1 - removes book with ID 1 from the list and return back the rest of the books

That is a simple ArrayList delete issue

Like your getBook method, add a deleteBook method and then implement the method that removes book from your list. `list.remove(getBook(id-1)); //

Then in your public Response deleteBookXML(@PathParam("bookID") int id) method, first deleteBook , and instead of returning Response with laughing buddha ( entity("Hehehe") ), as Entity, use bookList as entity.

BookList.list.removeif(x -> x.id.equals(id + "");
return Response.status(200).entity(BookList.list).build(); 

It appeares that your Book object is using Strings as ids?

The above code will use your static list of books and remove a book element with the id equal to the id from the URL.

The code will then return http status 200 with the list of books as entity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM