Back to the 2024 paper

Module III — Basics of Web Programming

20245m

Compare Servlets and JSP regarding their functionality, advantages, and limitations. In what scenarios would you choose one over the other?

Worked SolutionAI Assisted

Servlets vs JSP

Servlet: a Java class that runs on a server (servlet container such as Tomcat), receives HTTP requests, and generates responses. It is Java code with HTML embedded in out.println().

JSP (JavaServer Pages): a text page that is HTML with Java embedded (scriptlets, expressions, JSTL, EL). The container translates a JSP into a servlet and compiles it on first request, so JSP is built on servlets.

// Servlet
public class HelloServlet extends HttpServlet {
  protected void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
    res.setContentType("text/html");
    res.getWriter().println("<h1>Hello " + req.getParameter("name") + "</h1>");
  }
}
<%-- JSP --%>
<h1>Hello <%= request.getParameter("name") %></h1>

Comparison

Basis Servlet JSP
Nature Java class with HTML in strings HTML page with Java tags
Best for Logic, controllers, processing Presentation, views
Ease of writing Harder for UI; markup is hard to edit Easier for designers; natural HTML
Compilation Compiled manually Auto-translated and compiled on first request
Maintenance Changing HTML needs recompiling Java Edit the page directly
Built-in objects Must be obtained explicitly Implicit objects (request, session, out)
Performance Slightly faster on first request First request slower (translation), then equal

Advantages and limitations

Servlets

  • Advantages: full control over request handling, efficient (one thread per request), platform independent, good for controllers, filters, and APIs.
  • Limitations: presentation code is cumbersome and mixes HTML into Java; designers cannot edit pages easily.

JSP

  • Advantages: simple and quick UI development, easy for web designers, tag libraries (JSTL) reduce Java code, automatic recompilation.
  • Limitations: heavy scriptlet logic makes pages messy and hard to debug and test; not suitable for complex business logic.

When to choose which

  • Use Servlets for controllers, request processing, form handling, authentication, file upload, REST endpoints, and business logic.
  • Use JSP for pages that mostly display dynamic data (views, reports, templates).
  • Best practice (MVC): servlet as controller, JSP as view, JavaBeans/services as the model. The servlet processes the request, then forwards to a JSP: request.getRequestDispatcher("result.jsp").forward(req, res);

Similar questions

Budget AppAndroid App

Pocketly on Android

Log daily food, travel, and hostel expenses instantly. Set monthly spending limits and see where your money goes without complex spreadsheets.