How do I get the JAX-RS @Path of a different resource during a POST?

前端 未结 4 1818
走了就别回头了
走了就别回头了 2021-02-02 15:09

I have two REST classes for a simple web service (Jersey and GlassFish) that involves user resources - one to operate on all users (e.g., a factory for @POSTing) and another on

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-02 16:12

    With the strict REST concept you can make it as one root resource

    @POST   /users        -> CREATE a single user
    @GET    /users        -> READ all users
    @PUT    /users        -> UPDATE (REPLACE) all users @@?
    @DELETE /users        -> DELETE all users @@?
    
    @POST   /users/{id}   -> CREATE a single user's some other child; @@?
    @GET    /users/{id}   -> READ a single user
    @PUT    /users/{id}   -> UPDATE a single user
    @DELETE /users/{id}   -> DELETE a single user
    
    @Path("/users")
    @Stateless
    public class UsersResouce {
    
        // /users
        @POST
        @Consumes({MediaType.APPLICATION-XML, MediaType.APPLICATION-JSON})
        public Response createUser(final User user) {
            // persist the user here
            return Response.created("/" + user.getId()).build();
        }
    
        // /users
        @GET
        @Produces({MediaType.APPLICATION-XML, MediaType.APPLICATION-JSON})
        public Response readUsers() {
            //return all users
        }
    
        // /users/{id}
        @GET
        @Path("/{user_id: \\d+}")
        @Produces({MediaType.APPLICATION-XML, MediaType.APPLICATION-JSON})
        public Response readUser(
            @PathParam("user_id") final Long userId) {
    
            final User persisted = userBean.find(userId);
    
            if (persisted == null) {
                return Response.status(Status.NOT_FOUND).build();
            }
    
            return Response.ok().entity(persisted).build();
        }
    
        // /users/{id}
        @Consumes({MediaType.APPLICATION-XML, MediaType.APPLICATION-JSON})
        @PUT
        @Path("/{user_id: \\d+}")
        public Response updateUser(
            @PathParam("user_id") final Long userId,
            final User mergeable) {
    
            final User persisted = userBean.find(userId);
    
            if (persisted == null) {
                userBean.persist(mergeable);
            } else {
                persist.setName(mergeable.getName());
                userBean.merge(persisted);
            }
    
            return Response.status(Status.NO_CONTENT).build();
        }
    
        // /users/{id}
        @DELETE
        @Path("/{user_id: \\d+}")
        public Response deleteUser(
            @PathParam("user_id") final Long userId) {
    
            userBean.delete(userId);
    
            return Response.status(Status.NO_CONTENT).build();
        }
    
        @EJB
        private UserBean userBean;
    }
    

提交回复
热议问题