JSP vs Servlets
Compare JSP and Servlets directly - how Servlets generate HTML from Java, how JSP embeds Java in HTML, and when to use each.
Introduction
Servlets and JSP solve the same broad problem - generating dynamic web content in Java - but they approach it from opposite directions. A Servlet is Java code that produces HTML. A JSP page is HTML that contains Java code. Understanding this reversal is the key to knowing when to reach for each one.
Servlets: Java Generating HTML
A Servlet is a plain Java class that extends HttpServlet and overrides methods like doGet() or doPost() to handle incoming HTTP requests. Any HTML the Servlet wants to send back must be built manually, usually with a PrintWriter and repeated calls to println() or write().
import java.io.IOException;import java.io.PrintWriter;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;
public class GreetingServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String name = request.getParameter("name");
out.println("<html>"); out.println("<body>"); out.println("<h1>Hello, " + name + "!</h1>"); out.println("</body>"); out.println("</html>"); }}Click Run to see what this code prints.
This works fine for small amounts of markup, but imagine a full page with a navigation bar, a table of 50 rows, a footer, and CSS classes - every single line would need its own println() call, buried inside Java control-flow logic. That quickly becomes unreadable and painful to maintain.
JSP: HTML Embedding Java
JSP flips the arrangement. You write the page mostly as plain HTML, and drop in short pieces of Java exactly where dynamic values are needed.
<%@ page import="javax.servlet.http.HttpServletRequest" %><html><body> <h1>Hello, <%= request.getParameter("name") %>!</h1></body></html>Click Run to see what this code prints.
Both examples produce nearly identical output, but the JSP version is far easier to read as a web page, and far easier for someone comfortable with HTML but less comfortable with Java to edit safely.
Side-by-Side Comparison
| Aspect | Servlet | JSP |
|---|---|---|
| Primary content | Java code | HTML markup |
| Output HTML written by | println()/write() calls | Static markup, untouched |
| Best suited for | Request handling, business logic, control flow | Presenting/formatting the response |
| Readability of large pages | Poor - HTML buried in Java | Good - HTML stays readable |
| Compiled by developer or container | Developer compiles the .java file | Container translates & compiles automatically |
| Typical role in MVC | Controller | View |
When to Use Each
The rule of thumb enterprise Java teams settled on years ago is simple: use a Servlet for logic and control flow, use JSP for presentation.
Use a Servlet When
You need to process form submissions, talk to a database, validate input, manage sessions, or decide which page to show next.
Use JSP When
You need to display data as HTML - tables, forms, formatted text - once the logic has already been handled elsewhere.
Using Them Together
In real applications, Servlets and JSP are almost always used together, not as competitors. A common flow looks like this: a Servlet receives the request, performs any necessary logic (like querying a database), stores the results as a request attribute, and then forwards the request to a JSP page that only handles displaying that data.
request.setAttribute("username", "Asha");request.getRequestDispatcher("/welcome.jsp").forward(request, response);This separation - Servlet as controller, JSP as view - is exactly the classic MVC pattern mentioned in the previous lesson, and it is the pattern most enterprise JSP applications are built around.
Common Mistakes
- Putting heavy business logic and database calls directly inside a JSP file instead of a Servlet.
- Building large HTML pages entirely inside a Servlet using println() calls.
- Treating JSP and Servlets as competing technologies rather than complementary ones.
- Forgetting that request.getRequestDispatcher(...).forward(...) is how control typically passes from Servlet to JSP.
Best Practices
- Keep Servlets focused on logic: reading input, talking to services/databases, deciding what to show.
- Keep JSP focused on presentation: looping over data and formatting it as HTML.
- Pass data from Servlet to JSP using request attributes, then read them with Expression Language in the JSP.
- If a JSP page starts needing complex Java logic, that is usually a sign the logic belongs in a Servlet instead.
Frequently Asked Questions
Neither is universally "better" - they are designed for different jobs. JSP is better for presentation, Servlets are better for logic and control flow.
Yes. Servlets can write any content type, including JSON, since you control the output directly. JSP is specifically oriented toward producing HTML-like markup.
No, and in practice you should not. Most real JSP applications use both together, with Servlets as controllers and JSP pages as views.
Many learners find it useful to see a basic Servlet first to understand HTTP request handling, then move to JSP to see how presentation is cleaner when separated out.
Key Takeaways
- Servlets are Java code that generates HTML output manually.
- JSP is HTML markup with small pieces of embedded Java for dynamic sections.
- Servlets are best for logic and control flow; JSP is best for presentation.
- Real applications typically combine both: Servlet as controller, JSP as view.
- RequestDispatcher.forward() is the standard way to move from a Servlet to a JSP page.
Summary
Servlets and JSP are two sides of the same coin: one optimized for logic, the other for presentation. Knowing when to use each - and how to combine them - is fundamental to writing clean Java web applications. Next, you will set up an actual JSP development environment using Apache Tomcat so you can start running these examples yourself.