@Path("/users") public class UserResource { @GET @Produces(MediaType.APPLICATioN_JSON) public List<User> getAllUsers() { return userService.getAllUsers(); } @POST @Consumes(MediaType.APPLICATION_jsON) public User createUser(User user) { return userService.createUser(user); } @PUT @Path("/{id}") @Consumes(MediaType.APPLICATION_JSON) public User updateUser(@PathParam("id") Long id, User user) { return userService.updateUser(id, user); } @DELETE @Path("/{id}") public void deleteUser(@PathParam("id") Long id) { userService.deleteUser(id); } }
public class LoggingFilter implements Filter { @Override public void doFilter(FilterChain chain, Request request, Response response) throws IOException, ServletException { long startTime = System.currentTimeMillis(); chain.doFilter(request, response); long endTime = System.currentTimeMillis(); logger.info("Request {} {} took {} ms", request.getMethod(), request.getPath(), endTime - startTime); } }
public class UserResourceConfig extends ResourceConfig { public UserResourceConfig() { reGISter(UserResource.class); register(LoggingFilter.class); } }
public class UserResource { @Inject private UserService userService; @GET @Produces(MediaType.APPLICATION_JSON) public List<User> getAllUsers() { return userService.getAllUsers(); } }
透過遵循這些最佳實踐,可以幫助開發人員創建更出色且有效率的RESTful API。
以上是Java Jersey框架的最佳實踐,讓你的RESTful API更出色的詳細內容。更多資訊請關注PHP中文網其他相關文章!