Servlet versus JAX-RS
Replace verbose HttpServlet boilerplate with declarative JAX-RS resource classes.
Porównanie kodu
✕ Java EE
@WebServlet("/users")
public class UserServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException {
String id = req.getParameter("id");
res.setContentType("application/json");
res.getWriter().write("{\"id\":\"" + id + "\"}");
}
}
✓ Jakarta EE 8+
@Path("/users")
public class UserResource {
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getUser(
@QueryParam("id") String id) {
return Response.ok(new User(id)).build();
}
}
Widzisz problem z tym kodem? Daj nam znać.
Dlaczego nowoczesne podejście wygrywa
Declarative routing
Annotations define HTTP method, path, and content type instead of imperative if/else dispatch.
Automatic marshalling
Return POJOs directly; the runtime serialises them to JSON or XML based on @Produces.
Easier testing
Resource classes are plain Java objects, testable without a servlet container.
Stare podejście
HttpServlet
Nowoczesne podejście
JAX-RS Resource
Od JDK
11
Poziom trudności
Średniozaawansowany
Wsparcie JDK
Servlet versus JAX-RS
Dostępne
Widely available since Jakarta EE 8 / Java 11
Jak to działa
JAX-RS (Jakarta RESTful Web Services) lets you expose REST endpoints using simple annotations like @GET, @Path, and @Produces. No more manual parsing of request parameters or setting content types on the response — the runtime handles marshalling and routing automatically.
Powiązana dokumentacja