• [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(); } }
  • 相关阅读:
    web开发中禁止因为网速慢导致重复提交数据
    margin四个元素的顺序
    js阻止提交表单(post)
    js中DOM集合的动态特性
    js正则表达式中=s.g表示什么意思
    js去掉字符串前后空格的五种方法
    电脑结构和CPU、内存、硬盘三者之间的关系
    mysql——查询练习
    python基础知识14——I/O阻塞非阻塞,同步异步
    Redis主从数据库的安装及主从配置
  • 原文地址:https://www.cnblogs.com/Answer1215/p/9420439.html
Copyright © 2020-2023  润新知