[JavaEE] Implement a REST Endpoint
Posted Answer1215
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[JavaEE] Implement a REST Endpoint相关的知识,希望对你有一定的参考价值。
1. Create a rest folder with JAXRSConfiguration.java:
package com.pluralsight.bookstore.rest; import javax.ws.rs.ApplicationPath; import javax.ws.rs.core.Application; @ApplicationPath("api") public class JAXRSConfiguration extends Application { }
2. Create Endpoint file: BookEndpoint.java:
@Path("/books") public class BookEndpoint { @Inject private BookRepository bookRepository; }
package com.pluralsight.bookstore.rest; import com.pluralsight.bookstore.model.Book; import com.pluralsight.bookstore.repository.BookRepository; import javax.inject.Inject; import javax.validation.constraints.Min; import javax.ws.rs.*; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import java.net.URI; import java.util.List; import static javax.ws.rs.core.MediaType.APPLICATION_JSON; //api/books @Path("/books") public class BookEndpoint { @Inject private BookRepository bookRepository; @POST @Consumes(APPLICATION_JSON) public Response createBook(Book book, @Context UriInfo uriInfo) { book = bookRepository.create(book); URI createedURI = uriInfo.getBaseUriBuilder().path(book.getId().toString()).build(); return Response.created(createedURI).build(); } @GET @Produces(APPLICATION_JSON) public Response getBooks() { List<Book> books = bookRepository.findAll(); if(books.size() == 0) { return Response.noContent().build(); } return Response.ok(books).build(); } @GET @Path("/{id: \\\\d+}") @Produces(APPLICATION_JSON) public Response getBook(@PathParam("id") @Min(1) Long id) { Book book = bookRepository.find(id); if(book == null) { return Response.status(Response.Status.NOT_FOUND).build(); } return Response.ok(book).build(); } // api/books/count @GET @Path("/count")
@Produces(PLAIN_TEXT) public Response countBooks() { Long nbOfBooks = bookRepository.countAll(); if(nbOfBooks == 0) { return Response.noContent().build(); } return Response.ok(nbOfBooks).build(); } @DELETE @Path("/{id : \\\\d+}") public Response deleteBook(Long id) { bookRepository.delete(id); return Response.noContent().build(); } }
以上是关于[JavaEE] Implement a REST Endpoint的主要内容,如果未能解决你的问题,请参考以下文章
Implement a customized pin code input control