码迷,mamicode.com
首页 > 编程语言 > 详细

[JavaEE] Implement a REST Endpoint

时间:2018-08-04 23:16:54      阅读:175      评论:0      收藏:0      [点我收藏+]

标签: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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!