标签:util end style sum long text val net 图片
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") 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
标签:util end style sum long text val net 图片
原文地址:https://www.cnblogs.com/Answer1215/p/9420439.html