@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中文网其他相关文章!